From e19ae4b66c8021a19c77e6c494bfffbeb699561f Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Tue, 3 Sep 2013 17:42:45 -0400 Subject: [PATCH 01/48] minimum working example for Princeton Trivista spectrometer --- .../drivers/princetoninstruments/trivista.py | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 lantz/drivers/princetoninstruments/trivista.py diff --git a/lantz/drivers/princetoninstruments/trivista.py b/lantz/drivers/princetoninstruments/trivista.py new file mode 100644 index 0000000..789b6e5 --- /dev/null +++ b/lantz/drivers/princetoninstruments/trivista.py @@ -0,0 +1,51 @@ +# -*- coding: utf-8 -*- +""" + lantz.drivers.princetoninstruments.trivista + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Trivista Spectrometer. + + :copyright: 2013 by Lantz Authors, see AUTHORS for more details. + :license: BSD, see LICENSE for more details. +""" + +from lantz import Action, Feat, DictFeat +from lantz.serial import SerialDriver + +class SerialTemplate(SerialDriver): + """Template for drivers connecting via serial port. + """ + + ENCODING = 'ascii' + + RECV_TERMINATION = ' ok\r\n' + SEND_TERMINATION = '\r' + + @Feat() + def model(self): + """Returns model number of the monochromator + """ + return self.query('model') + +if __name__ == '__main__': + import argparse + import lantz.log + + parser = argparse.ArgumentParser(description='Test Kentech HRI') + parser.add_argument('-i', '--interactive', action='store_true', + default=False, help='Show interactive GUI') + parser.add_argument('-p', '--port', type=str, default='17', + help='Serial port to connect to') + + args = parser.parse_args() + lantz.log.log_to_socket(lantz.log.DEBUG) + print(args.port) + with SerialTemplate(args.port) as inst: + if args.interactive: + from lantz.ui.qtwidgets import start_test_app + start_test_app(inst) + else: + print('Non interactive mode') + print(inst.model) + + From 926dd1531356bafcf38aa16a99542229b602d979 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Wed, 4 Sep 2013 11:22:54 -0400 Subject: [PATCH 02/48] trivista add query commands --- .../drivers/princetoninstruments/trivista.py | 59 ++++++++++++++++++- 1 file changed, 57 insertions(+), 2 deletions(-) diff --git a/lantz/drivers/princetoninstruments/trivista.py b/lantz/drivers/princetoninstruments/trivista.py index 789b6e5..d3f9c13 100644 --- a/lantz/drivers/princetoninstruments/trivista.py +++ b/lantz/drivers/princetoninstruments/trivista.py @@ -27,11 +27,60 @@ def model(self): """ return self.query('model') + @Feat() + def serialNo(self): + """Returns serial number of the monochromator + """ + return self.query('serial') + + @Feat() + def mono_eestatus(self): + """Returns setup and grating calibration parameters for all gratings + """ + return self.query('mono-eestatus') + + @Feat() + def turret(self): + """Returns the correctly installed turret numbered 1 - 3 + """ + return self.query('?turret') + + @Feat() + def gratings(self): + """Returns the list of installed gratings with position groove density and blaze. The present grating is specified with an arrow. + """ + return self.query('?gratings') + + @Feat() + def grating(self): + """Returns the number of gratings presently being used numbered 1 - 9. + """ + return self.query('?grating') + + @Feat() + def nm_min(self): + """ Returns present scan rate in nm/min to 0.01 nm/min resolution with units nm/min. + """ + return self.query('?nm/min') + + @Feat() + def mono_done(self): + """Used with >NM command to determine if monochromator has reached the destination. Returns 0 if move is not complete, 1 if move is complete. + """ + return self.query('mono-?done') + + @Feat() + def nm(self): + """ Returns present wavelength in nm to 0.01 nm resolution with +units nm appended. + """ + return self.query('?nm') + if __name__ == '__main__': import argparse import lantz.log - parser = argparse.ArgumentParser(description='Test Kentech HRI') + parser = argparse.ArgumentParser(description='Princeton Instrument Trivista') parser.add_argument('-i', '--interactive', action='store_true', default=False, help='Show interactive GUI') parser.add_argument('-p', '--port', type=str, default='17', @@ -47,5 +96,11 @@ def model(self): else: print('Non interactive mode') print(inst.model) - + print(inst.serialNo) + print(inst.mono_eestatus) + print(inst.turret) + print(inst.gratings) + print(inst.grating) + print(inst.nm_min) + print(inst.nm) From efc20554f2a69695b2a05c44d07fba9c50652f5b Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Wed, 4 Sep 2013 11:35:09 -0400 Subject: [PATCH 03/48] trivista: custom query --- lantz/drivers/princetoninstruments/trivista.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/lantz/drivers/princetoninstruments/trivista.py b/lantz/drivers/princetoninstruments/trivista.py index d3f9c13..9db8c3a 100644 --- a/lantz/drivers/princetoninstruments/trivista.py +++ b/lantz/drivers/princetoninstruments/trivista.py @@ -74,7 +74,13 @@ def nm(self): """ Returns present wavelength in nm to 0.01 nm resolution with units nm appended. """ - return self.query('?nm') + return self.query('?nm') + + def query(self, command, *, send_args=(None, None), recv_args=(None, None)): + answer = super().query(command, send_args=send_args, recv_args=recv_args) + if answer == 'ERROR': + raise InstrumentError + return answer.strip() if __name__ == '__main__': import argparse @@ -104,3 +110,4 @@ def nm(self): print(inst.nm_min) print(inst.nm) + print('model: {}'.format(inst.model)) From 6bc407a44759822c0e120e6da4ac45e5e261024c Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Thu, 5 Sep 2013 13:30:00 -0400 Subject: [PATCH 04/48] initial commit for Newport842PE --- lantz/drivers/newport/842PE.py | 190 ++++++++++++++++++++++++++++++ lantz/drivers/newport/__init__.py | 19 +++ 2 files changed, 209 insertions(+) create mode 100644 lantz/drivers/newport/842PE.py create mode 100644 lantz/drivers/newport/__init__.py diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py new file mode 100644 index 0000000..d235795 --- /dev/null +++ b/lantz/drivers/newport/842PE.py @@ -0,0 +1,190 @@ +# -*- coding: utf-8 -*- +""" + lantz.drivers.newport.842PE + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Newport 842-PE powermeter + + :copyright: 2013 by Lantz Authors, see AUTHORS for more details. + :license: BSD, see LICENSE for more details. +""" +import time +from lantz import Action, Feat, DictFeat +from lantz.serial import SerialDriver + +class Newport842PE(SerialDriver): + """Newport 842-PE powermeter + """ + + ENCODING = 'ascii' + + RECV_DONE = 'ACK\r\n' #this string is return by the device when the action is done + RECV_TERMINATION = '\r\n' + SEND_TERMINATION = '\r\n' + + BAUDRATE = 115200 + BYTESIZE = 8 + PARITY = 'none' + STOPBITS = 1 + +#Display commands + + @Action(values={'real-time':0, 'histogram':1, 'statistic':2, 'needle':3, 'lineplot':4}) + def sdu(self, value): + """This command is used to change the device’s on-screen display mode. + """ + self.sendCommand('*sdu {}'.format(value)) + + @Action(values=set(('auto', '1p', '3p', '10p', '30p', '100p', '300p', '1n', '3n', '10n', '30n', '100n', '300n', '1u', '3u', '10u', '30u', '100u', '300u', '1m', '3m', '10m', '30m', '100m', '300m', '1', '3', '10', '30', '100', '300', '1k', '3k', '10k', '30k', '100k', '300k', '1M', '3M', '10M', '30M', '100M', '300M',))) + def ssa(self, value): + """This command is used to force the display of the current data into a specific range. + """ + self.sendCommand('*ssa {}'.format(value)) + + @Action(values={True:1, False:0}) + def dbu(self, value): + """This command changes the on-screen display unit to dBm. + """ + self.sendCommand('*dbu {}'.format(value)) + + @Action(values={True:1, False:0}) + def shl(self, value): + """This command is used to add significant digits to the on-screen reading. + """ + self.sendCommand('*shl {}'.format(value)) + +#MEASUREMENT COMMANDS - DATA ACQUISITION + + @Feat() + def cvu(self): + """This command is used to query the value that is currently being displayed on the device’s screen. The value is displayed in Watts or in Joules (not in dBm). + """ + result = self.query('*cvu') + return float(result.replace('Current Value:','').strip()) + + @Feat(values={False:'New Data Not Available', True:'New Data Available'}) + def nvu(self): + """This command is used to check whether a new value is available from the device. Though optional, its use is recommended when used with single pulse operations. + """ + return self.query('*nvu') + + @Feat() + def vsu(self): + """This command is used to read all the statistics data, provided that the device has previously been set into statistic mode. + """ + return self.query('*vsu') + + @Action(values={'stop':0, 'start raw':1, 'start saving':2, 'save both':3,}) + def Log(self, value): + """This command is used to log data on the 842-PE meter’s EEPROM. + """ + self.sendCommand('*log {}'.format(value)) + + @Feat() + def fdl(self): + """This command is used to retrieve a logged file from the device. + """ + return self.query('*fdl 1') + +#MEASUREMENT COMMANDS - SETUP + + @Feat() + def cau(self): + """This command is used to send data to the serial port according to the data sampling setting. The maximum transfer speed is 200Hz. + """ + return self.query('*cau') + +#MEASUREMENT COMMANDS - MEASUREMENT CONTROL +#INSTRUMENT AND DETECTOR INFORMATION COMMANDS + + @Feat() + def ver(self): + """This command is used to query the device to get information about the +firmware version and the device type. + """ + return self.query('*ver') + +#INSTRUMENT CONTROL COMMANDS + + @Action() + def bkl(self,parameter=0): + """ + """ + self.query('*bkl {}'.format(parameter)) + +#COMMUNICATIONS COMMANDS + + + def query(self, command, *, send_args=(None, None), recv_args=(None, None)): + answer = super().query(command, send_args=send_args, recv_args=recv_args) + if answer == 'ERROR': + raise InstrumentError + return answer + + def sendCommand(self, s): + self.send(s) + self.waitInstrumentDone() + + def waitInstrumentDone(self, termination=None, encoding=None, recv_chunk=None): + """Wait for command completion by instrument. + + :param termination: termination character (overrides class default) + :type termination: str + :param encoding: encoding to transform bytes to string (overrides class default) + :param recv_chunk: number of bytes to receive (overrides class default) + :return: string encoded from received bytes + """ + + termination = termination or self.RECV_DONE + encoding = encoding or self.ENCODING + recv_chunk = recv_chunk or self.RECV_CHUNK + + if not termination: + return str(self.raw_recv(recv_chunk), encoding) + + if self.TIMEOUT is None or self.TIMEOUT < 0: + stop = float('+inf') + else: + stop = time.time() + self.TIMEOUT + + received = self._received + while not termination in received: + if time.time() > stop: + raise LantzTimeoutError + raw_received = self.raw_recv(recv_chunk) + received += str(raw_received, encoding) + + self.log_debug('Received {!r} (len={})', received, len(received)) + +if __name__ == '__main__': + import argparse + import lantz.log + + parser = argparse.ArgumentParser(description='Newport 842-PE powermeter') + parser.add_argument('-i', '--interactive', action='store_true', + default=False, help='Show interactive GUI') + parser.add_argument('-p', '--port', type=str, default='17', + help='Serial port to connect to') + + args = parser.parse_args() + lantz.log.log_to_screen(lantz.log.DEBUG) + with Newport842PE(args.port) as inst: + if args.interactive: + from lantz.ui.qtwidgets import start_test_app + start_test_app(inst) + else: + print('Non interactive mode') + print('display mode: real-time') + inst.sdu('real-time') + print(inst.ver) + inst.Log('stop') + dataAvailable = inst.nvu + if inst.nvu: + print(inst.cvu) +# print(inst.fdl) #buggy +# print(inst.cau) #buggy + inst.ssa('100m') + inst.bkl(1) + inst.dbu(False) + inst.shl(False) + diff --git a/lantz/drivers/newport/__init__.py b/lantz/drivers/newport/__init__.py new file mode 100644 index 0000000..6da906c --- /dev/null +++ b/lantz/drivers/newport/__init__.py @@ -0,0 +1,19 @@ +# -*- coding: utf-8 -*- +""" + lantz.drivers.newport + ~~~~~~~~~~~~~~~~~~~ + + :company: Newport + :description: + :website: http://www.newport.com + + ---- + + :copyright: 2013 by Lantz Authors, see AUTHORS for more details. + :license: BSD, see LICENSE for more details. +""" + +from .842PE import 842PE + +__all__ = ['842PE',] + From a8f77b4d04b55c5d81e8dbdd23766ce86b4e3655 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Thu, 5 Sep 2013 13:35:46 -0400 Subject: [PATCH 05/48] remove contributions from trivista --- .../drivers/princetoninstruments/trivista.py | 113 ------------------ 1 file changed, 113 deletions(-) delete mode 100644 lantz/drivers/princetoninstruments/trivista.py diff --git a/lantz/drivers/princetoninstruments/trivista.py b/lantz/drivers/princetoninstruments/trivista.py deleted file mode 100644 index 9db8c3a..0000000 --- a/lantz/drivers/princetoninstruments/trivista.py +++ /dev/null @@ -1,113 +0,0 @@ -# -*- coding: utf-8 -*- -""" - lantz.drivers.princetoninstruments.trivista - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - Trivista Spectrometer. - - :copyright: 2013 by Lantz Authors, see AUTHORS for more details. - :license: BSD, see LICENSE for more details. -""" - -from lantz import Action, Feat, DictFeat -from lantz.serial import SerialDriver - -class SerialTemplate(SerialDriver): - """Template for drivers connecting via serial port. - """ - - ENCODING = 'ascii' - - RECV_TERMINATION = ' ok\r\n' - SEND_TERMINATION = '\r' - - @Feat() - def model(self): - """Returns model number of the monochromator - """ - return self.query('model') - - @Feat() - def serialNo(self): - """Returns serial number of the monochromator - """ - return self.query('serial') - - @Feat() - def mono_eestatus(self): - """Returns setup and grating calibration parameters for all gratings - """ - return self.query('mono-eestatus') - - @Feat() - def turret(self): - """Returns the correctly installed turret numbered 1 - 3 - """ - return self.query('?turret') - - @Feat() - def gratings(self): - """Returns the list of installed gratings with position groove density and blaze. The present grating is specified with an arrow. - """ - return self.query('?gratings') - - @Feat() - def grating(self): - """Returns the number of gratings presently being used numbered 1 - 9. - """ - return self.query('?grating') - - @Feat() - def nm_min(self): - """ Returns present scan rate in nm/min to 0.01 nm/min resolution with units nm/min. - """ - return self.query('?nm/min') - - @Feat() - def mono_done(self): - """Used with >NM command to determine if monochromator has reached the destination. Returns 0 if move is not complete, 1 if move is complete. - """ - return self.query('mono-?done') - - @Feat() - def nm(self): - """ Returns present wavelength in nm to 0.01 nm resolution with -units nm appended. - """ - return self.query('?nm') - - def query(self, command, *, send_args=(None, None), recv_args=(None, None)): - answer = super().query(command, send_args=send_args, recv_args=recv_args) - if answer == 'ERROR': - raise InstrumentError - return answer.strip() - -if __name__ == '__main__': - import argparse - import lantz.log - - parser = argparse.ArgumentParser(description='Princeton Instrument Trivista') - parser.add_argument('-i', '--interactive', action='store_true', - default=False, help='Show interactive GUI') - parser.add_argument('-p', '--port', type=str, default='17', - help='Serial port to connect to') - - args = parser.parse_args() - lantz.log.log_to_socket(lantz.log.DEBUG) - print(args.port) - with SerialTemplate(args.port) as inst: - if args.interactive: - from lantz.ui.qtwidgets import start_test_app - start_test_app(inst) - else: - print('Non interactive mode') - print(inst.model) - print(inst.serialNo) - print(inst.mono_eestatus) - print(inst.turret) - print(inst.gratings) - print(inst.grating) - print(inst.nm_min) - print(inst.nm) - - print('model: {}'.format(inst.model)) From a95253b69bc7447a0ae7ad83fe48ada08c45fa0c Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Thu, 5 Sep 2013 14:55:58 -0400 Subject: [PATCH 06/48] add commands --- lantz/drivers/newport/842PE.py | 61 +++++++++++++++++++++++++++++++--- 1 file changed, 57 insertions(+), 4 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index d235795..d0fb90a 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -80,30 +80,76 @@ def Log(self, value): """ self.sendCommand('*log {}'.format(value)) + #Buggy @Feat() def fdl(self): """This command is used to retrieve a logged file from the device. """ return self.query('*fdl 1') -#MEASUREMENT COMMANDS - SETUP - + #Buggy @Feat() def cau(self): """This command is used to send data to the serial port according to the data sampling setting. The maximum transfer speed is 200Hz. """ return self.query('*cau') +#MEASUREMENT COMMANDS - SETUP + + def swa(self): + """This command is used to specify the wavelength being used on the detector. + """ + self.sendCommand('*swa {}'.format(value)) + + @Action(values={True:1, False:0}) + def atu(self,value): + """This command is used to adjust the processing of the meter with the readings of the detector, depending on whether the detector is using an external attenuator or not. + """ + self.sendCommand('*atu {}'.format(value)) + + #Buggy +# @Action(values=set((1,2,))) +# def smu(self,values,multiplier): +# """This command is used to set the value of the multipliers. +# """ +# self.sendCommand('*smu {0} {1}'.format(value,multiplier)) + #MEASUREMENT COMMANDS - MEASUREMENT CONTROL + +# def (self): +# """ +# """ +# return self.query('*') + #INSTRUMENT AND DETECTOR INFORMATION COMMANDS @Feat() def ver(self): - """This command is used to query the device to get information about the -firmware version and the device type. + """This command is used to query the device to get information about the firmware version and the device type. """ return self.query('*ver') + @Feat() + def hea(self): + """Model of the current head + """ + return self.query('*hea') + + #buggy (return many \n\r) + @Feat() + def sta(self): + """This command is used to view data that is relevant to the current detector head. + """ + return self.query('*sta') + + @Feat() + def bat(self): + """This command is used to query the device’s remaining battery power. + """ + return self.query('*bat') + + #clk + #INSTRUMENT CONTROL COMMANDS @Action() @@ -188,3 +234,10 @@ def waitInstrumentDone(self, termination=None, encoding=None, recv_chunk=None): inst.dbu(False) inst.shl(False) +# print(inst.sta) + print(inst.hea) + print(inst.bat) +# print(inst.sta) + + + From 98ee2435cf83bc52b448daed7b70119d13600cdb Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Thu, 5 Sep 2013 16:37:28 -0400 Subject: [PATCH 07/48] add commands --- lantz/drivers/newport/842PE.py | 68 ++++++++++++++++++++++++++++++---- 1 file changed, 60 insertions(+), 8 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index d0fb90a..63cbb76 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -108,18 +108,59 @@ def atu(self,value): self.sendCommand('*atu {}'.format(value)) #Buggy +#how to limit input values for one parameter but not the other? # @Action(values=set((1,2,))) # def smu(self,values,multiplier): # """This command is used to set the value of the multipliers. # """ # self.sendCommand('*smu {0} {1}'.format(value,multiplier)) -#MEASUREMENT COMMANDS - MEASUREMENT CONTROL - -# def (self): + #Buggy +#how to limit input values for one parameter but not the other? +# @Action(values=set((1,2,))) +# def sou(self,values,multiplier): # """ # """ -# return self.query('*') +# self.sendCommand('*sou {0} {1}'.format(value,multiplier)) + + def rds(self): + """This command is used to read the current data sampling settings. + """ + return self.query('*rds') + + #DSU + + @Action() + def tla(self, value=True): + """This command sets the internal trigger level when using the device in energy reading mode. + """ + self.query('*tla {}%'.format(value)) + +#MEASUREMENT COMMANDS - MEASUREMENT CONTROL + + @Action(values={'disable':0, 'enable':1, 'reset':2}) + def esu(self, value=True): + """This command is used start, stop and reset the statistics calculating process on the data currently being acquisitioned. + """ + self.sendCommand('*esu {}'.format(value)) + + @Action(values={True:1, False:0}) + def sca(self,value): + """ + """ + self.sendCommand('*sca {}'.format(value)) + + @Action(values={True:1, False:0}) + def eaa(self,value): + """ + """ + self.sendCommand('*eaa {}'.format(value)) + + @Action(values={True:1, False:0}) + def eoa(self,value): + """ + """ + self.sendCommand('*eoa {}'.format(value)) #INSTRUMENT AND DETECTOR INFORMATION COMMANDS @@ -152,14 +193,25 @@ def bat(self): #INSTRUMENT CONTROL COMMANDS - @Action() - def bkl(self,parameter=0): + @Action(values={True:1, False:0}) + def bkl(self, value=True): + """This command is used to turn the backlight of the device display on or off. """ + self.query('*bkl {}'.format(value)) + + @Action(values={True:1, False:0}) + def ano(self, value=True): + """This command is used to enable or disable the output of the current value on the analog port of the meter. """ - self.query('*bkl {}'.format(parameter)) + self.query('*ano {}'.format(value)) #COMMUNICATIONS COMMANDS + @Action(values=set((2400, 9600, 14400, 19200, 38400, 155200))) + def brs(self, value=True): + """This command is used to change the current baud rate of the serial port of the device. + """ + self.sendCommand('*brs {}'.format(value)) def query(self, command, *, send_args=(None, None), recv_args=(None, None)): answer = super().query(command, send_args=send_args, recv_args=recv_args) @@ -238,6 +290,6 @@ def waitInstrumentDone(self, termination=None, encoding=None, recv_chunk=None): print(inst.hea) print(inst.bat) # print(inst.sta) - + inst.eoa(True) From 8c5bbd5f0ced7af62eb50a00b2cdda9ea221c577 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Thu, 5 Sep 2013 16:39:22 -0400 Subject: [PATCH 08/48] correct some Action --- lantz/drivers/newport/842PE.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 63cbb76..6047d0f 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -134,7 +134,7 @@ def rds(self): def tla(self, value=True): """This command sets the internal trigger level when using the device in energy reading mode. """ - self.query('*tla {}%'.format(value)) + self.sendCommand('*tla {}%'.format(value)) #MEASUREMENT COMMANDS - MEASUREMENT CONTROL @@ -197,13 +197,13 @@ def bat(self): def bkl(self, value=True): """This command is used to turn the backlight of the device display on or off. """ - self.query('*bkl {}'.format(value)) + self.sendCommand('*bkl {}'.format(value)) @Action(values={True:1, False:0}) def ano(self, value=True): """This command is used to enable or disable the output of the current value on the analog port of the meter. """ - self.query('*ano {}'.format(value)) + self.sendCommand('*ano {}'.format(value)) #COMMUNICATIONS COMMANDS From 4f3cf3d8e82863d99653502d41dea0562529ae80 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Thu, 5 Sep 2013 17:13:16 -0400 Subject: [PATCH 09/48] fix buggy commands --- lantz/drivers/newport/842PE.py | 37 +++++++++++++++++----------------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 6047d0f..c190e70 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -106,22 +106,18 @@ def atu(self,value): """This command is used to adjust the processing of the meter with the readings of the detector, depending on whether the detector is using an external attenuator or not. """ self.sendCommand('*atu {}'.format(value)) + + @Action(values=(set((1,2,)), None)) + def smu(self,value,multiplier): + """This command is used to set the value of the multipliers. + """ + self.sendCommand('*smu {0} {1}'.format(value,multiplier)) - #Buggy -#how to limit input values for one parameter but not the other? -# @Action(values=set((1,2,))) -# def smu(self,values,multiplier): -# """This command is used to set the value of the multipliers. -# """ -# self.sendCommand('*smu {0} {1}'.format(value,multiplier)) - - #Buggy -#how to limit input values for one parameter but not the other? -# @Action(values=set((1,2,))) -# def sou(self,values,multiplier): -# """ -# """ -# self.sendCommand('*sou {0} {1}'.format(value,multiplier)) + @Action(values=(set((1,2,)), None)) + def sou(self,value,multiplier): + """This command is used to set the value of the offsets. + """ + self.sendCommand('*sou {0} {1}'.format(value,multiplier)) def rds(self): """This command is used to read the current data sampling settings. @@ -176,12 +172,16 @@ def hea(self): """ return self.query('*hea') - #buggy (return many \n\r) + #The device is a bit buggy for this one as it return the info with 3 \n\r. So the hack here repare it. @Feat() def sta(self): """This command is used to view data that is relevant to the current detector head. """ - return self.query('*sta') + out = '' + out += self.query('*sta') + out += '\t{}'.format(self.recv()) + out += '\t{}'.format(self.recv()) + return out @Feat() def bat(self): @@ -291,5 +291,4 @@ def waitInstrumentDone(self, termination=None, encoding=None, recv_chunk=None): print(inst.bat) # print(inst.sta) inst.eoa(True) - - + inst.sta From b73bc86658099a12fdfa736326664b1cc1618b2a Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Thu, 5 Sep 2013 18:12:29 -0400 Subject: [PATCH 10/48] add dsu and clk --- lantz/drivers/newport/842PE.py | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index c190e70..cba3218 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -119,12 +119,21 @@ def sou(self,value,multiplier): """ self.sendCommand('*sou {0} {1}'.format(value,multiplier)) + @Feat() def rds(self): """This command is used to read the current data sampling settings. """ return self.query('*rds') - #DSU + SampleRateUnit = {'second':0, 'minute':1, 'hour':2, 'day':3, '%':4} + SamplePeriodUnit = {'second':0, 'minute':1, 'hour':2, 'day':3, 'week':4, 'pulse':5} + TotalDurationUnit = {'sample':0, 'second':1, 'minute':2, 'hour':3, 'day':4, 'week':5, 'continuous':6, 'predefinded':7} + TimeStamp = {True:1, False:0} + @Action(values=(None, SampleRateUnit, None, SamplePeriodUnit, None, TotalDurationUnit, TimeStamp,)) + def dsu(self, sampleRate, sampleRateUnit, samplePeriod, samplePeriodUnit, totalDuration, totalDurationUnit, timeStamp,): + """ + """ + self.sendCommand('*dsu {} {} {} {} {} {} {}'.format(sampleRate, sampleRateUnit, samplePeriod, samplePeriodUnit, totalDuration, totalDurationUnit, timeStamp,)) @Action() def tla(self, value=True): @@ -152,7 +161,7 @@ def eaa(self,value): """ self.sendCommand('*eaa {}'.format(value)) - @Action(values={True:1, False:0}) + @Action(values={'off':0, 'on':1, 'undo':2}) def eoa(self,value): """ """ @@ -189,7 +198,18 @@ def bat(self): """ return self.query('*bat') - #clk + day = set(range(1,32)) + month = set(range(1,13)) + year = set(range(1970,3000)) + hour = set(range(24)) + minute = set(range(59)) + second = set(range(59)) + AMPM = {'AM':0, 'PM':1} + @Action(values=(day, month, year, hour, minute, second, AMPM,)) + def clk(self, Day, Month, Year, Hour, Minute, Second, aMPM,): + """ + """ + self.sendCommand('*clk {} {} {} {} {} {} {}'.format(Day, Month, Year, Hour, Minute, Second, aMPM,)) #INSTRUMENT CONTROL COMMANDS @@ -290,5 +310,8 @@ def waitInstrumentDone(self, termination=None, encoding=None, recv_chunk=None): print(inst.hea) print(inst.bat) # print(inst.sta) - inst.eoa(True) - inst.sta + inst.eoa('on') + #inst.sta + #inst.clk(5,9,2013,17,58,00,'PM') + inst.dsu(1,'second', 10,'second', 1,'sample', True) + print(inst.rds) From 3c0bb528f4c5fb7f69fb261ee3f6e943105a7755 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Thu, 5 Sep 2013 13:30:00 -0400 Subject: [PATCH 11/48] initial commit for Newport 842-PE --- lantz/drivers/newport/842PE.py | 325 ++++++++++++++++++ lantz/drivers/newport/__init__.py | 19 + .../drivers/princetoninstruments/trivista.py | 113 ------ 3 files changed, 344 insertions(+), 113 deletions(-) create mode 100644 lantz/drivers/newport/842PE.py create mode 100644 lantz/drivers/newport/__init__.py delete mode 100644 lantz/drivers/princetoninstruments/trivista.py diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py new file mode 100644 index 0000000..687afbc --- /dev/null +++ b/lantz/drivers/newport/842PE.py @@ -0,0 +1,325 @@ +# -*- coding: utf-8 -*- +""" + lantz.drivers.newport.842PE + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Newport 842-PE powermeter + + :copyright: 2013 by Lantz Authors, see AUTHORS for more details. + :license: BSD, see LICENSE for more details. +""" +import time +from lantz import Action, Feat, DictFeat +from lantz.serial import SerialDriver + +class Newport842PE(SerialDriver): + """Newport 842-PE powermeter + """ + + ENCODING = 'ascii' + + RECV_DONE = 'ACK\r\n' #this string is return by the device when the action is done + RECV_TERMINATION = '\r\n' + SEND_TERMINATION = '\r\n' + + BAUDRATE = 115200 + BYTESIZE = 8 + PARITY = 'none' + STOPBITS = 1 + +#Display commands + + @Action(values={'real-time':0, 'histogram':1, 'statistic':2, 'needle':3, 'lineplot':4}) + def sdu(self, value): + """This command is used to change the device’s on-screen display mode. + """ + self.sendCommand('*sdu {}'.format(value)) + + @Action(values=set(('auto', '1p', '3p', '10p', '30p', '100p', '300p', '1n', '3n', '10n', '30n', '100n', '300n', '1u', '3u', '10u', '30u', '100u', '300u', '1m', '3m', '10m', '30m', '100m', '300m', '1', '3', '10', '30', '100', '300', '1k', '3k', '10k', '30k', '100k', '300k', '1M', '3M', '10M', '30M', '100M', '300M',))) + def ssa(self, value): + """This command is used to force the display of the current data into a specific range. + """ + self.sendCommand('*ssa {}'.format(value)) + + @Action(values={True:1, False:0}) + def dbu(self, value): + """This command changes the on-screen display unit to dBm. + """ + self.sendCommand('*dbu {}'.format(value)) + + @Action(values={True:1, False:0}) + def shl(self, value): + """This command is used to add significant digits to the on-screen reading. + """ + self.sendCommand('*shl {}'.format(value)) + +#MEASUREMENT COMMANDS - DATA ACQUISITION + + @Feat() + def cvu(self): + """This command is used to query the value that is currently being displayed on the device’s screen. The value is displayed in Watts or in Joules (not in dBm). + """ + result = self.query('*cvu') + return float(result.replace('Current Value:','').strip()) + + @Feat(values={False:'New Data Not Available', True:'New Data Available'}) + def nvu(self): + """This command is used to check whether a new value is available from the device. Though optional, its use is recommended when used with single pulse operations. + """ + return self.query('*nvu') + + @Feat() + def vsu(self): + """This command is used to read all the statistics data, provided that the device has previously been set into statistic mode. + """ + return self.query('*vsu') + + @Action(values={'stop':0, 'start raw':1, 'start saving':2, 'save both':3,}) + def Log(self, value): + """This command is used to log data on the 842-PE meter’s EEPROM. + """ + self.sendCommand('*log {}'.format(value)) + + #Buggy + @Action() + def fdl(self, value): + """This command is used to retrieve a logged file from the device. + """ +# return self.query('*fdl {}'.format(value)) + return self.query('*fdl 0') + + #Buggy + @Feat() + def cau(self): + """This command is used to send data to the serial port according to the data sampling setting. The maximum transfer speed is 200Hz. + """ + return self.query('*cau') + +#MEASUREMENT COMMANDS - SETUP + + def swa(self): + """This command is used to specify the wavelength being used on the detector. + """ + self.sendCommand('*swa {}'.format(value)) + + @Action(values={True:1, False:0}) + def atu(self,value): + """This command is used to adjust the processing of the meter with the readings of the detector, depending on whether the detector is using an external attenuator or not. + """ + self.sendCommand('*atu {}'.format(value)) + + @Action(values=(set((1,2,)), None)) + def smu(self,value,multiplier): + """This command is used to set the value of the multipliers. + """ + self.sendCommand('*smu {0} {1}'.format(value,multiplier)) + + @Action(values=(set((1,2,)), None)) + def sou(self,value,multiplier): + """This command is used to set the value of the offsets. + """ + self.sendCommand('*sou {0} {1}'.format(value,multiplier)) + + @Feat() + def rds(self): + """This command is used to read the current data sampling settings. + """ + return self.query('*rds') + + SampleRateUnit = {'second':0, 'minute':1, 'hour':2, 'day':3, '%':4} + SamplePeriodUnit = {'second':0, 'minute':1, 'hour':2, 'day':3, 'week':4, 'pulse':5} + TotalDurationUnit = {'sample':0, 'second':1, 'minute':2, 'hour':3, 'day':4, 'week':5, 'continuous':6, 'predefinded':7} + TimeStamp = {True:1, False:0} + @Action(values=(None, SampleRateUnit, None, SamplePeriodUnit, None, TotalDurationUnit, TimeStamp,)) + def dsu(self, sampleRate, sampleRateUnit, samplePeriod, samplePeriodUnit, totalDuration, totalDurationUnit, timeStamp,): + """ + """ + self.sendCommand('*dsu {} {} {} {} {} {} {}'.format(sampleRate, sampleRateUnit, samplePeriod, samplePeriodUnit, totalDuration, totalDurationUnit, timeStamp,)) + + @Action() + def tla(self, value=True): + """This command sets the internal trigger level when using the device in energy reading mode. + """ + self.sendCommand('*tla {}%'.format(value)) + +#MEASUREMENT COMMANDS - MEASUREMENT CONTROL + + @Action(values={'disable':0, 'enable':1, 'reset':2}) + def esu(self, value=True): + """This command is used start, stop and reset the statistics calculating process on the data currently being acquisitioned. + """ + self.sendCommand('*esu {}'.format(value)) + + @Action(values={True:1, False:0}) + def sca(self,value): + """ + """ + self.sendCommand('*sca {}'.format(value)) + + @Action(values={True:1, False:0}) + def eaa(self,value): + """ + """ + self.sendCommand('*eaa {}'.format(value)) + + @Action(values={'off':0, 'on':1, 'undo':2}) + def eoa(self,value): + """ + """ + self.sendCommand('*eoa {}'.format(value)) + +#INSTRUMENT AND DETECTOR INFORMATION COMMANDS + + @Feat() + def ver(self): + """This command is used to query the device to get information about the firmware version and the device type. + """ + return self.query('*ver') + + @Feat() + def hea(self): + """Model of the current head + """ + return self.query('*hea') + + #The device is a bit buggy for this one as it return the info with 3 \n\r. So the hack here repare it. + @Feat() + def sta(self): + """This command is used to view data that is relevant to the current detector head. + """ + out = '' + out += self.query('*sta') + out += '\t{}'.format(self.recv()) + out += '\t{}'.format(self.recv()) + return out + + @Feat() + def bat(self): + """This command is used to query the device’s remaining battery power. + """ + return self.query('*bat') + + day = set(range(1,32)) + month = set(range(1,13)) + year = set(range(1970,3000)) + hour = set(range(24)) + minute = set(range(59)) + second = set(range(59)) + AMPM = {'AM':0, 'PM':1} + @Action(values=(day, month, year, hour, minute, second, AMPM,)) + def clk(self, Day, Month, Year, Hour, Minute, Second, aMPM,): + """ + """ + self.sendCommand('*clk {} {} {} {} {} {} {}'.format(Day, Month, Year, Hour, Minute, Second, aMPM,)) + +#INSTRUMENT CONTROL COMMANDS + + @Action(values={True:1, False:0}) + def bkl(self, value=True): + """This command is used to turn the backlight of the device display on or off. + """ + self.sendCommand('*bkl {}'.format(value)) + + @Action(values={True:1, False:0}) + def ano(self, value=True): + """This command is used to enable or disable the output of the current value on the analog port of the meter. + """ + self.sendCommand('*ano {}'.format(value)) + +#COMMUNICATIONS COMMANDS + + @Action(values=set((2400, 9600, 14400, 19200, 38400, 155200))) + def brs(self, value=True): + """This command is used to change the current baud rate of the serial port of the device. + """ + self.sendCommand('*brs {}'.format(value)) + + def query(self, command, *, send_args=(None, None), recv_args=(None, None)): + answer = super().query(command, send_args=send_args, recv_args=recv_args) + if answer == 'ERROR': + raise InstrumentError + return answer + + def sendCommand(self, s): + self.send(s) + self.waitInstrumentDone() + + def waitInstrumentDone(self, termination=None, encoding=None, recv_chunk=None): + """Wait for command completion by instrument. + + :param termination: termination character (overrides class default) + :type termination: str + :param encoding: encoding to transform bytes to string (overrides class default) + :param recv_chunk: number of bytes to receive (overrides class default) + :return: string encoded from received bytes + """ + + termination = termination or self.RECV_DONE + encoding = encoding or self.ENCODING + recv_chunk = recv_chunk or self.RECV_CHUNK + + if not termination: + return str(self.raw_recv(recv_chunk), encoding) + + if self.TIMEOUT is None or self.TIMEOUT < 0: + stop = float('+inf') + else: + stop = time.time() + self.TIMEOUT + + received = self._received + while not termination in received: + if time.time() > stop: + raise LantzTimeoutError + raw_received = self.raw_recv(recv_chunk) + received += str(raw_received, encoding) + + self.log_debug('Received {!r} (len={})', received, len(received)) + +if __name__ == '__main__': + import argparse + import lantz.log + + parser = argparse.ArgumentParser(description='Newport 842-PE powermeter') + parser.add_argument('-i', '--interactive', action='store_true', + default=False, help='Show interactive GUI') + parser.add_argument('-p', '--port', type=str, default='17', + help='Serial port to connect to') + + args = parser.parse_args() + lantz.log.log_to_screen(lantz.log.DEBUG) + with Newport842PE(args.port) as inst: + if args.interactive: + from lantz.ui.qtwidgets import start_test_app + start_test_app(inst) + else: + print('Non interactive mode') + inst.sdu('statistic') + print(inst.ver) +# inst.Log('save both') +# time.sleep(1) +# inst.Log('stop') +# print(inst.fdl(1)) +# print(inst.cau) +# while 1: +# time.sleep(.1) +# print(inst.cvu) + + dataAvailable = inst.nvu + if inst.nvu: + print(inst.cvu) +# print(inst.fdl) #buggy +# print(inst.cau) #buggy + inst.ssa('100m') + inst.bkl(1) + inst.dbu(False) + inst.shl(False) + +# print(inst.sta) + print(inst.hea) + print(inst.bat) +# print(inst.sta) + inst.eoa('on') + #inst.sta + #inst.clk(5,9,2013,17,58,00,'PM') + #inst.dsu(1,'second', 10,'second', 1,'sample', True) + print(inst.rds) diff --git a/lantz/drivers/newport/__init__.py b/lantz/drivers/newport/__init__.py new file mode 100644 index 0000000..6da906c --- /dev/null +++ b/lantz/drivers/newport/__init__.py @@ -0,0 +1,19 @@ +# -*- coding: utf-8 -*- +""" + lantz.drivers.newport + ~~~~~~~~~~~~~~~~~~~ + + :company: Newport + :description: + :website: http://www.newport.com + + ---- + + :copyright: 2013 by Lantz Authors, see AUTHORS for more details. + :license: BSD, see LICENSE for more details. +""" + +from .842PE import 842PE + +__all__ = ['842PE',] + diff --git a/lantz/drivers/princetoninstruments/trivista.py b/lantz/drivers/princetoninstruments/trivista.py deleted file mode 100644 index 9db8c3a..0000000 --- a/lantz/drivers/princetoninstruments/trivista.py +++ /dev/null @@ -1,113 +0,0 @@ -# -*- coding: utf-8 -*- -""" - lantz.drivers.princetoninstruments.trivista - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - Trivista Spectrometer. - - :copyright: 2013 by Lantz Authors, see AUTHORS for more details. - :license: BSD, see LICENSE for more details. -""" - -from lantz import Action, Feat, DictFeat -from lantz.serial import SerialDriver - -class SerialTemplate(SerialDriver): - """Template for drivers connecting via serial port. - """ - - ENCODING = 'ascii' - - RECV_TERMINATION = ' ok\r\n' - SEND_TERMINATION = '\r' - - @Feat() - def model(self): - """Returns model number of the monochromator - """ - return self.query('model') - - @Feat() - def serialNo(self): - """Returns serial number of the monochromator - """ - return self.query('serial') - - @Feat() - def mono_eestatus(self): - """Returns setup and grating calibration parameters for all gratings - """ - return self.query('mono-eestatus') - - @Feat() - def turret(self): - """Returns the correctly installed turret numbered 1 - 3 - """ - return self.query('?turret') - - @Feat() - def gratings(self): - """Returns the list of installed gratings with position groove density and blaze. The present grating is specified with an arrow. - """ - return self.query('?gratings') - - @Feat() - def grating(self): - """Returns the number of gratings presently being used numbered 1 - 9. - """ - return self.query('?grating') - - @Feat() - def nm_min(self): - """ Returns present scan rate in nm/min to 0.01 nm/min resolution with units nm/min. - """ - return self.query('?nm/min') - - @Feat() - def mono_done(self): - """Used with >NM command to determine if monochromator has reached the destination. Returns 0 if move is not complete, 1 if move is complete. - """ - return self.query('mono-?done') - - @Feat() - def nm(self): - """ Returns present wavelength in nm to 0.01 nm resolution with -units nm appended. - """ - return self.query('?nm') - - def query(self, command, *, send_args=(None, None), recv_args=(None, None)): - answer = super().query(command, send_args=send_args, recv_args=recv_args) - if answer == 'ERROR': - raise InstrumentError - return answer.strip() - -if __name__ == '__main__': - import argparse - import lantz.log - - parser = argparse.ArgumentParser(description='Princeton Instrument Trivista') - parser.add_argument('-i', '--interactive', action='store_true', - default=False, help='Show interactive GUI') - parser.add_argument('-p', '--port', type=str, default='17', - help='Serial port to connect to') - - args = parser.parse_args() - lantz.log.log_to_socket(lantz.log.DEBUG) - print(args.port) - with SerialTemplate(args.port) as inst: - if args.interactive: - from lantz.ui.qtwidgets import start_test_app - start_test_app(inst) - else: - print('Non interactive mode') - print(inst.model) - print(inst.serialNo) - print(inst.mono_eestatus) - print(inst.turret) - print(inst.gratings) - print(inst.grating) - print(inst.nm_min) - print(inst.nm) - - print('model: {}'.format(inst.model)) From 5cc2985259efed6d54632002d98a607d2dc570b3 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Thu, 5 Sep 2013 20:15:49 -0400 Subject: [PATCH 12/48] correct code style --- lantz/drivers/newport/842PE.py | 70 +++++++++++++++++----------------- 1 file changed, 36 insertions(+), 34 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 687afbc..d8df463 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -12,7 +12,7 @@ from lantz import Action, Feat, DictFeat from lantz.serial import SerialDriver -class Newport842PE(SerialDriver): +class N842PE(SerialDriver): """Newport 842-PE powermeter """ @@ -27,40 +27,40 @@ class Newport842PE(SerialDriver): PARITY = 'none' STOPBITS = 1 -#Display commands + #Display commands @Action(values={'real-time':0, 'histogram':1, 'statistic':2, 'needle':3, 'lineplot':4}) def sdu(self, value): """This command is used to change the device’s on-screen display mode. """ - self.sendCommand('*sdu {}'.format(value)) + self.send_command('*sdu {}'.format(value)) @Action(values=set(('auto', '1p', '3p', '10p', '30p', '100p', '300p', '1n', '3n', '10n', '30n', '100n', '300n', '1u', '3u', '10u', '30u', '100u', '300u', '1m', '3m', '10m', '30m', '100m', '300m', '1', '3', '10', '30', '100', '300', '1k', '3k', '10k', '30k', '100k', '300k', '1M', '3M', '10M', '30M', '100M', '300M',))) def ssa(self, value): """This command is used to force the display of the current data into a specific range. """ - self.sendCommand('*ssa {}'.format(value)) + self.send_command('*ssa {}'.format(value)) @Action(values={True:1, False:0}) def dbu(self, value): """This command changes the on-screen display unit to dBm. """ - self.sendCommand('*dbu {}'.format(value)) + self.send_command('*dbu {}'.format(value)) @Action(values={True:1, False:0}) def shl(self, value): """This command is used to add significant digits to the on-screen reading. """ - self.sendCommand('*shl {}'.format(value)) + self.send_command('*shl {}'.format(value)) -#MEASUREMENT COMMANDS - DATA ACQUISITION + #MEASUREMENT COMMANDS - DATA ACQUISITION @Feat() def cvu(self): """This command is used to query the value that is currently being displayed on the device’s screen. The value is displayed in Watts or in Joules (not in dBm). """ - result = self.query('*cvu') - return float(result.replace('Current Value:','').strip()) + return self.parse_query('*cvu', + format='Current Value: {}') @Feat(values={False:'New Data Not Available', True:'New Data Available'}) def nvu(self): @@ -78,7 +78,7 @@ def vsu(self): def Log(self, value): """This command is used to log data on the 842-PE meter’s EEPROM. """ - self.sendCommand('*log {}'.format(value)) + self.send_command('*log {}'.format(value)) #Buggy @Action() @@ -94,31 +94,31 @@ def cau(self): """This command is used to send data to the serial port according to the data sampling setting. The maximum transfer speed is 200Hz. """ return self.query('*cau') - -#MEASUREMENT COMMANDS - SETUP + + #MEASUREMENT COMMANDS - SETUP def swa(self): """This command is used to specify the wavelength being used on the detector. """ - self.sendCommand('*swa {}'.format(value)) + self.send_command('*swa {}'.format(value)) @Action(values={True:1, False:0}) def atu(self,value): """This command is used to adjust the processing of the meter with the readings of the detector, depending on whether the detector is using an external attenuator or not. """ - self.sendCommand('*atu {}'.format(value)) + self.send_command('*atu {}'.format(value)) @Action(values=(set((1,2,)), None)) def smu(self,value,multiplier): """This command is used to set the value of the multipliers. """ - self.sendCommand('*smu {0} {1}'.format(value,multiplier)) + self.send_command('*smu {0} {1}'.format(value,multiplier)) @Action(values=(set((1,2,)), None)) def sou(self,value,multiplier): """This command is used to set the value of the offsets. """ - self.sendCommand('*sou {0} {1}'.format(value,multiplier)) + self.send_command('*sou {0} {1}'.format(value,multiplier)) @Feat() def rds(self): @@ -134,41 +134,41 @@ def rds(self): def dsu(self, sampleRate, sampleRateUnit, samplePeriod, samplePeriodUnit, totalDuration, totalDurationUnit, timeStamp,): """ """ - self.sendCommand('*dsu {} {} {} {} {} {} {}'.format(sampleRate, sampleRateUnit, samplePeriod, samplePeriodUnit, totalDuration, totalDurationUnit, timeStamp,)) + self.send_command('*dsu {} {} {} {} {} {} {}'.format(sampleRate, sampleRateUnit, samplePeriod, samplePeriodUnit, totalDuration, totalDurationUnit, timeStamp,)) @Action() def tla(self, value=True): """This command sets the internal trigger level when using the device in energy reading mode. """ - self.sendCommand('*tla {}%'.format(value)) + self.send_command('*tla {}%'.format(value)) -#MEASUREMENT COMMANDS - MEASUREMENT CONTROL + #MEASUREMENT COMMANDS - MEASUREMENT CONTROL @Action(values={'disable':0, 'enable':1, 'reset':2}) def esu(self, value=True): """This command is used start, stop and reset the statistics calculating process on the data currently being acquisitioned. """ - self.sendCommand('*esu {}'.format(value)) + self.send_command('*esu {}'.format(value)) @Action(values={True:1, False:0}) def sca(self,value): """ """ - self.sendCommand('*sca {}'.format(value)) + self.send_command('*sca {}'.format(value)) @Action(values={True:1, False:0}) def eaa(self,value): """ """ - self.sendCommand('*eaa {}'.format(value)) + self.send_command('*eaa {}'.format(value)) @Action(values={'off':0, 'on':1, 'undo':2}) def eoa(self,value): """ """ - self.sendCommand('*eoa {}'.format(value)) + self.send_command('*eoa {}'.format(value)) -#INSTRUMENT AND DETECTOR INFORMATION COMMANDS + #INSTRUMENT AND DETECTOR INFORMATION COMMANDS @Feat() def ver(self): @@ -210,29 +210,29 @@ def bat(self): def clk(self, Day, Month, Year, Hour, Minute, Second, aMPM,): """ """ - self.sendCommand('*clk {} {} {} {} {} {} {}'.format(Day, Month, Year, Hour, Minute, Second, aMPM,)) + self.send_command('*clk {} {} {} {} {} {} {}'.format(Day, Month, Year, Hour, Minute, Second, aMPM,)) -#INSTRUMENT CONTROL COMMANDS + #INSTRUMENT CONTROL COMMANDS @Action(values={True:1, False:0}) def bkl(self, value=True): """This command is used to turn the backlight of the device display on or off. """ - self.sendCommand('*bkl {}'.format(value)) + self.send_command('*bkl {}'.format(value)) @Action(values={True:1, False:0}) def ano(self, value=True): """This command is used to enable or disable the output of the current value on the analog port of the meter. """ - self.sendCommand('*ano {}'.format(value)) + self.send_command('*ano {}'.format(value)) -#COMMUNICATIONS COMMANDS + #COMMUNICATIONS COMMANDS @Action(values=set((2400, 9600, 14400, 19200, 38400, 155200))) def brs(self, value=True): """This command is used to change the current baud rate of the serial port of the device. """ - self.sendCommand('*brs {}'.format(value)) + self.send_command('*brs {}'.format(value)) def query(self, command, *, send_args=(None, None), recv_args=(None, None)): answer = super().query(command, send_args=send_args, recv_args=recv_args) @@ -240,11 +240,11 @@ def query(self, command, *, send_args=(None, None), recv_args=(None, None)): raise InstrumentError return answer - def sendCommand(self, s): + def send_command(self, s): self.send(s) - self.waitInstrumentDone() + self.wait_instrument_done() - def waitInstrumentDone(self, termination=None, encoding=None, recv_chunk=None): + def wait_instrument_done(self, termination=None, encoding=None, recv_chunk=None): """Wait for command completion by instrument. :param termination: termination character (overrides class default) @@ -287,7 +287,7 @@ def waitInstrumentDone(self, termination=None, encoding=None, recv_chunk=None): args = parser.parse_args() lantz.log.log_to_screen(lantz.log.DEBUG) - with Newport842PE(args.port) as inst: + with N842PE(args.port) as inst: if args.interactive: from lantz.ui.qtwidgets import start_test_app start_test_app(inst) @@ -323,3 +323,5 @@ def waitInstrumentDone(self, termination=None, encoding=None, recv_chunk=None): #inst.clk(5,9,2013,17,58,00,'PM') #inst.dsu(1,'second', 10,'second', 1,'sample', True) print(inst.rds) + print(inst.sta) + print(inst.cvu) From c41841b45a31ee7e197df689afcb5beb73589a67 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Fri, 6 Sep 2013 11:41:49 -0400 Subject: [PATCH 13/48] pep8 & pyflakes OK --- lantz/drivers/newport/842PE.py | 193 +++++++++++++++++++++------------ 1 file changed, 121 insertions(+), 72 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index d8df463..37b6952 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -9,8 +9,11 @@ :license: BSD, see LICENSE for more details. """ import time -from lantz import Action, Feat, DictFeat + +from lantz import Action, Feat from lantz.serial import SerialDriver +from lantz.errors import InstrumentError, LantzTimeoutError + class N842PE(SerialDriver): """Newport 842-PE powermeter @@ -18,7 +21,8 @@ class N842PE(SerialDriver): ENCODING = 'ascii' - RECV_DONE = 'ACK\r\n' #this string is return by the device when the action is done + # this string is returned by the device when the action is done + RECV_DONE = 'ACK\r\n' RECV_TERMINATION = '\r\n' SEND_TERMINATION = '\r\n' @@ -29,27 +33,35 @@ class N842PE(SerialDriver): #Display commands - @Action(values={'real-time':0, 'histogram':1, 'statistic':2, 'needle':3, 'lineplot':4}) + @Action(values={'real-time': 0, 'histogram': 1, 'statistic': 2, + 'needle': 3, 'lineplot': 4}) def sdu(self, value): """This command is used to change the device’s on-screen display mode. """ self.send_command('*sdu {}'.format(value)) - @Action(values=set(('auto', '1p', '3p', '10p', '30p', '100p', '300p', '1n', '3n', '10n', '30n', '100n', '300n', '1u', '3u', '10u', '30u', '100u', '300u', '1m', '3m', '10m', '30m', '100m', '300m', '1', '3', '10', '30', '100', '300', '1k', '3k', '10k', '30k', '100k', '300k', '1M', '3M', '10M', '30M', '100M', '300M',))) + @Action(values=set(('auto', '1p', '3p', '10p', '30p', '100p', '300p', '1n', + '3n', '10n', '30n', '100n', '300n', '1u', '3u', '10u', + '30u', '100u', '300u', '1m', '3m', '10m', '30m', + '100m', '300m', '1', '3', '10', '30', '100', '300', + '1k', '3k', '10k', '30k', '100k', '300k', '1M', '3M', + '10M', '30M', '100M', '300M',))) def ssa(self, value): - """This command is used to force the display of the current data into a specific range. + """This command is used to force the display of the current data into a + specific range. """ self.send_command('*ssa {}'.format(value)) - @Action(values={True:1, False:0}) + @Action(values={False: 0, True: 1}) def dbu(self, value): """This command changes the on-screen display unit to dBm. """ self.send_command('*dbu {}'.format(value)) - @Action(values={True:1, False:0}) + @Action(values={False: 0, True: 1}) def shl(self, value): - """This command is used to add significant digits to the on-screen reading. + """This command is used to add significant digits to the on-screen + reading. """ self.send_command('*shl {}'.format(value)) @@ -57,24 +69,30 @@ def shl(self, value): @Feat() def cvu(self): - """This command is used to query the value that is currently being displayed on the device’s screen. The value is displayed in Watts or in Joules (not in dBm). + """This command is used to query the value that is currently being + displayed on the device’s screen. The value is displayed in Watts or in + Joules (not in dBm). """ return self.parse_query('*cvu', format='Current Value: {}') - @Feat(values={False:'New Data Not Available', True:'New Data Available'}) + @Feat(values={False: 'New Data Not Available', True: 'New Data Available'}) def nvu(self): - """This command is used to check whether a new value is available from the device. Though optional, its use is recommended when used with single pulse operations. + """This command is used to check whether a new value is available from + the device. Though optional, its use is recommended when used with + single pulse operations. """ return self.query('*nvu') @Feat() def vsu(self): - """This command is used to read all the statistics data, provided that the device has previously been set into statistic mode. + """This command is used to read all the statistics data, provided that + the device has previously been set into statistic mode. """ return self.query('*vsu') - @Action(values={'stop':0, 'start raw':1, 'start saving':2, 'save both':3,}) + @Action(values={'stop': 0, 'start raw': 1, 'start saving': 2, + 'save both': 3}) def Log(self, value): """This command is used to log data on the 842-PE meter’s EEPROM. """ @@ -91,88 +109,107 @@ def fdl(self, value): #Buggy @Feat() def cau(self): - """This command is used to send data to the serial port according to the data sampling setting. The maximum transfer speed is 200Hz. + """This command is used to send data to the serial port according to + the data sampling setting. The maximum transfer speed is 200Hz. """ return self.query('*cau') - + #MEASUREMENT COMMANDS - SETUP - def swa(self): - """This command is used to specify the wavelength being used on the detector. + def swa(self, value): + """This command is used to specify the wavelength being used on the + detector. """ self.send_command('*swa {}'.format(value)) - @Action(values={True:1, False:0}) - def atu(self,value): - """This command is used to adjust the processing of the meter with the readings of the detector, depending on whether the detector is using an external attenuator or not. + @Action(values={False: 0, True: 1}) + def atu(self, value): + """This command is used to adjust the processing of the meter with the + readings of the detector, depending on whether the detector is using an + external attenuator or not. """ self.send_command('*atu {}'.format(value)) - - @Action(values=(set((1,2,)), None)) - def smu(self,value,multiplier): - """This command is used to set the value of the multipliers. - """ - self.send_command('*smu {0} {1}'.format(value,multiplier)) - - @Action(values=(set((1,2,)), None)) - def sou(self,value,multiplier): + + @Action(values=(set((1, 2,)), None)) + def smu(self, value, multiplier): + """This command is used to set the value of the multipliers. + """ + self.send_command('*smu {0} {1}'.format(value, multiplier)) + + @Action(values=(set((1, 2,)), None)) + def sou(self, value, multiplier): """This command is used to set the value of the offsets. """ - self.send_command('*sou {0} {1}'.format(value,multiplier)) + self.send_command('*sou {0} {1}'.format(value, multiplier)) - @Feat() + @Feat() def rds(self): - """This command is used to read the current data sampling settings. - """ - return self.query('*rds') + """This command is used to read the current data sampling settings. + """ + return self.query('*rds') + + SampleRateUnit = {'second': 0, 'minute': 1, 'hour': 2, 'day': 3, '%': 4} + SamplePeriodUnit = {'second': 0, 'minute': 1, 'hour': 2, 'day': 3, + 'week': 4, 'pulse': 5} + TotalDurationUnit = {'sample': 0, 'second': 1, 'minute': 2, 'hour': 3, + 'day': 4, 'week': 5, 'continuous': 6, + 'predefinded': 7} + TimeStamp = {False: 0, True: 1} - SampleRateUnit = {'second':0, 'minute':1, 'hour':2, 'day':3, '%':4} - SamplePeriodUnit = {'second':0, 'minute':1, 'hour':2, 'day':3, 'week':4, 'pulse':5} - TotalDurationUnit = {'sample':0, 'second':1, 'minute':2, 'hour':3, 'day':4, 'week':5, 'continuous':6, 'predefinded':7} - TimeStamp = {True:1, False:0} - @Action(values=(None, SampleRateUnit, None, SamplePeriodUnit, None, TotalDurationUnit, TimeStamp,)) - def dsu(self, sampleRate, sampleRateUnit, samplePeriod, samplePeriodUnit, totalDuration, totalDurationUnit, timeStamp,): + @Action(values=(None, SampleRateUnit, None, SamplePeriodUnit, None, + TotalDurationUnit, TimeStamp,)) + def dsu(self, sampleRate, sampleRateUnit, samplePeriod, samplePeriodUnit, + totalDuration, totalDurationUnit, timeStamp,): """ """ - self.send_command('*dsu {} {} {} {} {} {} {}'.format(sampleRate, sampleRateUnit, samplePeriod, samplePeriodUnit, totalDuration, totalDurationUnit, timeStamp,)) + self.send_command('*dsu {} {} {} {} {} {} {}'.format(sampleRate, + sampleRateUnit, + samplePeriod, + samplePeriodUnit, + totalDuration, + totalDurationUnit, + timeStamp,)) @Action() def tla(self, value=True): - """This command sets the internal trigger level when using the device in energy reading mode. + """This command sets the internal trigger level when using the device + in energy reading mode. """ self.send_command('*tla {}%'.format(value)) #MEASUREMENT COMMANDS - MEASUREMENT CONTROL - @Action(values={'disable':0, 'enable':1, 'reset':2}) + @Action(values={'disable': 0, 'enable': 1, 'reset': 2}) def esu(self, value=True): - """This command is used start, stop and reset the statistics calculating process on the data currently being acquisitioned. + """This command is used start, stop and reset the statistics + calculating process on the data currently being acquisitioned. """ self.send_command('*esu {}'.format(value)) - @Action(values={True:1, False:0}) - def sca(self,value): + @Action(values={False: 0, True: 1}) + def sca(self, value): """ """ self.send_command('*sca {}'.format(value)) - @Action(values={True:1, False:0}) - def eaa(self,value): + @Action(values={False: 0, True: 1}) + def eaa(self, value): """ """ self.send_command('*eaa {}'.format(value)) - @Action(values={'off':0, 'on':1, 'undo':2}) - def eoa(self,value): + @Action(values={'off': 0, 'on': 1, 'undo': 2}) + def eoa(self, value): """ """ self.send_command('*eoa {}'.format(value)) - #INSTRUMENT AND DETECTOR INFORMATION COMMANDS + #INSTRUMENT AND DETECTOR INFORMATION COMMANDS @Feat() def ver(self): - """This command is used to query the device to get information about the firmware version and the device type. + """This command is used to query the device to get information about + the firmware version and the device type. """ return self.query('*ver') @@ -182,10 +219,12 @@ def hea(self): """ return self.query('*hea') - #The device is a bit buggy for this one as it return the info with 3 \n\r. So the hack here repare it. + #The device is a bit buggy for this one as it return the info with 3 \n\r. + #So the hack here repare it. @Feat() def sta(self): - """This command is used to view data that is relevant to the current detector head. + """This command is used to view data that is relevant to the current + detector head. """ out = '' out += self.query('*sta') @@ -195,34 +234,39 @@ def sta(self): @Feat() def bat(self): - """This command is used to query the device’s remaining battery power. + """This command is used to query the device’s remaining battery power. """ return self.query('*bat') - day = set(range(1,32)) - month = set(range(1,13)) - year = set(range(1970,3000)) + day = set(range(1, 32)) + month = set(range(1, 13)) + year = set(range(1970, 3000)) hour = set(range(24)) minute = set(range(59)) second = set(range(59)) - AMPM = {'AM':0, 'PM':1} + AMPM = {'AM': 0, 'PM': 1} + @Action(values=(day, month, year, hour, minute, second, AMPM,)) def clk(self, Day, Month, Year, Hour, Minute, Second, aMPM,): """ """ - self.send_command('*clk {} {} {} {} {} {} {}'.format(Day, Month, Year, Hour, Minute, Second, aMPM,)) + self.send_command('*clk {} {} {} {} {} {} {}'.format(Day, Month, Year, + Hour, Minute, + Second, aMPM,)) #INSTRUMENT CONTROL COMMANDS - @Action(values={True:1, False:0}) + @Action(values={False: 0, True: 1}) def bkl(self, value=True): - """This command is used to turn the backlight of the device display on or off. + """This command is used to turn the backlight of the device display on + or off. """ self.send_command('*bkl {}'.format(value)) - @Action(values={True:1, False:0}) + @Action(values={False: 0, True: 1}) def ano(self, value=True): - """This command is used to enable or disable the output of the current value on the analog port of the meter. + """This command is used to enable or disable the output of the current + value on the analog port of the meter. """ self.send_command('*ano {}'.format(value)) @@ -230,26 +274,31 @@ def ano(self, value=True): @Action(values=set((2400, 9600, 14400, 19200, 38400, 155200))) def brs(self, value=True): - """This command is used to change the current baud rate of the serial port of the device. + """This command is used to change the current baud rate of the serial + port of the device. """ self.send_command('*brs {}'.format(value)) - def query(self, command, *, send_args=(None, None), recv_args=(None, None)): - answer = super().query(command, send_args=send_args, recv_args=recv_args) + def query(self, command, *, send_args=(None, None), + recv_args=(None, None)): + answer = super().query(command, send_args=send_args, + recv_args=recv_args) if answer == 'ERROR': raise InstrumentError return answer def send_command(self, s): self.send(s) - self.wait_instrument_done() + self.wait_instrument_done() - def wait_instrument_done(self, termination=None, encoding=None, recv_chunk=None): + def wait_instrument_done(self, termination=None, encoding=None, + recv_chunk=None): """Wait for command completion by instrument. :param termination: termination character (overrides class default) :type termination: str - :param encoding: encoding to transform bytes to string (overrides class default) + :param encoding: encoding to transform bytes to string (overrides class + default) :param recv_chunk: number of bytes to receive (overrides class default) :return: string encoded from received bytes """ @@ -299,11 +348,11 @@ def wait_instrument_done(self, termination=None, encoding=None, recv_chunk=None) # time.sleep(1) # inst.Log('stop') # print(inst.fdl(1)) -# print(inst.cau) +# print(inst.cau) # while 1: # time.sleep(.1) # print(inst.cvu) - + dataAvailable = inst.nvu if inst.nvu: print(inst.cvu) From 5fca00b6671cea2e7daaed72fd5762db5301c27e Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Fri, 6 Sep 2013 17:10:58 -0400 Subject: [PATCH 14/48] remove send_command --- lantz/drivers/newport/842PE.py | 99 +++++++++++----------------------- 1 file changed, 31 insertions(+), 68 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 37b6952..bc3a708 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -21,8 +21,6 @@ class N842PE(SerialDriver): ENCODING = 'ascii' - # this string is returned by the device when the action is done - RECV_DONE = 'ACK\r\n' RECV_TERMINATION = '\r\n' SEND_TERMINATION = '\r\n' @@ -38,7 +36,7 @@ class N842PE(SerialDriver): def sdu(self, value): """This command is used to change the device’s on-screen display mode. """ - self.send_command('*sdu {}'.format(value)) + self.query('*sdu {}'.format(value)) @Action(values=set(('auto', '1p', '3p', '10p', '30p', '100p', '300p', '1n', '3n', '10n', '30n', '100n', '300n', '1u', '3u', '10u', @@ -50,20 +48,20 @@ def ssa(self, value): """This command is used to force the display of the current data into a specific range. """ - self.send_command('*ssa {}'.format(value)) + self.query('*ssa {}'.format(value)) @Action(values={False: 0, True: 1}) def dbu(self, value): """This command changes the on-screen display unit to dBm. """ - self.send_command('*dbu {}'.format(value)) + self.query('*dbu {}'.format(value)) @Action(values={False: 0, True: 1}) def shl(self, value): """This command is used to add significant digits to the on-screen reading. """ - self.send_command('*shl {}'.format(value)) + self.query('*shl {}'.format(value)) #MEASUREMENT COMMANDS - DATA ACQUISITION @@ -96,7 +94,7 @@ def vsu(self): def Log(self, value): """This command is used to log data on the 842-PE meter’s EEPROM. """ - self.send_command('*log {}'.format(value)) + self.query('*log {}'.format(value)) #Buggy @Action() @@ -120,7 +118,7 @@ def swa(self, value): """This command is used to specify the wavelength being used on the detector. """ - self.send_command('*swa {}'.format(value)) + self.query('*swa {}'.format(value)) @Action(values={False: 0, True: 1}) def atu(self, value): @@ -128,19 +126,19 @@ def atu(self, value): readings of the detector, depending on whether the detector is using an external attenuator or not. """ - self.send_command('*atu {}'.format(value)) + self.query('*atu {}'.format(value)) @Action(values=(set((1, 2,)), None)) def smu(self, value, multiplier): """This command is used to set the value of the multipliers. """ - self.send_command('*smu {0} {1}'.format(value, multiplier)) + self.query('*smu {0} {1}'.format(value, multiplier)) @Action(values=(set((1, 2,)), None)) def sou(self, value, multiplier): """This command is used to set the value of the offsets. """ - self.send_command('*sou {0} {1}'.format(value, multiplier)) + self.query('*sou {0} {1}'.format(value, multiplier)) @Feat() def rds(self): @@ -162,20 +160,20 @@ def dsu(self, sampleRate, sampleRateUnit, samplePeriod, samplePeriodUnit, totalDuration, totalDurationUnit, timeStamp,): """ """ - self.send_command('*dsu {} {} {} {} {} {} {}'.format(sampleRate, - sampleRateUnit, - samplePeriod, - samplePeriodUnit, - totalDuration, - totalDurationUnit, - timeStamp,)) + self.query('*dsu {} {} {} {} {} {} {}'.format(sampleRate, + sampleRateUnit, + samplePeriod, + samplePeriodUnit, + totalDuration, + totalDurationUnit, + timeStamp,)) @Action() def tla(self, value=True): """This command sets the internal trigger level when using the device in energy reading mode. """ - self.send_command('*tla {}%'.format(value)) + self.query('*tla {}%'.format(value)) #MEASUREMENT COMMANDS - MEASUREMENT CONTROL @@ -184,25 +182,25 @@ def esu(self, value=True): """This command is used start, stop and reset the statistics calculating process on the data currently being acquisitioned. """ - self.send_command('*esu {}'.format(value)) + self.query('*esu {}'.format(value)) @Action(values={False: 0, True: 1}) def sca(self, value): """ """ - self.send_command('*sca {}'.format(value)) + self.query('*sca {}'.format(value)) @Action(values={False: 0, True: 1}) def eaa(self, value): """ """ - self.send_command('*eaa {}'.format(value)) + self.query('*eaa {}'.format(value)) @Action(values={'off': 0, 'on': 1, 'undo': 2}) def eoa(self, value): """ """ - self.send_command('*eoa {}'.format(value)) + self.query('*eoa {}'.format(value)) #INSTRUMENT AND DETECTOR INFORMATION COMMANDS @@ -250,9 +248,9 @@ def bat(self): def clk(self, Day, Month, Year, Hour, Minute, Second, aMPM,): """ """ - self.send_command('*clk {} {} {} {} {} {} {}'.format(Day, Month, Year, - Hour, Minute, - Second, aMPM,)) + self.query('*clk {} {} {} {} {} {} {}'.format(Day, Month, Year, + Hour, Minute, + Second, aMPM,)) #INSTRUMENT CONTROL COMMANDS @@ -261,14 +259,14 @@ def bkl(self, value=True): """This command is used to turn the backlight of the device display on or off. """ - self.send_command('*bkl {}'.format(value)) + self.query('*bkl {}'.format(value)) @Action(values={False: 0, True: 1}) def ano(self, value=True): """This command is used to enable or disable the output of the current value on the analog port of the meter. """ - self.send_command('*ano {}'.format(value)) + self.query('*ano {}'.format(value)) #COMMUNICATIONS COMMANDS @@ -277,7 +275,7 @@ def brs(self, value=True): """This command is used to change the current baud rate of the serial port of the device. """ - self.send_command('*brs {}'.format(value)) + self.query('*brs {}'.format(value)) def query(self, command, *, send_args=(None, None), recv_args=(None, None)): @@ -287,43 +285,6 @@ def query(self, command, *, send_args=(None, None), raise InstrumentError return answer - def send_command(self, s): - self.send(s) - self.wait_instrument_done() - - def wait_instrument_done(self, termination=None, encoding=None, - recv_chunk=None): - """Wait for command completion by instrument. - - :param termination: termination character (overrides class default) - :type termination: str - :param encoding: encoding to transform bytes to string (overrides class - default) - :param recv_chunk: number of bytes to receive (overrides class default) - :return: string encoded from received bytes - """ - - termination = termination or self.RECV_DONE - encoding = encoding or self.ENCODING - recv_chunk = recv_chunk or self.RECV_CHUNK - - if not termination: - return str(self.raw_recv(recv_chunk), encoding) - - if self.TIMEOUT is None or self.TIMEOUT < 0: - stop = float('+inf') - else: - stop = time.time() + self.TIMEOUT - - received = self._received - while not termination in received: - if time.time() > stop: - raise LantzTimeoutError - raw_received = self.raw_recv(recv_chunk) - received += str(raw_received, encoding) - - self.log_debug('Received {!r} (len={})', received, len(received)) - if __name__ == '__main__': import argparse import lantz.log @@ -342,7 +303,9 @@ def wait_instrument_done(self, termination=None, encoding=None, start_test_app(inst) else: print('Non interactive mode') - inst.sdu('statistic') + inst.sdu('needle') + time.sleep(1) + inst.sdu('real-time') print(inst.ver) # inst.Log('save both') # time.sleep(1) @@ -360,7 +323,7 @@ def wait_instrument_done(self, termination=None, encoding=None, # print(inst.cau) #buggy inst.ssa('100m') inst.bkl(1) - inst.dbu(False) + #inst.dbu(False) inst.shl(False) # print(inst.sta) From 86c253dc0b067db7db3c72a501b78368ff5fb5a8 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Fri, 6 Sep 2013 17:11:59 -0400 Subject: [PATCH 15/48] remove send_command --- lantz/drivers/newport/842PE.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index bc3a708..51395ae 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -12,7 +12,7 @@ from lantz import Action, Feat from lantz.serial import SerialDriver -from lantz.errors import InstrumentError, LantzTimeoutError +from lantz.errors import InstrumentError class N842PE(SerialDriver): From 430d40c90d0444ea603ccd221cccfb2d332a834b Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Fri, 6 Sep 2013 17:13:10 -0400 Subject: [PATCH 16/48] m --- lantz/drivers/newport/__init__.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lantz/drivers/newport/__init__.py b/lantz/drivers/newport/__init__.py index 6da906c..0c278c3 100644 --- a/lantz/drivers/newport/__init__.py +++ b/lantz/drivers/newport/__init__.py @@ -13,7 +13,7 @@ :license: BSD, see LICENSE for more details. """ -from .842PE import 842PE +from .842PE import N842PE -__all__ = ['842PE',] +__all__ = ['N842PE',] From a3df82c4e9af35a0759d2123843f3d0eef022b1e Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Fri, 6 Sep 2013 17:23:14 -0400 Subject: [PATCH 17/48] add warning for broken functions --- lantz/drivers/newport/842PE.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 51395ae..bde01fc 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -9,6 +9,7 @@ :license: BSD, see LICENSE for more details. """ import time +import warnings from lantz import Action, Feat from lantz.serial import SerialDriver @@ -101,8 +102,8 @@ def Log(self, value): def fdl(self, value): """This command is used to retrieve a logged file from the device. """ -# return self.query('*fdl {}'.format(value)) - return self.query('*fdl 0') + #return self.query('*fdl {}'.format(value)) + warnings.warn('This function does not work!') #Buggy @Feat() @@ -110,7 +111,8 @@ def cau(self): """This command is used to send data to the serial port according to the data sampling setting. The maximum transfer speed is 200Hz. """ - return self.query('*cau') + #return self.query('*cau') + warnings.warn('This function does not work!') #MEASUREMENT COMMANDS - SETUP @@ -337,3 +339,4 @@ def query(self, command, *, send_args=(None, None), print(inst.rds) print(inst.sta) print(inst.cvu) + inst.cau From e8eadbc3018635d66820bd9593286dbdc040f2b5 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Sat, 7 Sep 2013 21:04:18 -0400 Subject: [PATCH 18/48] change functions name to human --- lantz/drivers/newport/842PE.py | 225 ++++++++++++++++++++------------- 1 file changed, 134 insertions(+), 91 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index bde01fc..01da04d 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -34,8 +34,9 @@ class N842PE(SerialDriver): @Action(values={'real-time': 0, 'histogram': 1, 'statistic': 2, 'needle': 3, 'lineplot': 4}) - def sdu(self, value): + def display(self, value): """This command is used to change the device’s on-screen display mode. + (sdu) """ self.query('*sdu {}'.format(value)) @@ -45,122 +46,155 @@ def sdu(self, value): '100m', '300m', '1', '3', '10', '30', '100', '300', '1k', '3k', '10k', '30k', '100k', '300k', '1M', '3M', '10M', '30M', '100M', '300M',))) - def ssa(self, value): + def scale(self, value): """This command is used to force the display of the current data into a - specific range. + specific range. (ssa) """ self.query('*ssa {}'.format(value)) @Action(values={False: 0, True: 1}) - def dbu(self, value): - """This command changes the on-screen display unit to dBm. + def dBm(self, value): + """This command changes the on-screen display unit to dBm. (dbu) """ self.query('*dbu {}'.format(value)) @Action(values={False: 0, True: 1}) - def shl(self, value): + def high_resolution(self, value): """This command is used to add significant digits to the on-screen - reading. + reading. (shl) """ self.query('*shl {}'.format(value)) #MEASUREMENT COMMANDS - DATA ACQUISITION @Feat() - def cvu(self): + def current_value(self): """This command is used to query the value that is currently being displayed on the device’s screen. The value is displayed in Watts or in - Joules (not in dBm). + Joules (not in dBm). (cvu) """ return self.parse_query('*cvu', format='Current Value: {}') @Feat(values={False: 'New Data Not Available', True: 'New Data Available'}) - def nvu(self): + def value_available(self): """This command is used to check whether a new value is available from the device. Though optional, its use is recommended when used with - single pulse operations. + single pulse operations. (nvu) """ return self.query('*nvu') @Feat() - def vsu(self): + def statistics(self): """This command is used to read all the statistics data, provided that - the device has previously been set into statistic mode. + the device has previously been set into statistic mode. (vsu) """ return self.query('*vsu') @Action(values={'stop': 0, 'start raw': 1, 'start saving': 2, 'save both': 3}) - def Log(self, value): - """This command is used to log data on the 842-PE meter’s EEPROM. + def logging(self, value): + """This command is used to log data on the 842-PE meter’s EEPROM. (log) """ self.query('*log {}'.format(value)) #Buggy @Action() - def fdl(self, value): + def get_log(self, value): """This command is used to retrieve a logged file from the device. + (fdl) """ #return self.query('*fdl {}'.format(value)) warnings.warn('This function does not work!') #Buggy @Feat() - def cau(self): + def get_data(self): """This command is used to send data to the serial port according to - the data sampling setting. The maximum transfer speed is 200Hz. + the data sampling setting. The maximum transfer speed is 200Hz. (cau) """ #return self.query('*cau') warnings.warn('This function does not work!') #MEASUREMENT COMMANDS - SETUP - def swa(self, value): + def wavelength(self, value): """This command is used to specify the wavelength being used on the - detector. + detector. (swa) """ self.query('*swa {}'.format(value)) @Action(values={False: 0, True: 1}) - def atu(self, value): + def attenuator(self, value): """This command is used to adjust the processing of the meter with the readings of the detector, depending on whether the detector is using an - external attenuator or not. + external attenuator or not. (atu) """ self.query('*atu {}'.format(value)) @Action(values=(set((1, 2,)), None)) - def smu(self, value, multiplier): - """This command is used to set the value of the multipliers. + def multiplier(self, value, multiplier): + """This command is used to set the value of the multipliers. (smu) """ self.query('*smu {0} {1}'.format(value, multiplier)) @Action(values=(set((1, 2,)), None)) - def sou(self, value, multiplier): - """This command is used to set the value of the offsets. + def offset(self, value, multiplier): + """This command is used to set the value of the offsets. (sou) """ self.query('*sou {0} {1}'.format(value, multiplier)) @Feat() - def rds(self): + def sampling2(self): """This command is used to read the current data sampling settings. + (rds) """ - return self.query('*rds') - - SampleRateUnit = {'second': 0, 'minute': 1, 'hour': 2, 'day': 3, '%': 4} - SamplePeriodUnit = {'second': 0, 'minute': 1, 'hour': 2, 'day': 3, - 'week': 4, 'pulse': 5} - TotalDurationUnit = {'sample': 0, 'second': 1, 'minute': 2, 'hour': 3, - 'day': 4, 'week': 5, 'continuous': 6, - 'predefinded': 7} - TimeStamp = {False: 0, True: 1} + out = self.parse_query('*rds', format='Sample Rate: {} / {}\tSample Period: {} / {}\tTotal Duration: {} {}\tTime Stamp: {}') + print(out) + return out - @Action(values=(None, SampleRateUnit, None, SamplePeriodUnit, None, + SampleRateUnit = {'Seconds': '0', 'Minutes': '1', 'Hours': '2', 'Days': '3', '%': '4'} + SamplePeriodUnit = {'Seconds': '0', 'Minutes': '1', 'Hours': '2', 'Days': '3', + 'Weeks': '4', 'Pulses': '5'} + TotalDurationUnit = {'Period': '0', 'Seconds': '1', 'Minutes': '2', 'Hours': '3', + 'Days': '4', 'Weeks': '5', 'Continuous': '6', + 'predefinded': '7'} + TimeStamp = {'OFF': False, 'ON': True, False: 0, True: 1} + @Feat(values=(None, SampleRateUnit, None, SamplePeriodUnit, None, TotalDurationUnit, TimeStamp,)) + def sampling(self): + """This command is used to read the current data sampling settings. + (rds) + """ + out = self.parse_query('*rds', format='Sample Rate: {} / {}\tSample Period: {} / {}\tTotal Duration: {} {}\tTime Stamp: {}') + print(out) + #global SampleRateUnit + SampleRateUnit = {'Seconds': '0', 'Minutes': '1', 'Hours': '2', 'Days': '3', '%': '4'} + SamplePeriodUnit = {'Seconds': '0', 'Minutes': '1', 'Hours': '2', 'Days': '3', + 'Weeks': '4', 'Pulses': '5'} + TotalDurationUnit = {'Period': '0', 'Seconds': '1', 'Minutes': '2', 'Hours': '3', + 'Days': '4', 'Weeks': '5', 'Continuous': '6', + 'predefinded': '7'} + TimeStamp = {'OFF': 0, 'ON': 1, False: 0, True: 1} + out[1] = SampleRateUnit[out[1]] + out[3] = SamplePeriodUnit[out[3]] + out[5] = TotalDurationUnit[out[5]] + out[6] = TimeStamp[out[6]] + return out + #return self.query('*rds') + + @sampling.setter + def sampling(self, value): + """This command provides the data sampling parameters for the logging + and statistics environments. (dsu) + """ + self.query('*dsu {} {} {} {} {} {} {}'.format(*value)) + + @Action() def dsu(self, sampleRate, sampleRateUnit, samplePeriod, samplePeriodUnit, totalDuration, totalDurationUnit, timeStamp,): - """ + """This command provides the data sampling parameters for the logging + and statistics environments. (dsu) """ self.query('*dsu {} {} {} {} {} {} {}'.format(sampleRate, sampleRateUnit, @@ -171,9 +205,9 @@ def dsu(self, sampleRate, sampleRateUnit, samplePeriod, samplePeriodUnit, timeStamp,)) @Action() - def tla(self, value=True): + def trigger(self, value=True): """This command sets the internal trigger level when using the device - in energy reading mode. + in energy reading mode. (tla) """ self.query('*tla {}%'.format(value)) @@ -182,49 +216,53 @@ def tla(self, value=True): @Action(values={'disable': 0, 'enable': 1, 'reset': 2}) def esu(self, value=True): """This command is used start, stop and reset the statistics - calculating process on the data currently being acquisitioned. + calculating process on the data currently being acquisitioned. (esu) """ self.query('*esu {}'.format(value)) @Action(values={False: 0, True: 1}) - def sca(self, value): - """ + def energy_mode(self, value): + """This command is used to toggle the Energy mode when using a high + power detector. (sca) """ self.query('*sca {}'.format(value)) @Action(values={False: 0, True: 1}) - def eaa(self, value): - """ + def anticipation(self, value): + """This command is used to enable or disable the anticipation + processing when the device is reading from a wattmeter. (eaa) """ self.query('*eaa {}'.format(value)) @Action(values={'off': 0, 'on': 1, 'undo': 2}) - def eoa(self, value): - """ + def zero(self, value): + """This command subtracts the current value from all future + measurements the moment the command is issued to set a new zero point. + (eoa) """ self.query('*eoa {}'.format(value)) #INSTRUMENT AND DETECTOR INFORMATION COMMANDS @Feat() - def ver(self): + def idn(self): """This command is used to query the device to get information about - the firmware version and the device type. + the firmware version and the device type. (ver) """ return self.query('*ver') @Feat() - def hea(self): - """Model of the current head + def idn_head(self): + """Model of the current head. (hea) """ return self.query('*hea') #The device is a bit buggy for this one as it return the info with 3 \n\r. #So the hack here repare it. @Feat() - def sta(self): + def status(self): """This command is used to view data that is relevant to the current - detector head. + detector head. (sta) """ out = '' out += self.query('*sta') @@ -233,8 +271,9 @@ def sta(self): return out @Feat() - def bat(self): + def battery(self): """This command is used to query the device’s remaining battery power. + (bat) """ return self.query('*bat') @@ -247,8 +286,9 @@ def bat(self): AMPM = {'AM': 0, 'PM': 1} @Action(values=(day, month, year, hour, minute, second, AMPM,)) - def clk(self, Day, Month, Year, Hour, Minute, Second, aMPM,): - """ + def clock(self, Day, Month, Year, Hour, Minute, Second, aMPM,): + """This command is used to adjust the time and date of the monitor's + internal clock. (clk) """ self.query('*clk {} {} {} {} {} {} {}'.format(Day, Month, Year, Hour, Minute, @@ -257,25 +297,25 @@ def clk(self, Day, Month, Year, Hour, Minute, Second, aMPM,): #INSTRUMENT CONTROL COMMANDS @Action(values={False: 0, True: 1}) - def bkl(self, value=True): + def backlight(self, value=True): """This command is used to turn the backlight of the device display on - or off. + or off. (blk) """ self.query('*bkl {}'.format(value)) @Action(values={False: 0, True: 1}) - def ano(self, value=True): + def analog_port(self, value=True): """This command is used to enable or disable the output of the current - value on the analog port of the meter. + value on the analog port of the meter. (ano) """ self.query('*ano {}'.format(value)) #COMMUNICATIONS COMMANDS @Action(values=set((2400, 9600, 14400, 19200, 38400, 155200))) - def brs(self, value=True): + def baud_rate(self, value=True): """This command is used to change the current baud rate of the serial - port of the device. + port of the device. (brs) """ self.query('*brs {}'.format(value)) @@ -304,39 +344,42 @@ def query(self, command, *, send_args=(None, None), from lantz.ui.qtwidgets import start_test_app start_test_app(inst) else: - print('Non interactive mode') - inst.sdu('needle') - time.sleep(1) - inst.sdu('real-time') - print(inst.ver) -# inst.Log('save both') + print('Testing instrument...') +# inst.display('needle') # time.sleep(1) -# inst.Log('stop') +# inst.display('real-time') +# print(inst.idn) +# inst.logging('save both') +# time.sleep(1) +# inst.logging('stop') # print(inst.fdl(1)) -# print(inst.cau) +# print(inst.get_data) # while 1: # time.sleep(.1) -# print(inst.cvu) +# print(inst.current_value) - dataAvailable = inst.nvu - if inst.nvu: - print(inst.cvu) +# if inst.value_available: +# print(inst.current_value) # print(inst.fdl) #buggy -# print(inst.cau) #buggy - inst.ssa('100m') - inst.bkl(1) - #inst.dbu(False) - inst.shl(False) - -# print(inst.sta) - print(inst.hea) - print(inst.bat) -# print(inst.sta) - inst.eoa('on') - #inst.sta +# print(inst.get_data) #buggy +# inst.scale('100m') + inst.backlight(True) + #inst.dBm(False) +# inst.high_resolution(False) + +# print(inst.status) +# print(inst.idn_head) +# print(inst.battery) +# print(inst.status) +# inst.zero('on') + #inst.status #inst.clk(5,9,2013,17,58,00,'PM') - #inst.dsu(1,'second', 10,'second', 1,'sample', True) - print(inst.rds) - print(inst.sta) - print(inst.cvu) - inst.cau + + inst.sampling = ('1', 'Minutes', '700000', 'Seconds', '1', 'Period', 'OFF') + print(inst.sampling) + + print(inst.sampling2) + + #print(inst.status) + #print(inst.current_value) + #inst.get_data From e8878d355a0979ef8bdf0b9340cbaa91266e4f73 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Sun, 8 Sep 2013 19:30:55 -0400 Subject: [PATCH 19/48] sampling getter/setter work --- lantz/drivers/newport/842PE.py | 97 ++++++++++++++++------------------ 1 file changed, 46 insertions(+), 51 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 01da04d..80f9278 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -144,44 +144,39 @@ def offset(self, value, multiplier): """ self.query('*sou {0} {1}'.format(value, multiplier)) - @Feat() - def sampling2(self): - """This command is used to read the current data sampling settings. - (rds) - """ - out = self.parse_query('*rds', format='Sample Rate: {} / {}\tSample Period: {} / {}\tTotal Duration: {} {}\tTime Stamp: {}') - print(out) - return out + SampleRateUnit = {'Seconds': '0', 'Minutes': '1', 'Hours': '2', + 'Days': '3', '% of pulses': '4'} + SamplePeriodUnit = {'Seconds': '0', 'Minutes': '1', 'Hours': '2', + 'Days': '3', 'Weeks': '4', 'Pulses': '5'} + TotalDurationUnit = {'Period': '0', 'Seconds': '1', 'Minutes': '2', + 'Hours': '3', 'Days': '4', 'Weeks': '5', + 'Continuous': '6', 'Points': '7'} + TimeStampEnabled = {False: 0, True: 1} - SampleRateUnit = {'Seconds': '0', 'Minutes': '1', 'Hours': '2', 'Days': '3', '%': '4'} - SamplePeriodUnit = {'Seconds': '0', 'Minutes': '1', 'Hours': '2', 'Days': '3', - 'Weeks': '4', 'Pulses': '5'} - TotalDurationUnit = {'Period': '0', 'Seconds': '1', 'Minutes': '2', 'Hours': '3', - 'Days': '4', 'Weeks': '5', 'Continuous': '6', - 'predefinded': '7'} - TimeStamp = {'OFF': False, 'ON': True, False: 0, True: 1} @Feat(values=(None, SampleRateUnit, None, SamplePeriodUnit, None, - TotalDurationUnit, TimeStamp,)) + TotalDurationUnit, TimeStampEnabled,)) def sampling(self): """This command is used to read the current data sampling settings. (rds) """ - out = self.parse_query('*rds', format='Sample Rate: {} / {}\tSample Period: {} / {}\tTotal Duration: {} {}\tTime Stamp: {}') - print(out) - #global SampleRateUnit - SampleRateUnit = {'Seconds': '0', 'Minutes': '1', 'Hours': '2', 'Days': '3', '%': '4'} - SamplePeriodUnit = {'Seconds': '0', 'Minutes': '1', 'Hours': '2', 'Days': '3', - 'Weeks': '4', 'Pulses': '5'} - TotalDurationUnit = {'Period': '0', 'Seconds': '1', 'Minutes': '2', 'Hours': '3', - 'Days': '4', 'Weeks': '5', 'Continuous': '6', - 'predefinded': '7'} - TimeStamp = {'OFF': 0, 'ON': 1, False: 0, True: 1} - out[1] = SampleRateUnit[out[1]] - out[3] = SamplePeriodUnit[out[3]] - out[5] = TotalDurationUnit[out[5]] - out[6] = TimeStamp[out[6]] + out = self.parse_query('*rds', format='Sample Rate: {} / {}\t' + 'Sample Period: {} / {}\t' + 'Total Duration: {} {}\t' + 'Time Stamp: {}') + #For out[i] where i is odd, the device returns human readable units + #('Seconds', etc) (i.e. the keys of the values's dictionnaries). So + #we need to convert them to 'numbers' (i.e. values of the keys). + #For example, the device returns 'Seconds' instead of '0' for out[1] + out[0] = int(out[0]) + out[1] = self.SampleRateUnit[out[1]] + out[2] = int(out[2]) + out[3] = self.SamplePeriodUnit[out[3]] + out[4] = int(out[4]) + if out[5] == 'Continous': # The is a typo in returned value from the + out[5] = 'Continuous' # device! + out[5] = self.TotalDurationUnit[out[5]] + out[6] = 1 if (out[6] == 'ON') else 0 return out - #return self.query('*rds') @sampling.setter def sampling(self, value): @@ -190,20 +185,6 @@ def sampling(self, value): """ self.query('*dsu {} {} {} {} {} {} {}'.format(*value)) - @Action() - def dsu(self, sampleRate, sampleRateUnit, samplePeriod, samplePeriodUnit, - totalDuration, totalDurationUnit, timeStamp,): - """This command provides the data sampling parameters for the logging - and statistics environments. (dsu) - """ - self.query('*dsu {} {} {} {} {} {} {}'.format(sampleRate, - sampleRateUnit, - samplePeriod, - samplePeriodUnit, - totalDuration, - totalDurationUnit, - timeStamp,)) - @Action() def trigger(self, value=True): """This command sets the internal trigger level when using the device @@ -363,7 +344,7 @@ def query(self, command, *, send_args=(None, None), # print(inst.fdl) #buggy # print(inst.get_data) #buggy # inst.scale('100m') - inst.backlight(True) +# inst.backlight(True) #inst.dBm(False) # inst.high_resolution(False) @@ -375,11 +356,25 @@ def query(self, command, *, send_args=(None, None), #inst.status #inst.clk(5,9,2013,17,58,00,'PM') - inst.sampling = ('1', 'Minutes', '700000', 'Seconds', '1', 'Period', 'OFF') + inst.energy_mode(True) + inst.sampling = ('1', '% of pulses', '30', 'Weeks', '3', 'Points', + False) print(inst.sampling) - print(inst.sampling2) + # print(inst.sampling2) + + # #print(inst.status) + # #print(inst.current_value) + # #inst.get_data + + # second = Q_(1, 's') + # minute = Q_(1, 'min') + # hour = Q_(1, 'hour') + # day = Q_(1, 'day') + # week = Q_(1, 'week') - #print(inst.status) - #print(inst.current_value) - #inst.get_data + # print(second) + # print(minute.to('s')) + # print(hour.to('min')) + # print(day.to('hour')) + # print(week.to('day')) From d1473999783a8ea2e2c6c337b5def2462fdeba56 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Mon, 9 Sep 2013 14:13:39 -0400 Subject: [PATCH 20/48] new query status. Now put result in an internal variable for later retrival by fake getters --- lantz/drivers/newport/842PE.py | 111 +++++++++++++++++++++++++++------ 1 file changed, 93 insertions(+), 18 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 80f9278..607275a 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -201,6 +201,9 @@ def esu(self, value=True): """ self.query('*esu {}'.format(value)) + # IMPORTANT: + # energy_mode cannot be activated with photodiodes + # Should prevent this because it creates an error @Action(values={False: 0, True: 1}) def energy_mode(self, value): """This command is used to toggle the Energy mode when using a high @@ -238,18 +241,86 @@ def idn_head(self): """ return self.query('*hea') - #The device is a bit buggy for this one as it return the info with 3 \n\r. - #So the hack here repare it. + DeviceStatus = {} + + # The device is a bit buggy for this one as it return the info with 3 \n\r. + # So the hack here repare it. + # We have to read it 3 times. + # In addition, it seems to never return the last field (dBm). @Feat() def status(self): - """This command is used to view data that is relevant to the current - detector head. (sta) + """This command is used to query the current device status. (sta) + It stores it in self.Device Status for later retrival by other query + function. """ - out = '' - out += self.query('*sta') - out += '\t{}'.format(self.recv()) - out += '\t{}'.format(self.recv()) - return out + out1 = self.parse_query('*sta', format='Head Type: {}\t' + 'Head Version: {}\t' + 'Head Serial Number: {}\t{}\t' + 'Calibration Sensitivity: {} V/W\t' + 'Default WaveLength: {} nm\t' + 'Active Sensitivity: {} V/W\t' + 'Active WaveLength: {} nm\t' + 'Scale Min Power : {}\t' + 'Scale Max Power: {}\t' + 'Scale Min Energy : {}\t' + 'Scale Max Energy: {}\t' + 'Current Scale: {}\t' + 'Energy Mode: {}\t' + 'Anticipation: {}\t' + 'Trig Level: {}%\t' + 'Zero Offset: {}\t' + 'Multiplier #1: {}\t' + 'Offset #1: {}\t' + 'Multiplier #2: {}\t' + 'Offset #2: {}\t' + 'Currently Logging data: {}\t' + 'Analog Output: {}\t' + 'Resolution: {}\t' + 'Currently Calculating Stats: {}\t' + 'High Resolution Display: {}\t' + 'Min Wavelength index: {}\t' + 'Max Wavelength index: {}\t' + 'Upper Bound: {}\t' + 'Lower Bound: {}\t' + 'Reference Value: {}\t' + 'P/F Status: {}\t' + 'Threshold: {}') + out1.append(self.parse_query('', format='Attenuator: {}')) + out1.append(self.parse_query('', format='AutoScale: {}')) + + self.DeviceStatus['HeadType'] = out1[0] # WattMeter, Photodiode + #self.DeviceStatus['Head Version'] = out1[1] # Is that really the head version? + self.DeviceStatus['SerialNumber'] = out1[2] + self.DeviceStatus['HeadName'] = out1[3] + self.DeviceStatus['CalibrationSensitivity'] = out1[4] # unit V/W + self.DeviceStatus['CalibrationWavelength'] = out1[5] # unit nm, seems non-sense for photodiode + self.DeviceStatus['ActiveSensitivity'] = out1[6] # unit V/W + self.DeviceStatus['ActiveWavelength'] = out1[7] # unit nm + self.DeviceStatus['ScaleMinPower'] = out1[8] + self.DeviceStatus['ScaleMaxPower'] = out1[9] + self.DeviceStatus['ScaleMinEnergy'] = out1[10] # is N/A for photodiodes + self.DeviceStatus['ScaleMaxEnergy'] = out1[11] # is N/A for photodiodes + self.DeviceStatus['CurrentScale'] = out1[12] + self.DeviceStatus['EnergyMode'] = 1 if (out1[13] == 'On') else 0 + self.DeviceStatus['Anticipation'] = 1 if (out1[14] == 'On') else 0 + self.DeviceStatus['TrigLevel'] = out1[15] # unit % + self.DeviceStatus['ZeroOffset'] = out1[16] + self.DeviceStatus['Multiplier'] = [out1[17], out1[19]] + self.DeviceStatus['Offset'] = [out1[18], out1[20]] + self.DeviceStatus['CurrentlyLoggingdata'] = 1 if (out1[21] == 'Yes') else 0 + self.DeviceStatus['AnalogOutput'] = 1 if (out1[22] == 'On') else 0 + self.DeviceStatus['Resolution'] = out1[23] + self.DeviceStatus['CurrentlyCalculatingStats'] = 1 if (out1[24] == 'Yes') else 0 + self.DeviceStatus['HighResolutionDisplay'] = 1 if (out1[25] == 'On') else 0 + self.DeviceStatus['MinWavelengthindex'] = out1[26] # For photodiodes, it's the minimum wavelength in nm + self.DeviceStatus['MaxWavelengthindex'] = out1[27] # For photodiodes, it's the minimum wavelength in nm + self.DeviceStatus['UpperBound'] = out1[28] + self.DeviceStatus['LowerBound'] = out1[29] + self.DeviceStatus['ReferenceValue'] = out1[30] + self.DeviceStatus['P/FStatus'] = out1[31] # N/A, .... (To be tested) + self.DeviceStatus['Threshold'] = out1[32] # On, Off (To be tested) + self.DeviceStatus['Attenuator'] = 1 if (out1[33] == 'On') else 0 # On, Off or N/A. N/A is when there is not + self.DeviceStatus['AutoScale'] = 1 if (out1[34] == 'On') else 0 @Feat() def battery(self): @@ -330,9 +401,9 @@ def query(self, command, *, send_args=(None, None), # time.sleep(1) # inst.display('real-time') # print(inst.idn) -# inst.logging('save both') + inst.logging('save both') # time.sleep(1) -# inst.logging('stop') + inst.logging('stop') # print(inst.fdl(1)) # print(inst.get_data) # while 1: @@ -344,9 +415,9 @@ def query(self, command, *, send_args=(None, None), # print(inst.fdl) #buggy # print(inst.get_data) #buggy # inst.scale('100m') -# inst.backlight(True) + inst.backlight(True) #inst.dBm(False) -# inst.high_resolution(False) + inst.high_resolution(True) # print(inst.status) # print(inst.idn_head) @@ -356,14 +427,18 @@ def query(self, command, *, send_args=(None, None), #inst.status #inst.clk(5,9,2013,17,58,00,'PM') - inst.energy_mode(True) - inst.sampling = ('1', '% of pulses', '30', 'Weeks', '3', 'Points', - False) - print(inst.sampling) + #inst.energy_mode(True) + #inst.sampling = ('1', '% of pulses', '30', 'Weeks', '3', 'Points', + # False) + #print(inst.sampling) # print(inst.sampling2) - # #print(inst.status) + inst.anticipation(False) + inst.analog_port(True) + inst.attenuator(False) + inst.esu('disable') + inst.status # #print(inst.current_value) # #inst.get_data From 9171be8c8b857e63b189b1019cda0e3234b7d565 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Tue, 10 Sep 2013 12:26:02 -0400 Subject: [PATCH 21/48] how to fake a getter --- lantz/drivers/newport/842PE.py | 104 ++++++++++++++++++++------------- 1 file changed, 63 insertions(+), 41 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 607275a..2b52acd 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -30,6 +30,11 @@ class N842PE(SerialDriver): PARITY = 'none' STOPBITS = 1 + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.initialize() + self.DeviceStatus = self.status # Read the device status + #Display commands @Action(values={'real-time': 0, 'histogram': 1, 'statistic': 2, @@ -40,17 +45,25 @@ def display(self, value): """ self.query('*sdu {}'.format(value)) - @Action(values=set(('auto', '1p', '3p', '10p', '30p', '100p', '300p', '1n', - '3n', '10n', '30n', '100n', '300n', '1u', '3u', '10u', - '30u', '100u', '300u', '1m', '3m', '10m', '30m', - '100m', '300m', '1', '3', '10', '30', '100', '300', - '1k', '3k', '10k', '30k', '100k', '300k', '1M', '3M', - '10M', '30M', '100M', '300M',))) + Scales = ('auto', '1p', '3p', '10p', '30p', '100p', '300p', '1n', + '3n', '10n', '30n', '100n', '300n', '1u', '3u', '10u', + '30u', '100u', '300u', '1m', '3m', '10m', '30m', + '100m', '300m', '1', '3', '10', '30', '100', '300', + '1k', '3k', '10k', '30k', '100k', '300k', '1M', '3M', + '10M', '30M', '100M', '300M',) + + @Feat(values=set(Scales)) + def scale(self): + out = self.DeviceStatus['CurrentScale'] + return self.Scales[out] + + @scale.setter def scale(self, value): """This command is used to force the display of the current data into a specific range. (ssa) """ self.query('*ssa {}'.format(value)) + self.DeviceStatus = self.status # update cached device status @Action(values={False: 0, True: 1}) def dBm(self, value): @@ -241,8 +254,6 @@ def idn_head(self): """ return self.query('*hea') - DeviceStatus = {} - # The device is a bit buggy for this one as it return the info with 3 \n\r. # So the hack here repare it. # We have to read it 3 times. @@ -253,6 +264,7 @@ def status(self): It stores it in self.Device Status for later retrival by other query function. """ + DeviceStatus = {} out1 = self.parse_query('*sta', format='Head Type: {}\t' 'Head Version: {}\t' 'Head Serial Number: {}\t{}\t' @@ -288,39 +300,41 @@ def status(self): out1.append(self.parse_query('', format='Attenuator: {}')) out1.append(self.parse_query('', format='AutoScale: {}')) - self.DeviceStatus['HeadType'] = out1[0] # WattMeter, Photodiode - #self.DeviceStatus['Head Version'] = out1[1] # Is that really the head version? - self.DeviceStatus['SerialNumber'] = out1[2] - self.DeviceStatus['HeadName'] = out1[3] - self.DeviceStatus['CalibrationSensitivity'] = out1[4] # unit V/W - self.DeviceStatus['CalibrationWavelength'] = out1[5] # unit nm, seems non-sense for photodiode - self.DeviceStatus['ActiveSensitivity'] = out1[6] # unit V/W - self.DeviceStatus['ActiveWavelength'] = out1[7] # unit nm - self.DeviceStatus['ScaleMinPower'] = out1[8] - self.DeviceStatus['ScaleMaxPower'] = out1[9] - self.DeviceStatus['ScaleMinEnergy'] = out1[10] # is N/A for photodiodes - self.DeviceStatus['ScaleMaxEnergy'] = out1[11] # is N/A for photodiodes - self.DeviceStatus['CurrentScale'] = out1[12] - self.DeviceStatus['EnergyMode'] = 1 if (out1[13] == 'On') else 0 - self.DeviceStatus['Anticipation'] = 1 if (out1[14] == 'On') else 0 - self.DeviceStatus['TrigLevel'] = out1[15] # unit % - self.DeviceStatus['ZeroOffset'] = out1[16] - self.DeviceStatus['Multiplier'] = [out1[17], out1[19]] - self.DeviceStatus['Offset'] = [out1[18], out1[20]] - self.DeviceStatus['CurrentlyLoggingdata'] = 1 if (out1[21] == 'Yes') else 0 - self.DeviceStatus['AnalogOutput'] = 1 if (out1[22] == 'On') else 0 - self.DeviceStatus['Resolution'] = out1[23] - self.DeviceStatus['CurrentlyCalculatingStats'] = 1 if (out1[24] == 'Yes') else 0 - self.DeviceStatus['HighResolutionDisplay'] = 1 if (out1[25] == 'On') else 0 - self.DeviceStatus['MinWavelengthindex'] = out1[26] # For photodiodes, it's the minimum wavelength in nm - self.DeviceStatus['MaxWavelengthindex'] = out1[27] # For photodiodes, it's the minimum wavelength in nm - self.DeviceStatus['UpperBound'] = out1[28] - self.DeviceStatus['LowerBound'] = out1[29] - self.DeviceStatus['ReferenceValue'] = out1[30] - self.DeviceStatus['P/FStatus'] = out1[31] # N/A, .... (To be tested) - self.DeviceStatus['Threshold'] = out1[32] # On, Off (To be tested) - self.DeviceStatus['Attenuator'] = 1 if (out1[33] == 'On') else 0 # On, Off or N/A. N/A is when there is not - self.DeviceStatus['AutoScale'] = 1 if (out1[34] == 'On') else 0 + DeviceStatus['HeadType'] = out1[0] # WattMeter, Photodiode + #DeviceStatus['Head Version'] = out1[1] # Is that really the head version? + DeviceStatus['SerialNumber'] = out1[2] + DeviceStatus['HeadName'] = out1[3] + DeviceStatus['CalibrationSensitivity'] = out1[4] # unit V/W + DeviceStatus['CalibrationWavelength'] = out1[5] # unit nm, seems non-sense for photodiode + DeviceStatus['ActiveSensitivity'] = out1[6] # unit V/W + DeviceStatus['ActiveWavelength'] = out1[7] # unit nm + DeviceStatus['ScaleMinPower'] = out1[8] + DeviceStatus['ScaleMaxPower'] = out1[9] + DeviceStatus['ScaleMinEnergy'] = out1[10] # is N/A for photodiodes + DeviceStatus['ScaleMaxEnergy'] = out1[11] # is N/A for photodiodes + DeviceStatus['CurrentScale'] = int(out1[12]) + DeviceStatus['EnergyMode'] = 1 if (out1[13] == 'On') else 0 + DeviceStatus['Anticipation'] = 1 if (out1[14] == 'On') else 0 + DeviceStatus['TrigLevel'] = out1[15] # unit % + DeviceStatus['ZeroOffset'] = out1[16] + DeviceStatus['Multiplier'] = [out1[17], out1[19]] + DeviceStatus['Offset'] = [out1[18], out1[20]] + DeviceStatus['CurrentlyLoggingdata'] = 1 if (out1[21] == 'Yes') else 0 + DeviceStatus['AnalogOutput'] = 1 if (out1[22] == 'On') else 0 + DeviceStatus['Resolution'] = out1[23] + DeviceStatus['CurrentlyCalculatingStats'] = 1 if (out1[24] == 'Yes') else 0 + DeviceStatus['HighResolutionDisplay'] = 1 if (out1[25] == 'On') else 0 + DeviceStatus['MinWavelengthindex'] = out1[26] # For photodiodes, it's the minimum wavelength in nm + DeviceStatus['MaxWavelengthindex'] = out1[27] # For photodiodes, it's the minimum wavelength in nm + DeviceStatus['UpperBound'] = out1[28] + DeviceStatus['LowerBound'] = out1[29] + DeviceStatus['ReferenceValue'] = out1[30] + DeviceStatus['P/FStatus'] = out1[31] # N/A, .... (To be tested) + DeviceStatus['Threshold'] = out1[32] # On, Off (To be tested) + DeviceStatus['Attenuator'] = 1 if (out1[33] == 'On') else 0 # On, Off or N/A. N/A is when there is not + DeviceStatus['AutoScale'] = 1 if (out1[34] == 'On') else 0 + + return DeviceStatus @Feat() def battery(self): @@ -453,3 +467,11 @@ def query(self, command, *, send_args=(None, None), # print(hour.to('min')) # print(day.to('hour')) # print(week.to('day')) + + inst.scale = '30u' + print(inst.scale) + + time.sleep(1) + print(inst.scale) + inst.scale = '300n' + print(inst.scale) From 6796e6cd90419e42ddb8fea9e82914a7c142ca09 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Tue, 10 Sep 2013 16:06:15 -0400 Subject: [PATCH 22/48] in @Feat status, read directly in a dictionary --- lantz/drivers/newport/842PE.py | 157 ++++++++++++++++----------------- 1 file changed, 74 insertions(+), 83 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 2b52acd..bbcbaab 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -34,7 +34,7 @@ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.initialize() self.DeviceStatus = self.status # Read the device status - + #Display commands @Action(values={'real-time': 0, 'histogram': 1, 'statistic': 2, @@ -51,7 +51,7 @@ def display(self, value): '100m', '300m', '1', '3', '10', '30', '100', '300', '1k', '3k', '10k', '30k', '100k', '300k', '1M', '3M', '10M', '30M', '100M', '300M',) - + @Feat(values=set(Scales)) def scale(self): out = self.DeviceStatus['CurrentScale'] @@ -63,7 +63,7 @@ def scale(self, value): specific range. (ssa) """ self.query('*ssa {}'.format(value)) - self.DeviceStatus = self.status # update cached device status + self.DeviceStatus = self.status # update cached device status @Action(values={False: 0, True: 1}) def dBm(self, value): @@ -255,8 +255,7 @@ def idn_head(self): return self.query('*hea') # The device is a bit buggy for this one as it return the info with 3 \n\r. - # So the hack here repare it. - # We have to read it 3 times. + # So the hack here: we have to read it 3 times to read everything # In addition, it seems to never return the last field (dBm). @Feat() def status(self): @@ -265,75 +264,67 @@ def status(self): function. """ DeviceStatus = {} - out1 = self.parse_query('*sta', format='Head Type: {}\t' - 'Head Version: {}\t' - 'Head Serial Number: {}\t{}\t' - 'Calibration Sensitivity: {} V/W\t' - 'Default WaveLength: {} nm\t' - 'Active Sensitivity: {} V/W\t' - 'Active WaveLength: {} nm\t' - 'Scale Min Power : {}\t' - 'Scale Max Power: {}\t' - 'Scale Min Energy : {}\t' - 'Scale Max Energy: {}\t' - 'Current Scale: {}\t' - 'Energy Mode: {}\t' - 'Anticipation: {}\t' - 'Trig Level: {}%\t' - 'Zero Offset: {}\t' - 'Multiplier #1: {}\t' - 'Offset #1: {}\t' - 'Multiplier #2: {}\t' - 'Offset #2: {}\t' - 'Currently Logging data: {}\t' - 'Analog Output: {}\t' - 'Resolution: {}\t' - 'Currently Calculating Stats: {}\t' - 'High Resolution Display: {}\t' - 'Min Wavelength index: {}\t' - 'Max Wavelength index: {}\t' - 'Upper Bound: {}\t' - 'Lower Bound: {}\t' - 'Reference Value: {}\t' - 'P/F Status: {}\t' - 'Threshold: {}') - out1.append(self.parse_query('', format='Attenuator: {}')) - out1.append(self.parse_query('', format='AutoScale: {}')) - - DeviceStatus['HeadType'] = out1[0] # WattMeter, Photodiode - #DeviceStatus['Head Version'] = out1[1] # Is that really the head version? - DeviceStatus['SerialNumber'] = out1[2] - DeviceStatus['HeadName'] = out1[3] - DeviceStatus['CalibrationSensitivity'] = out1[4] # unit V/W - DeviceStatus['CalibrationWavelength'] = out1[5] # unit nm, seems non-sense for photodiode - DeviceStatus['ActiveSensitivity'] = out1[6] # unit V/W - DeviceStatus['ActiveWavelength'] = out1[7] # unit nm - DeviceStatus['ScaleMinPower'] = out1[8] - DeviceStatus['ScaleMaxPower'] = out1[9] - DeviceStatus['ScaleMinEnergy'] = out1[10] # is N/A for photodiodes - DeviceStatus['ScaleMaxEnergy'] = out1[11] # is N/A for photodiodes - DeviceStatus['CurrentScale'] = int(out1[12]) - DeviceStatus['EnergyMode'] = 1 if (out1[13] == 'On') else 0 - DeviceStatus['Anticipation'] = 1 if (out1[14] == 'On') else 0 - DeviceStatus['TrigLevel'] = out1[15] # unit % - DeviceStatus['ZeroOffset'] = out1[16] - DeviceStatus['Multiplier'] = [out1[17], out1[19]] - DeviceStatus['Offset'] = [out1[18], out1[20]] - DeviceStatus['CurrentlyLoggingdata'] = 1 if (out1[21] == 'Yes') else 0 - DeviceStatus['AnalogOutput'] = 1 if (out1[22] == 'On') else 0 - DeviceStatus['Resolution'] = out1[23] - DeviceStatus['CurrentlyCalculatingStats'] = 1 if (out1[24] == 'Yes') else 0 - DeviceStatus['HighResolutionDisplay'] = 1 if (out1[25] == 'On') else 0 - DeviceStatus['MinWavelengthindex'] = out1[26] # For photodiodes, it's the minimum wavelength in nm - DeviceStatus['MaxWavelengthindex'] = out1[27] # For photodiodes, it's the minimum wavelength in nm - DeviceStatus['UpperBound'] = out1[28] - DeviceStatus['LowerBound'] = out1[29] - DeviceStatus['ReferenceValue'] = out1[30] - DeviceStatus['P/FStatus'] = out1[31] # N/A, .... (To be tested) - DeviceStatus['Threshold'] = out1[32] # On, Off (To be tested) - DeviceStatus['Attenuator'] = 1 if (out1[33] == 'On') else 0 # On, Off or N/A. N/A is when there is not - DeviceStatus['AutoScale'] = 1 if (out1[34] == 'On') else 0 - + out = self.parse_query('*sta', format='Head Type: {[HeadType]}\t' # WattMeter, Photodiode + 'Head Version: {[HeadVersion]}\t' # Is that really the head version? + 'Head Serial Number: {[HeadSerialNumber]}\t{[HeadName]}\t' + 'Calibration Sensitivity: {[CalibrationSensitivity]:f} V/W\t' # unit V/W + 'Default WaveLength: {[CalibrationWavelength]:f} nm\t' # unit nm, seems non-sense for photodiode + 'Active Sensitivity: {[ActiveSensitivity]:f} V/W\t' # unit V/W + 'Active WaveLength: {[ActiveWaveLength]:f} nm\t' # unit nm + 'Scale Min Power : {[ScaleMinPower]:d}\t' + 'Scale Max Power: {[ScaleMaxPower]:d}\t' + 'Scale Min Energy : {[ScaleMinEnergy]}\t' # is N/A for photodiodes + 'Scale Max Energy: {[ScaleMaxEnergy]}\t' # is N/A for photodiodes + 'Current Scale: {[CurrentScale]:d}\t' + 'Energy Mode: {[EnergyMode]}\t' + 'Anticipation: {[Anticipation]}\t' + 'Trig Level: {[TrigLevel]:f}%\t' # unit % + 'Zero Offset: {[Zero Offset]:f}\t' + 'Multiplier #1: {[Multiplier1]:f}\t' + 'Offset #1: {[Offset1]:f}\t' + 'Multiplier #2: {[Multiplier2]:f}\t' + 'Offset #2: {[Offset2]}\t' + 'Currently Logging data: {[CurrentlyLoggingData]}\t' + 'Analog Output: {[AnalogOutput]}\t' + 'Resolution: {[Resolution]:f}\t' + 'Currently Calculating Stats: {[CurrentlyCalculatingStats]}\t' + 'High Resolution Display: {[HighResolutionDisplay]}\t' + 'Min Wavelength index: {[MinWavelengthIndex]:f}\t' # For photodiodes, it's the minimum wavelength in nm + 'Max Wavelength index: {[MaxWavelengthIndex]:f}\t' # For photodiodes, it's the minimum wavelength in nm + 'Upper Bound: {[UpperBound]:f}\t' + 'Lower Bound: {[LowerBound]:f}\t' + 'Reference Value: {[ReferenceValue]:f}\t' + 'P/F Status: {[P/FStatus]}\t' # N/A, .... (To be tested) + 'Threshold: {[Threshold]}') # On, Off (To be tested) + out.append(self.parse_query('', format='Attenuator: {[Attenuator]}')) # add remaining parameters + out.append(self.parse_query('', format='AutoScale: {[AutoScale]}')) # add remaining parameters + + #transform the list of dictionaries in a single dictionary + DeviceStatus = {} + for i in out: + DeviceStatus.update(i) + + DeviceStatus['EnergyMode'] = 1 if (DeviceStatus['EnergyMode'] == 'On') else 0 + DeviceStatus['Anticipation'] = 1 if (DeviceStatus['Anticipation'] == 'On') else 0 + #Merge the two multipliers + DeviceStatus['Multiplier'] = [DeviceStatus['Multiplier1'], DeviceStatus['Multiplier2']] + del DeviceStatus['Multiplier1'] + del DeviceStatus['Multiplier2'] + #Merge the two offsets + DeviceStatus['Offset'] = [DeviceStatus['Offset1'], DeviceStatus['Offset2']] + del DeviceStatus['Offset1'] + del DeviceStatus['Offset2'] + DeviceStatus['CurrentlyLoggingData'] = 1 if (DeviceStatus['CurrentlyLoggingData'] == 'Yes') else 0 + DeviceStatus['AnalogOutput'] = 1 if (DeviceStatus['AnalogOutput'] == 'On') else 0 + DeviceStatus['CurrentlyCalculatingStats'] = 1 if (DeviceStatus['CurrentlyCalculatingStats'] == 'Yes') else 0 + DeviceStatus['HighResolutionDisplay'] = 1 if (DeviceStatus['HighResolutionDisplay'] == 'On') else 0 + DeviceStatus['Attenuator'] = 1 if (DeviceStatus['Attenuator'] == 'On') else 0 # On, Off or N/A. N/A is when there is not + DeviceStatus['AutoScale'] = 1 if (DeviceStatus['AutoScale'] == 'On') else 0 + + #Print dictionary (for debug) + #for key in sorted(DeviceStatus.keys()): + # print ("%s: %s" % (key, DeviceStatus[key])) + return DeviceStatus @Feat() @@ -415,9 +406,9 @@ def query(self, command, *, send_args=(None, None), # time.sleep(1) # inst.display('real-time') # print(inst.idn) - inst.logging('save both') + #inst.logging('save both') # time.sleep(1) - inst.logging('stop') + #inst.logging('stop') # print(inst.fdl(1)) # print(inst.get_data) # while 1: @@ -429,9 +420,9 @@ def query(self, command, *, send_args=(None, None), # print(inst.fdl) #buggy # print(inst.get_data) #buggy # inst.scale('100m') - inst.backlight(True) + #inst.backlight(True) #inst.dBm(False) - inst.high_resolution(True) + #inst.high_resolution(True) # print(inst.status) # print(inst.idn_head) @@ -448,11 +439,11 @@ def query(self, command, *, send_args=(None, None), # print(inst.sampling2) - inst.anticipation(False) - inst.analog_port(True) - inst.attenuator(False) - inst.esu('disable') - inst.status + #inst.anticipation(False) + #inst.analog_port(True) + #inst.attenuator(False) + #inst.esu('disable') + print(inst.status) # #print(inst.current_value) # #inst.get_data From 98a960afd34515ea010f3abcae5a1da6cdddc568 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Tue, 10 Sep 2013 16:44:34 -0400 Subject: [PATCH 23/48] convert some @Action to getter/setter pairs --- lantz/drivers/newport/842PE.py | 77 +++++++++++++++++++++++++++------- 1 file changed, 62 insertions(+), 15 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index bbcbaab..d4891c6 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -8,6 +8,11 @@ :copyright: 2013 by Lantz Authors, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ + +#TODO: Add units +#TODO: status works with head 818-UV, but not with 818P +#TODO: test energy_mode getter/setter + import time import warnings @@ -71,12 +76,20 @@ def dBm(self, value): """ self.query('*dbu {}'.format(value)) - @Action(values={False: 0, True: 1}) + @Feat(values={False: 0, True: 1}) + def high_resolution(self): + """This command is used to add significant digits to the on-screen + reading. (shl) + """ + return self.DeviceStatus['HighResolutionDisplay'] + + @high_resolution.setter def high_resolution(self, value): """This command is used to add significant digits to the on-screen reading. (shl) """ self.query('*shl {}'.format(value)) + self.DeviceStatus = self.status # update cached device status #MEASUREMENT COMMANDS - DATA ACQUISITION @@ -131,26 +144,45 @@ def get_data(self): #MEASUREMENT COMMANDS - SETUP + @Feat() + def wavelength(self): + """This command is used to read the wavelength being used on the + detector. (swa) + """ + return self.DeviceStatus['ActiveWaveLength'] + + @wavelength.setter def wavelength(self, value): - """This command is used to specify the wavelength being used on the + """This command is used to set the wavelength being used on the detector. (swa) """ self.query('*swa {}'.format(value)) + self.DeviceStatus = self.status # update cached device status - @Action(values={False: 0, True: 1}) + @Feat(values={False: 0, True: 1}) + def attenuator(self): + """This command is used to read if whether the detector is using an + external attenuator or not. (atu) + """ + return self.DeviceStatus['Attenuator'] + + @attenuator.setter def attenuator(self, value): """This command is used to adjust the processing of the meter with the readings of the detector, depending on whether the detector is using an external attenuator or not. (atu) """ self.query('*atu {}'.format(value)) + self.DeviceStatus = self.status # update cached device status + #TODO: To be changed to a getter/setter pair @Action(values=(set((1, 2,)), None)) def multiplier(self, value, multiplier): """This command is used to set the value of the multipliers. (smu) """ self.query('*smu {0} {1}'.format(value, multiplier)) + #TODO: To be changed to a getter/setter pair @Action(values=(set((1, 2,)), None)) def offset(self, value, multiplier): """This command is used to set the value of the offsets. (sou) @@ -198,6 +230,7 @@ def sampling(self, value): """ self.query('*dsu {} {} {} {} {} {} {}'.format(*value)) + #TODO: To be changed to a getter/setter pair @Action() def trigger(self, value=True): """This command sets the internal trigger level when using the device @@ -214,22 +247,32 @@ def esu(self, value=True): """ self.query('*esu {}'.format(value)) + @Feat(values={False: 0, True: 1}) + def energy_mode(self): + return self.DeviceStatus['EnergyMode'] + # IMPORTANT: # energy_mode cannot be activated with photodiodes # Should prevent this because it creates an error - @Action(values={False: 0, True: 1}) + @energy_mode.setter def energy_mode(self, value): """This command is used to toggle the Energy mode when using a high power detector. (sca) """ - self.query('*sca {}'.format(value)) + self.query('*csa {}'.format(value)) + self.DeviceStatus = self.status # update cached device status - @Action(values={False: 0, True: 1}) + @Feat(values={False: 0, True: 1}) + def anticipation(self): + return self.DeviceStatus['Anticipation'] + + @anticipation.setter def anticipation(self, value): """This command is used to enable or disable the anticipation processing when the device is reading from a wattmeter. (eaa) """ self.query('*eaa {}'.format(value)) + self.DeviceStatus = self.status # update cached device status @Action(values={'off': 0, 'on': 1, 'undo': 2}) def zero(self, value): @@ -294,8 +337,8 @@ def status(self): 'Upper Bound: {[UpperBound]:f}\t' 'Lower Bound: {[LowerBound]:f}\t' 'Reference Value: {[ReferenceValue]:f}\t' - 'P/F Status: {[P/FStatus]}\t' # N/A, .... (To be tested) - 'Threshold: {[Threshold]}') # On, Off (To be tested) + 'P/F Status: {[P/FStatus]}\t' # N/A, .... (TODO: To be tested) + 'Threshold: {[Threshold]}') # On, Off (TODO: To be tested) out.append(self.parse_query('', format='Attenuator: {[Attenuator]}')) # add remaining parameters out.append(self.parse_query('', format='AutoScale: {[AutoScale]}')) # add remaining parameters @@ -360,12 +403,17 @@ def backlight(self, value=True): """ self.query('*bkl {}'.format(value)) - @Action(values={False: 0, True: 1}) - def analog_port(self, value=True): + @Feat(values={False: 0, True: 1}) + def analog_port(self): + return self.DeviceStatus['AnalogOutput'] + + @analog_port.setter + def analog_port(self, value): """This command is used to enable or disable the output of the current value on the analog port of the meter. (ano) """ self.query('*ano {}'.format(value)) + self.DeviceStatus = self.status # update cached device status #COMMUNICATIONS COMMANDS @@ -459,10 +507,9 @@ def query(self, command, *, send_args=(None, None), # print(day.to('hour')) # print(week.to('day')) - inst.scale = '30u' - print(inst.scale) + inst.energy_mode = True + print(inst.energy_mode) time.sleep(1) - print(inst.scale) - inst.scale = '300n' - print(inst.scale) + inst.energy_mode = False + print(inst.energy_mode) From 3b89594abb79a0acd88fa4ffb0c6bc2557f685e2 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Wed, 11 Sep 2013 14:14:08 -0400 Subject: [PATCH 24/48] status: read a float instead of a int (fix for some heads) --- lantz/drivers/newport/842PE.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index d4891c6..e6dc16a 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -332,15 +332,17 @@ def status(self): 'Resolution: {[Resolution]:f}\t' 'Currently Calculating Stats: {[CurrentlyCalculatingStats]}\t' 'High Resolution Display: {[HighResolutionDisplay]}\t' - 'Min Wavelength index: {[MinWavelengthIndex]:f}\t' # For photodiodes, it's the minimum wavelength in nm - 'Max Wavelength index: {[MaxWavelengthIndex]:f}\t' # For photodiodes, it's the minimum wavelength in nm + #Putting nex two fields as float will produce an error with some heads + 'Min Wavelength index: {[MinWavelengthIndex]:d}\t' # For photodiodes, it's the minimum wavelength in nm + 'Max Wavelength index: {[MaxWavelengthIndex]:d}\t' # For photodiodes, it's the minimum wavelength in nm 'Upper Bound: {[UpperBound]:f}\t' 'Lower Bound: {[LowerBound]:f}\t' 'Reference Value: {[ReferenceValue]:f}\t' 'P/F Status: {[P/FStatus]}\t' # N/A, .... (TODO: To be tested) 'Threshold: {[Threshold]}') # On, Off (TODO: To be tested) - out.append(self.parse_query('', format='Attenuator: {[Attenuator]}')) # add remaining parameters - out.append(self.parse_query('', format='AutoScale: {[AutoScale]}')) # add remaining parameters + # add remaining parameters (see description of this bug just before the function declaration + out.append(self.parse_query('', format='Attenuator: {[Attenuator]}')) + out.append(self.parse_query('', format='AutoScale: {[AutoScale]}')) #transform the list of dictionaries in a single dictionary DeviceStatus = {} From ece508f92fd15770db171316a2ca7f4957cbe18a Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Wed, 11 Sep 2013 15:47:32 -0400 Subject: [PATCH 25/48] all possible getter/setter done --- lantz/drivers/newport/842PE.py | 57 ++++++++++++++++++++++++---------- 1 file changed, 40 insertions(+), 17 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index e6dc16a..085b7c7 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -8,10 +8,9 @@ :copyright: 2013 by Lantz Authors, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ +#Cheched working with following heads: 818-UV, 818P #TODO: Add units -#TODO: status works with head 818-UV, but not with 818P -#TODO: test energy_mode getter/setter import time import warnings @@ -34,6 +33,7 @@ class N842PE(SerialDriver): BYTESIZE = 8 PARITY = 'none' STOPBITS = 1 + TIMEOUT = 1 def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -175,19 +175,35 @@ def attenuator(self, value): self.query('*atu {}'.format(value)) self.DeviceStatus = self.status # update cached device status - #TODO: To be changed to a getter/setter pair + def get_multiplier(self, index): + """This command is used to get the value of one multipliers. (smu) + """ + values = set((1,2)) + if not (index in values): + raise ValueError('%d not in {1, 2}' % (index,)) + return self.DeviceStatus['Multiplier'][index-1] + @Action(values=(set((1, 2,)), None)) def multiplier(self, value, multiplier): """This command is used to set the value of the multipliers. (smu) """ self.query('*smu {0} {1}'.format(value, multiplier)) + self.DeviceStatus = self.status # update cached device status + + def get_offset(self, index): + """This command is used to get the value of one offset. (sou) + """ + values = set((1,2)) + if not (index in values): + raise ValueError('%d not in {1, 2}' % (index,)) + return self.DeviceStatus['Offset'][index-1] - #TODO: To be changed to a getter/setter pair @Action(values=(set((1, 2,)), None)) - def offset(self, value, multiplier): + def offset(self, value, offset): """This command is used to set the value of the offsets. (sou) """ - self.query('*sou {0} {1}'.format(value, multiplier)) + self.query('*sou {0} {1}'.format(value, offset)) + self.DeviceStatus = self.status # update cached device status SampleRateUnit = {'Seconds': '0', 'Minutes': '1', 'Hours': '2', 'Days': '3', '% of pulses': '4'} @@ -230,13 +246,17 @@ def sampling(self, value): """ self.query('*dsu {} {} {} {} {} {} {}'.format(*value)) - #TODO: To be changed to a getter/setter pair - @Action() - def trigger(self, value=True): + @Feat() + def trigger(self): + return self.DeviceStatus['TrigLevel'] + + @trigger.setter + def trigger(self, value): """This command sets the internal trigger level when using the device in energy reading mode. (tla) """ - self.query('*tla {}%'.format(value)) + self.query('*tla {}'.format(value)) + self.DeviceStatus = self.status # update cached device status #MEASUREMENT COMMANDS - MEASUREMENT CONTROL @@ -259,7 +279,7 @@ def energy_mode(self, value): """This command is used to toggle the Energy mode when using a high power detector. (sca) """ - self.query('*csa {}'.format(value)) + self.query('*sca {}'.format(value)) self.DeviceStatus = self.status # update cached device status @Feat(values={False: 0, True: 1}) @@ -326,7 +346,7 @@ def status(self): 'Multiplier #1: {[Multiplier1]:f}\t' 'Offset #1: {[Offset1]:f}\t' 'Multiplier #2: {[Multiplier2]:f}\t' - 'Offset #2: {[Offset2]}\t' + 'Offset #2: {[Offset2]:f}\t' 'Currently Logging data: {[CurrentlyLoggingData]}\t' 'Analog Output: {[AnalogOutput]}\t' 'Resolution: {[Resolution]:f}\t' @@ -509,9 +529,12 @@ def query(self, command, *, send_args=(None, None), # print(day.to('hour')) # print(week.to('day')) - inst.energy_mode = True - print(inst.energy_mode) + inst.offset(1, -1) + print(inst.get_offset(1)) + + inst.offset(2, 2) + print(inst.get_offset(2)) - time.sleep(1) - inst.energy_mode = False - print(inst.energy_mode) +# time.sleep(2) +# inst.multiplier(2, 2) +# print(inst.get_multiplier(2)) From a1da7cfde6318f4c2df7dd064e9e6ad460ae4e56 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Wed, 11 Sep 2013 16:15:04 -0400 Subject: [PATCH 26/48] add pint (units) --- lantz/drivers/newport/842PE.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 085b7c7..17e1d7a 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -10,15 +10,14 @@ """ #Cheched working with following heads: 818-UV, 818P -#TODO: Add units - import time import warnings -from lantz import Action, Feat +from lantz import Action, Feat, Q_ from lantz.serial import SerialDriver from lantz.errors import InstrumentError +nanometer = Q_(1, 'nm') class N842PE(SerialDriver): """Newport 842-PE powermeter @@ -368,6 +367,9 @@ def status(self): DeviceStatus = {} for i in out: DeviceStatus.update(i) + + DeviceStatus['ActiveWavelength'] = Q_(DeviceStatus['ActiveWavelength'], nanometer) + DeviceStatus['CalibrationWavelength'] = Q_(DeviceStatus['CalibrationWavelength'], nanometer) DeviceStatus['EnergyMode'] = 1 if (DeviceStatus['EnergyMode'] == 'On') else 0 DeviceStatus['Anticipation'] = 1 if (DeviceStatus['Anticipation'] == 'On') else 0 @@ -529,11 +531,11 @@ def query(self, command, *, send_args=(None, None), # print(day.to('hour')) # print(week.to('day')) - inst.offset(1, -1) - print(inst.get_offset(1)) + #inst.offset(1, -1) + #print(inst.get_offset(1)) - inst.offset(2, 2) - print(inst.get_offset(2)) + #inst.offset(2, 2) + #print(inst.get_offset(2)) # time.sleep(2) # inst.multiplier(2, 2) From 744103ca6ae42249934ed4e1bf9fde55c71b61c2 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Wed, 11 Sep 2013 16:54:01 -0400 Subject: [PATCH 27/48] prevent energy_mode with photodiode, split multiplies in 2, same for offsets --- lantz/drivers/newport/842PE.py | 107 ++++++++++++++++++++++----------- 1 file changed, 73 insertions(+), 34 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 17e1d7a..1946d04 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -174,34 +174,56 @@ def attenuator(self, value): self.query('*atu {}'.format(value)) self.DeviceStatus = self.status # update cached device status - def get_multiplier(self, index): - """This command is used to get the value of one multipliers. (smu) + @Feat() + def multiplier1(self): + """This command is used to get the value multiplier1. (smu) """ - values = set((1,2)) - if not (index in values): - raise ValueError('%d not in {1, 2}' % (index,)) - return self.DeviceStatus['Multiplier'][index-1] + return self.DeviceStatus['Multiplier'][0] - @Action(values=(set((1, 2,)), None)) - def multiplier(self, value, multiplier): - """This command is used to set the value of the multipliers. (smu) + @multiplier1.setter + def multiplier1(self, multiplier): + """This command is used to set the value of multiplier1. (smu) """ - self.query('*smu {0} {1}'.format(value, multiplier)) + self.query('*smu 1 {}'.format(multiplier)) self.DeviceStatus = self.status # update cached device status - def get_offset(self, index): - """This command is used to get the value of one offset. (sou) + @Feat() + def multiplier2(self): + """This command is used to get the value multiplier2. (smu) """ - values = set((1,2)) - if not (index in values): - raise ValueError('%d not in {1, 2}' % (index,)) - return self.DeviceStatus['Offset'][index-1] + return self.DeviceStatus['Multiplier'][1] - @Action(values=(set((1, 2,)), None)) - def offset(self, value, offset): - """This command is used to set the value of the offsets. (sou) + @multiplier2.setter + def multiplier2(self, multiplier): + """This command is used to set the value multiplier2. (smu) """ - self.query('*sou {0} {1}'.format(value, offset)) + self.query('*smu 2 {}'.format(multiplier)) + self.DeviceStatus = self.status # update cached device status + + @Feat() + def offset1(self): + """This command is used to get the value offset1. (sou) + """ + return self.DeviceStatus['Offset'][0] + + @offset1.setter + def offset1(self, offset): + """This command is used to set the value of offset1. (sou) + """ + self.query('*sou 1 {}'.format(offset)) + self.DeviceStatus = self.status # update cached device status + + @Feat() + def offset2(self): + """This command is used to get the value offset2. (sou) + """ + return self.DeviceStatus['Offset'][1] + + @offset2.setter + def offset2(self, offset): + """This command is used to set the value of offset2. (sou) + """ + self.query('*sou 2 {}'.format(offset)) self.DeviceStatus = self.status # update cached device status SampleRateUnit = {'Seconds': '0', 'Minutes': '1', 'Hours': '2', @@ -270,16 +292,16 @@ def esu(self, value=True): def energy_mode(self): return self.DeviceStatus['EnergyMode'] - # IMPORTANT: - # energy_mode cannot be activated with photodiodes - # Should prevent this because it creates an error @energy_mode.setter def energy_mode(self, value): """This command is used to toggle the Energy mode when using a high power detector. (sca) """ - self.query('*sca {}'.format(value)) - self.DeviceStatus = self.status # update cached device status + if not(self.DeviceStatus['HeadType'] in 'Photodiode'): + self.query('*sca {}'.format(value)) + self.DeviceStatus = self.status # update cached device status + else: # energy_mode cannot be activated with photodiodes + warnings.warn('Cannot put energy_mode True with a Photodiode') @Feat(values={False: 0, True: 1}) def anticipation(self): @@ -332,7 +354,7 @@ def status(self): 'Calibration Sensitivity: {[CalibrationSensitivity]:f} V/W\t' # unit V/W 'Default WaveLength: {[CalibrationWavelength]:f} nm\t' # unit nm, seems non-sense for photodiode 'Active Sensitivity: {[ActiveSensitivity]:f} V/W\t' # unit V/W - 'Active WaveLength: {[ActiveWaveLength]:f} nm\t' # unit nm + 'Active WaveLength: {[ActiveWavelength]:f} nm\t' # unit nm 'Scale Min Power : {[ScaleMinPower]:d}\t' 'Scale Max Power: {[ScaleMaxPower]:d}\t' 'Scale Min Energy : {[ScaleMinEnergy]}\t' # is N/A for photodiodes @@ -363,21 +385,23 @@ def status(self): out.append(self.parse_query('', format='Attenuator: {[Attenuator]}')) out.append(self.parse_query('', format='AutoScale: {[AutoScale]}')) - #transform the list of dictionaries in a single dictionary + # transform the list of dictionaries in a single dictionary DeviceStatus = {} for i in out: DeviceStatus.update(i) - + + # units DeviceStatus['ActiveWavelength'] = Q_(DeviceStatus['ActiveWavelength'], nanometer) DeviceStatus['CalibrationWavelength'] = Q_(DeviceStatus['CalibrationWavelength'], nanometer) + # DeviceStatus['EnergyMode'] = 1 if (DeviceStatus['EnergyMode'] == 'On') else 0 DeviceStatus['Anticipation'] = 1 if (DeviceStatus['Anticipation'] == 'On') else 0 - #Merge the two multipliers + # Merge the two multipliers DeviceStatus['Multiplier'] = [DeviceStatus['Multiplier1'], DeviceStatus['Multiplier2']] del DeviceStatus['Multiplier1'] del DeviceStatus['Multiplier2'] - #Merge the two offsets + # Merge the two offsets DeviceStatus['Offset'] = [DeviceStatus['Offset1'], DeviceStatus['Offset2']] del DeviceStatus['Offset1'] del DeviceStatus['Offset2'] @@ -531,11 +555,26 @@ def query(self, command, *, send_args=(None, None), # print(day.to('hour')) # print(week.to('day')) - #inst.offset(1, -1) - #print(inst.get_offset(1)) + inst.energy_mode = False + print(inst.energy_mode) + + time.sleep(2) + inst.energy_mode = False + print(inst.energy_mode) + + + inst.offset1 = -2 + print(inst.offset1) + inst.offset2 = 34.3 + print(inst.offset2) + + inst.multiplier1 = .5 + print(inst.multiplier1) + inst.multiplier2 = 1 + print(inst.multiplier2) - #inst.offset(2, 2) - #print(inst.get_offset(2)) + #inst.multiplier(2, 2) + #print(inst.get_multiplier(2)) # time.sleep(2) # inst.multiplier(2, 2) From 1a3f84744dbfe1b1ec6848c98755a290cace5407 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Wed, 11 Sep 2013 17:26:37 -0400 Subject: [PATCH 28/48] add unit for returned current_value --- lantz/drivers/newport/842PE.py | 95 ++++++++-------------------------- 1 file changed, 21 insertions(+), 74 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 1946d04..034268e 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -18,6 +18,8 @@ from lantz.errors import InstrumentError nanometer = Q_(1, 'nm') +watt = Q_(1, 'W') +joule = Q_(1, 'J') class N842PE(SerialDriver): """Newport 842-PE powermeter @@ -98,9 +100,14 @@ def current_value(self): displayed on the device’s screen. The value is displayed in Watts or in Joules (not in dBm). (cvu) """ - return self.parse_query('*cvu', - format='Current Value: {}') - + out = float(self.parse_query('*cvu', + format='Current Value: {}')) + print(out) + if self.energy_mode: + return Q_(out, joule) + else: + return Q_(out, watt) + @Feat(values={False: 'New Data Not Available', True: 'New Data Available'}) def value_available(self): """This command is used to check whether a new value is available from @@ -348,7 +355,7 @@ def status(self): function. """ DeviceStatus = {} - out = self.parse_query('*sta', format='Head Type: {[HeadType]}\t' # WattMeter, Photodiode + out = self.parse_query('*sta', format='Head Type: {[HeadType]}\t' # WattMeter, Photodiode, others? 'Head Version: {[HeadVersion]}\t' # Is that really the head version? 'Head Serial Number: {[HeadSerialNumber]}\t{[HeadName]}\t' 'Calibration Sensitivity: {[CalibrationSensitivity]:f} V/W\t' # unit V/W @@ -491,91 +498,31 @@ def query(self, command, *, send_args=(None, None), help='Serial port to connect to') args = parser.parse_args() - lantz.log.log_to_screen(lantz.log.DEBUG) + lantz.log.log_to_screen(lantz.log.INFO) with N842PE(args.port) as inst: if args.interactive: from lantz.ui.qtwidgets import start_test_app start_test_app(inst) else: print('Testing instrument...') -# inst.display('needle') -# time.sleep(1) -# inst.display('real-time') -# print(inst.idn) - #inst.logging('save both') -# time.sleep(1) - #inst.logging('stop') -# print(inst.fdl(1)) -# print(inst.get_data) -# while 1: -# time.sleep(.1) -# print(inst.current_value) - -# if inst.value_available: -# print(inst.current_value) -# print(inst.fdl) #buggy -# print(inst.get_data) #buggy -# inst.scale('100m') - #inst.backlight(True) - #inst.dBm(False) - #inst.high_resolution(True) - -# print(inst.status) -# print(inst.idn_head) -# print(inst.battery) -# print(inst.status) -# inst.zero('on') - #inst.status - #inst.clk(5,9,2013,17,58,00,'PM') - - #inst.energy_mode(True) - #inst.sampling = ('1', '% of pulses', '30', 'Weeks', '3', 'Points', - # False) - #print(inst.sampling) - - # print(inst.sampling2) - - #inst.anticipation(False) - #inst.analog_port(True) - #inst.attenuator(False) - #inst.esu('disable') print(inst.status) - # #print(inst.current_value) - # #inst.get_data - - # second = Q_(1, 's') - # minute = Q_(1, 'min') - # hour = Q_(1, 'hour') - # day = Q_(1, 'day') - # week = Q_(1, 'week') - # print(second) - # print(minute.to('s')) - # print(hour.to('min')) - # print(day.to('hour')) - # print(week.to('day')) + #inst.energy_mode = False + #print(inst.energy_mode) - inst.energy_mode = False - print(inst.energy_mode) + #time.sleep(2) + #inst.energy_mode = True + #print(inst.energy_mode) - time.sleep(2) - inst.energy_mode = False - print(inst.energy_mode) - - inst.offset1 = -2 + inst.offset1 = 0 print(inst.offset1) - inst.offset2 = 34.3 + inst.offset2 = 0 print(inst.offset2) - inst.multiplier1 = .5 + inst.multiplier1 = 1 print(inst.multiplier1) inst.multiplier2 = 1 print(inst.multiplier2) - #inst.multiplier(2, 2) - #print(inst.get_multiplier(2)) - -# time.sleep(2) -# inst.multiplier(2, 2) -# print(inst.get_multiplier(2)) + print(inst.current_value) From 10588b22fe08e538f467ab5055953d96507c4a05 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Thu, 12 Sep 2013 12:15:54 -0400 Subject: [PATCH 29/48] convert Actions->setters, add send_command() --- lantz/drivers/newport/842PE.py | 151 +++++++++++++++++++++------------ 1 file changed, 97 insertions(+), 54 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 034268e..61cb612 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -8,7 +8,8 @@ :copyright: 2013 by Lantz Authors, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ -#Cheched working with following heads: 818-UV, 818P +# Cheched working with following heads: 818-UV, 818P +# import time import warnings @@ -27,6 +28,13 @@ class N842PE(SerialDriver): ENCODING = 'ascii' + # This string is returned by the device when the action/setter is done + # It is needeed because when there is an error it looks like this: + # 'Error 26: Option only available with photodiode\r\nACK\r\n' + # So if we just detect a RECV_TERMINATION the next query will be polluted + # To use a command/setter, we then should use send_command() instead of query() + RECV_DONE = 'ACK\r\n' + RECV_TERMINATION = '\r\n' SEND_TERMINATION = '\r\n' @@ -34,8 +42,8 @@ class N842PE(SerialDriver): BYTESIZE = 8 PARITY = 'none' STOPBITS = 1 - TIMEOUT = 1 + #TODO: is this functin complete? def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.initialize() @@ -43,13 +51,14 @@ def __init__(self, *args, **kwargs): #Display commands - @Action(values={'real-time': 0, 'histogram': 1, 'statistic': 2, + display = Feat(values={'real-time': 0, 'histogram': 1, 'statistic': 2, 'needle': 3, 'lineplot': 4}) + @display.setter def display(self, value): """This command is used to change the device’s on-screen display mode. (sdu) """ - self.query('*sdu {}'.format(value)) + self.send_command('*sdu {}'.format(value)) Scales = ('auto', '1p', '3p', '10p', '30p', '100p', '300p', '1n', '3n', '10n', '30n', '100n', '300n', '1u', '3u', '10u', @@ -68,14 +77,15 @@ def scale(self, value): """This command is used to force the display of the current data into a specific range. (ssa) """ - self.query('*ssa {}'.format(value)) + self.send_command('*ssa {}'.format(value)) self.DeviceStatus = self.status # update cached device status - @Action(values={False: 0, True: 1}) + dBm = Feat(values={False: 0, True: 1}) + @dBm.setter def dBm(self, value): """This command changes the on-screen display unit to dBm. (dbu) """ - self.query('*dbu {}'.format(value)) + self.send_command('*dbu {}'.format(value)) @Feat(values={False: 0, True: 1}) def high_resolution(self): @@ -89,7 +99,7 @@ def high_resolution(self, value): """This command is used to add significant digits to the on-screen reading. (shl) """ - self.query('*shl {}'.format(value)) + self.send_command('*shl {}'.format(value)) self.DeviceStatus = self.status # update cached device status #MEASUREMENT COMMANDS - DATA ACQUISITION @@ -117,26 +127,27 @@ def value_available(self): return self.query('*nvu') @Feat() - def statistics(self): + def get_statistics(self): """This command is used to read all the statistics data, provided that the device has previously been set into statistic mode. (vsu) """ return self.query('*vsu') - @Action(values={'stop': 0, 'start raw': 1, 'start saving': 2, + logging = Feat(values={'stop': 0, 'start raw': 1, 'start saving': 2, 'save both': 3}) + @logging.setter def logging(self, value): """This command is used to log data on the 842-PE meter’s EEPROM. (log) """ - self.query('*log {}'.format(value)) + self.send_command('*log {}'.format(value)) #Buggy - @Action() + @Feat() def get_log(self, value): """This command is used to retrieve a logged file from the device. (fdl) """ - #return self.query('*fdl {}'.format(value)) + #return self.send_command('*fdl {}'.format(value)) warnings.warn('This function does not work!') #Buggy @@ -145,7 +156,7 @@ def get_data(self): """This command is used to send data to the serial port according to the data sampling setting. The maximum transfer speed is 200Hz. (cau) """ - #return self.query('*cau') + #return self.send_command('*cau') warnings.warn('This function does not work!') #MEASUREMENT COMMANDS - SETUP @@ -162,7 +173,7 @@ def wavelength(self, value): """This command is used to set the wavelength being used on the detector. (swa) """ - self.query('*swa {}'.format(value)) + self.send_command('*swa {}'.format(value)) self.DeviceStatus = self.status # update cached device status @Feat(values={False: 0, True: 1}) @@ -178,7 +189,7 @@ def attenuator(self, value): readings of the detector, depending on whether the detector is using an external attenuator or not. (atu) """ - self.query('*atu {}'.format(value)) + self.send_command('*atu {}'.format(value)) self.DeviceStatus = self.status # update cached device status @Feat() @@ -191,7 +202,7 @@ def multiplier1(self): def multiplier1(self, multiplier): """This command is used to set the value of multiplier1. (smu) """ - self.query('*smu 1 {}'.format(multiplier)) + self.send_command('*smu 1 {}'.format(multiplier)) self.DeviceStatus = self.status # update cached device status @Feat() @@ -204,7 +215,7 @@ def multiplier2(self): def multiplier2(self, multiplier): """This command is used to set the value multiplier2. (smu) """ - self.query('*smu 2 {}'.format(multiplier)) + self.send_command('*smu 2 {}'.format(multiplier)) self.DeviceStatus = self.status # update cached device status @Feat() @@ -217,7 +228,7 @@ def offset1(self): def offset1(self, offset): """This command is used to set the value of offset1. (sou) """ - self.query('*sou 1 {}'.format(offset)) + self.send_command('*sou 1 {}'.format(offset)) self.DeviceStatus = self.status # update cached device status @Feat() @@ -230,7 +241,7 @@ def offset2(self): def offset2(self, offset): """This command is used to set the value of offset2. (sou) """ - self.query('*sou 2 {}'.format(offset)) + self.send_command('*sou 2 {}'.format(offset)) self.DeviceStatus = self.status # update cached device status SampleRateUnit = {'Seconds': '0', 'Minutes': '1', 'Hours': '2', @@ -272,7 +283,7 @@ def sampling(self, value): """This command provides the data sampling parameters for the logging and statistics environments. (dsu) """ - self.query('*dsu {} {} {} {} {} {} {}'.format(*value)) + self.send_command('*dsu {} {} {} {} {} {} {}'.format(*value)) @Feat() def trigger(self): @@ -283,17 +294,18 @@ def trigger(self, value): """This command sets the internal trigger level when using the device in energy reading mode. (tla) """ - self.query('*tla {}'.format(value)) + self.send_command('*tla {}'.format(value)) self.DeviceStatus = self.status # update cached device status #MEASUREMENT COMMANDS - MEASUREMENT CONTROL - @Action(values={'disable': 0, 'enable': 1, 'reset': 2}) - def esu(self, value=True): + set_statistics = Feat(values={'disable': 0, 'enable': 1, 'reset': 2}) + @set_statistics.setter + def set_statistics(self, value=True): """This command is used start, stop and reset the statistics calculating process on the data currently being acquisitioned. (esu) """ - self.query('*esu {}'.format(value)) + self.send_command('*esu {}'.format(value)) @Feat(values={False: 0, True: 1}) def energy_mode(self): @@ -305,7 +317,7 @@ def energy_mode(self, value): power detector. (sca) """ if not(self.DeviceStatus['HeadType'] in 'Photodiode'): - self.query('*sca {}'.format(value)) + self.send_command('*sca {}'.format(value)) self.DeviceStatus = self.status # update cached device status else: # energy_mode cannot be activated with photodiodes warnings.warn('Cannot put energy_mode True with a Photodiode') @@ -319,16 +331,17 @@ def anticipation(self, value): """This command is used to enable or disable the anticipation processing when the device is reading from a wattmeter. (eaa) """ - self.query('*eaa {}'.format(value)) + self.send_command('*eaa {}'.format(value)) self.DeviceStatus = self.status # update cached device status - @Action(values={'off': 0, 'on': 1, 'undo': 2}) - def zero(self, value): + set_zero = Feat(values={'off': 0, 'on': 1, 'undo': 2}) + @set_zero.getter + def set_zero(self, value): """This command subtracts the current value from all future measurements the moment the command is issued to set a new zero point. (eoa) """ - self.query('*eoa {}'.format(value)) + self.send_command('*eoa {}'.format(value)) #INSTRUMENT AND DETECTOR INFORMATION COMMANDS @@ -445,18 +458,19 @@ def clock(self, Day, Month, Year, Hour, Minute, Second, aMPM,): """This command is used to adjust the time and date of the monitor's internal clock. (clk) """ - self.query('*clk {} {} {} {} {} {} {}'.format(Day, Month, Year, + self.send_command('*clk {} {} {} {} {} {} {}'.format(Day, Month, Year, Hour, Minute, Second, aMPM,)) #INSTRUMENT CONTROL COMMANDS - @Action(values={False: 0, True: 1}) + backlight = Feat(values={False: 0, True: 1}) + @backlight.setter def backlight(self, value=True): """This command is used to turn the backlight of the device display on or off. (blk) """ - self.query('*bkl {}'.format(value)) + self.send_command('*bkl {}'.format(value)) @Feat(values={False: 0, True: 1}) def analog_port(self): @@ -467,7 +481,7 @@ def analog_port(self, value): """This command is used to enable or disable the output of the current value on the analog port of the meter. (ano) """ - self.query('*ano {}'.format(value)) + self.send_command('*ano {}'.format(value)) self.DeviceStatus = self.status # update cached device status #COMMUNICATIONS COMMANDS @@ -477,7 +491,7 @@ def baud_rate(self, value=True): """This command is used to change the current baud rate of the serial port of the device. (brs) """ - self.query('*brs {}'.format(value)) + self.send_command('*brs {}'.format(value)) def query(self, command, *, send_args=(None, None), recv_args=(None, None)): @@ -487,6 +501,43 @@ def query(self, command, *, send_args=(None, None), raise InstrumentError return answer + def send_command(self, s): + self.send(s) + self.wait_instrument_done() + + def wait_instrument_done(self, termination=None, encoding=None, + recv_chunk=None): + """Wait for command completion by instrument. + + :param termination: termination character (overrides class default) + :type termination: str + :param encoding: encoding to transform bytes to string (overrides class + default) + :param recv_chunk: number of bytes to receive (overrides class default) + :return: string encoded from received bytes + """ + + termination = termination or self.RECV_DONE + encoding = encoding or self.ENCODING + recv_chunk = recv_chunk or self.RECV_CHUNK + + if not termination: + return str(self.raw_recv(recv_chunk), encoding) + + if self.TIMEOUT is None or self.TIMEOUT < 0: + stop = float('+inf') + else: + stop = time.time() + self.TIMEOUT + + received = self._received + while not termination in received: + if time.time() > stop: + raise LantzTimeoutError + raw_received = self.raw_recv(recv_chunk) + received += str(raw_received, encoding) + + self.log_debug('Received {!r} (len={})', received, len(received)) + if __name__ == '__main__': import argparse import lantz.log @@ -498,7 +549,7 @@ def query(self, command, *, send_args=(None, None), help='Serial port to connect to') args = parser.parse_args() - lantz.log.log_to_screen(lantz.log.INFO) + lantz.log.log_to_screen(lantz.log.DEBUG) with N842PE(args.port) as inst: if args.interactive: from lantz.ui.qtwidgets import start_test_app @@ -506,23 +557,15 @@ def query(self, command, *, send_args=(None, None), else: print('Testing instrument...') print(inst.status) - - #inst.energy_mode = False - #print(inst.energy_mode) - - #time.sleep(2) - #inst.energy_mode = True - #print(inst.energy_mode) - - - inst.offset1 = 0 - print(inst.offset1) - inst.offset2 = 0 - print(inst.offset2) - - inst.multiplier1 = 1 - print(inst.multiplier1) - inst.multiplier2 = 1 - print(inst.multiplier2) + inst.display = 'real-time' print(inst.current_value) + print(inst.idn) + print(inst.idn_head) + inst.dBm = False + inst.backlight = True +# inst.set_statistics = 'disable' +# inst.set_statistics = 'reset' +# inst.set_statistics = 'enable' + + #print(inst.get_statistics) From d50bc70ef516772a9c70a6a16ae38a650c1c21e8 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Thu, 12 Sep 2013 13:24:00 -0400 Subject: [PATCH 30/48] comments + prevent dBm without a photodiode --- lantz/drivers/newport/842PE.py | 226 +++++++++++++++------------------ 1 file changed, 103 insertions(+), 123 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 61cb612..73e83c9 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -9,9 +9,8 @@ :license: BSD, see LICENSE for more details. """ # Cheched working with following heads: 818-UV, 818P -# +# This device also has a binary mode, witch is not implemented here. -import time import warnings from lantz import Action, Feat, Q_ @@ -22,6 +21,7 @@ watt = Q_(1, 'W') joule = Q_(1, 'J') + class N842PE(SerialDriver): """Newport 842-PE powermeter """ @@ -32,7 +32,8 @@ class N842PE(SerialDriver): # It is needeed because when there is an error it looks like this: # 'Error 26: Option only available with photodiode\r\nACK\r\n' # So if we just detect a RECV_TERMINATION the next query will be polluted - # To use a command/setter, we then should use send_command() instead of query() + # To use a command/setter, we then should use send_command() instead of + # query() RECV_DONE = 'ACK\r\n' RECV_TERMINATION = '\r\n' @@ -52,11 +53,11 @@ def __init__(self, *args, **kwargs): #Display commands display = Feat(values={'real-time': 0, 'histogram': 1, 'statistic': 2, - 'needle': 3, 'lineplot': 4}) + 'needle': 3, 'lineplot': 4}) + @display.setter def display(self, value): - """This command is used to change the device’s on-screen display mode. - (sdu) + """Set the device’s on-screen display mode. (sdu) """ self.send_command('*sdu {}'.format(value)) @@ -69,35 +70,38 @@ def display(self, value): @Feat(values=set(Scales)) def scale(self): + """Get the display range. (ssa) + """ out = self.DeviceStatus['CurrentScale'] return self.Scales[out] @scale.setter def scale(self, value): - """This command is used to force the display of the current data into a - specific range. (ssa) + """Set the display of the current data into a specific range. (ssa) """ self.send_command('*ssa {}'.format(value)) self.DeviceStatus = self.status # update cached device status dBm = Feat(values={False: 0, True: 1}) + @dBm.setter def dBm(self, value): - """This command changes the on-screen display unit to dBm. (dbu) + """Set the on-screen display unit to dBm. (dbu) """ - self.send_command('*dbu {}'.format(value)) + if not('Photodiode' in self.DeviceStatus['HeadType']): + warnings.warn('Cannot put dBm without a Photodiode Detector') + else: # dBm can only be set with Photodiode Detectors + self.send_command('*dbu {}'.format(value)) @Feat(values={False: 0, True: 1}) def high_resolution(self): - """This command is used to add significant digits to the on-screen - reading. (shl) + """Get the high resolution digits on the on-screen reading. (shl) """ return self.DeviceStatus['HighResolutionDisplay'] @high_resolution.setter def high_resolution(self, value): - """This command is used to add significant digits to the on-screen - reading. (shl) + """Set the high resolution digits on the on-screen reading. (shl) """ self.send_command('*shl {}'.format(value)) self.DeviceStatus = self.status # update cached device status @@ -106,21 +110,20 @@ def high_resolution(self, value): @Feat() def current_value(self): - """This command is used to query the value that is currently being - displayed on the device’s screen. The value is displayed in Watts or in - Joules (not in dBm). (cvu) + """Get the value that is currently being displayed on the device’s + screen. The value is displayed in Watts or in Joules (not in dBm). + (cvu) """ out = float(self.parse_query('*cvu', - format='Current Value: {}')) - print(out) + format='Current Value: {}')) if self.energy_mode: return Q_(out, joule) else: return Q_(out, watt) - + @Feat(values={False: 'New Data Not Available', True: 'New Data Available'}) def value_available(self): - """This command is used to check whether a new value is available from + """Check whether a new value is available from the device. Though optional, its use is recommended when used with single pulse operations. (nvu) """ @@ -128,24 +131,24 @@ def value_available(self): @Feat() def get_statistics(self): - """This command is used to read all the statistics data, provided that - the device has previously been set into statistic mode. (vsu) + """Get all the statistics data, provided that the device has previously + been set into statistic mode. (vsu) """ return self.query('*vsu') logging = Feat(values={'stop': 0, 'start raw': 1, 'start saving': 2, - 'save both': 3}) + 'save both': 3}) + @logging.setter def logging(self, value): - """This command is used to log data on the 842-PE meter’s EEPROM. (log) + """set logging data on the 842-PE meter’s EEPROM. (log) """ self.send_command('*log {}'.format(value)) #Buggy @Feat() def get_log(self, value): - """This command is used to retrieve a logged file from the device. - (fdl) + """Retrieve a logged file from the device. (fdl) """ #return self.send_command('*fdl {}'.format(value)) warnings.warn('This function does not work!') @@ -153,8 +156,8 @@ def get_log(self, value): #Buggy @Feat() def get_data(self): - """This command is used to send data to the serial port according to - the data sampling setting. The maximum transfer speed is 200Hz. (cau) + """Get data according to the data sampling setting. The maximum + transfer speed is 200Hz. (cau) """ #return self.send_command('*cau') warnings.warn('This function does not work!') @@ -163,14 +166,14 @@ def get_data(self): @Feat() def wavelength(self): - """This command is used to read the wavelength being used on the + """Get the wavelength being used on the detector. (swa) """ return self.DeviceStatus['ActiveWaveLength'] @wavelength.setter def wavelength(self, value): - """This command is used to set the wavelength being used on the + """Set the wavelength being used on the detector. (swa) """ self.send_command('*swa {}'.format(value)) @@ -178,68 +181,68 @@ def wavelength(self, value): @Feat(values={False: 0, True: 1}) def attenuator(self): - """This command is used to read if whether the detector is using an - external attenuator or not. (atu) + """Get if whether the detector is using an external attenuator or not. + (atu) """ return self.DeviceStatus['Attenuator'] @attenuator.setter def attenuator(self, value): - """This command is used to adjust the processing of the meter with the - readings of the detector, depending on whether the detector is using an - external attenuator or not. (atu) + """Set if whether the detector is using an external attenuator or not. + This is used to adjust the processing of the meter with the readings of + the detector. (atu) """ self.send_command('*atu {}'.format(value)) self.DeviceStatus = self.status # update cached device status @Feat() def multiplier1(self): - """This command is used to get the value multiplier1. (smu) + """Get the value of multiplier1. (smu) """ return self.DeviceStatus['Multiplier'][0] @multiplier1.setter def multiplier1(self, multiplier): - """This command is used to set the value of multiplier1. (smu) + """Set the value of multiplier1. (smu) """ self.send_command('*smu 1 {}'.format(multiplier)) self.DeviceStatus = self.status # update cached device status @Feat() def multiplier2(self): - """This command is used to get the value multiplier2. (smu) + """Get the value of multiplier2. (smu) """ return self.DeviceStatus['Multiplier'][1] @multiplier2.setter def multiplier2(self, multiplier): - """This command is used to set the value multiplier2. (smu) + """Set the value of multiplier2. (smu) """ self.send_command('*smu 2 {}'.format(multiplier)) self.DeviceStatus = self.status # update cached device status @Feat() def offset1(self): - """This command is used to get the value offset1. (sou) + """Get the value of offset1. (sou) """ return self.DeviceStatus['Offset'][0] @offset1.setter def offset1(self, offset): - """This command is used to set the value of offset1. (sou) + """Set the value of offset1. (sou) """ self.send_command('*sou 1 {}'.format(offset)) self.DeviceStatus = self.status # update cached device status @Feat() def offset2(self): - """This command is used to get the value offset2. (sou) + """Get the value of offset2. (sou) """ return self.DeviceStatus['Offset'][1] @offset2.setter def offset2(self, offset): - """This command is used to set the value of offset2. (sou) + """Set the value of offset2. (sou) """ self.send_command('*sou 2 {}'.format(offset)) self.DeviceStatus = self.status # update cached device status @@ -256,8 +259,7 @@ def offset2(self, offset): @Feat(values=(None, SampleRateUnit, None, SamplePeriodUnit, None, TotalDurationUnit, TimeStampEnabled,)) def sampling(self): - """This command is used to read the current data sampling settings. - (rds) + """Get the current data sampling settings. (rds) """ out = self.parse_query('*rds', format='Sample Rate: {} / {}\t' 'Sample Period: {} / {}\t' @@ -280,19 +282,22 @@ def sampling(self): @sampling.setter def sampling(self, value): - """This command provides the data sampling parameters for the logging - and statistics environments. (dsu) + """Set the data sampling parameters for the logging and statistics + environments. (dsu) """ self.send_command('*dsu {} {} {} {} {} {} {}'.format(*value)) @Feat() def trigger(self): + """Get the internal trigger level when using the device in energy + reading mode. (tla) + """ return self.DeviceStatus['TrigLevel'] @trigger.setter def trigger(self, value): - """This command sets the internal trigger level when using the device - in energy reading mode. (tla) + """Set the internal trigger level when using the device in energy + reading mode. (tla) """ self.send_command('*tla {}'.format(value)) self.DeviceStatus = self.status # update cached device status @@ -300,10 +305,11 @@ def trigger(self, value): #MEASUREMENT COMMANDS - MEASUREMENT CONTROL set_statistics = Feat(values={'disable': 0, 'enable': 1, 'reset': 2}) + @set_statistics.setter def set_statistics(self, value=True): - """This command is used start, stop and reset the statistics - calculating process on the data currently being acquisitioned. (esu) + """Used start, stop and reset the statistics calculating process on the + data currently being acquisitioned. (esu) """ self.send_command('*esu {}'.format(value)) @@ -313,33 +319,39 @@ def energy_mode(self): @energy_mode.setter def energy_mode(self, value): - """This command is used to toggle the Energy mode when using a high - power detector. (sca) + """Toggle the Energy mode when using a high power detector. (sca) """ - if not(self.DeviceStatus['HeadType'] in 'Photodiode'): + if not('Photodiode' in self.DeviceStatus['HeadType']): self.send_command('*sca {}'.format(value)) self.DeviceStatus = self.status # update cached device status else: # energy_mode cannot be activated with photodiodes - warnings.warn('Cannot put energy_mode True with a Photodiode') + warnings.warn('Cannot put energy_mode with a Photodiode') @Feat(values={False: 0, True: 1}) def anticipation(self): + """Get whether the anticipation processing is active when the device is + reading from a wattmeter or not. (eaa) + """ return self.DeviceStatus['Anticipation'] @anticipation.setter def anticipation(self, value): - """This command is used to enable or disable the anticipation - processing when the device is reading from a wattmeter. (eaa) + """Enable or disable the anticipation processing when the device is + reading from a wattmeter. (eaa) """ self.send_command('*eaa {}'.format(value)) self.DeviceStatus = self.status # update cached device status set_zero = Feat(values={'off': 0, 'on': 1, 'undo': 2}) + @set_zero.getter def set_zero(self, value): - """This command subtracts the current value from all future - measurements the moment the command is issued to set a new zero point. - (eoa) + """Set the instrument zero mode. (eoa) + + off: not active + on: current value is substracted from all future measurements the + moment the command is issued. + undo: """ self.send_command('*eoa {}'.format(value)) @@ -347,23 +359,17 @@ def set_zero(self, value): @Feat() def idn(self): - """This command is used to query the device to get information about - the firmware version and the device type. (ver) + """Get the device to get information about the firmware version and the + device type. (ver) """ return self.query('*ver') - @Feat() - def idn_head(self): - """Model of the current head. (hea) - """ - return self.query('*hea') - # The device is a bit buggy for this one as it return the info with 3 \n\r. # So the hack here: we have to read it 3 times to read everything # In addition, it seems to never return the last field (dBm). @Feat() def status(self): - """This command is used to query the current device status. (sta) + """Query the current device status. (sta) It stores it in self.Device Status for later retrival by other query function. """ @@ -411,18 +417,20 @@ def status(self): DeviceStatus.update(i) # units - DeviceStatus['ActiveWavelength'] = Q_(DeviceStatus['ActiveWavelength'], nanometer) + DeviceStatus['ActiveWavelength'] = Q_(DeviceStatus['ActiveWavelength'], + nanometer) DeviceStatus['CalibrationWavelength'] = Q_(DeviceStatus['CalibrationWavelength'], nanometer) - # DeviceStatus['EnergyMode'] = 1 if (DeviceStatus['EnergyMode'] == 'On') else 0 DeviceStatus['Anticipation'] = 1 if (DeviceStatus['Anticipation'] == 'On') else 0 # Merge the two multipliers - DeviceStatus['Multiplier'] = [DeviceStatus['Multiplier1'], DeviceStatus['Multiplier2']] + DeviceStatus['Multiplier'] = [DeviceStatus['Multiplier1'], + DeviceStatus['Multiplier2']] del DeviceStatus['Multiplier1'] del DeviceStatus['Multiplier2'] # Merge the two offsets - DeviceStatus['Offset'] = [DeviceStatus['Offset1'], DeviceStatus['Offset2']] + DeviceStatus['Offset'] = [DeviceStatus['Offset1'], + DeviceStatus['Offset2']] del DeviceStatus['Offset1'] del DeviceStatus['Offset2'] DeviceStatus['CurrentlyLoggingData'] = 1 if (DeviceStatus['CurrentlyLoggingData'] == 'Yes') else 0 @@ -440,8 +448,7 @@ def status(self): @Feat() def battery(self): - """This command is used to query the device’s remaining battery power. - (bat) + """Get the device’s remaining battery power. (bat) """ return self.query('*bat') @@ -455,31 +462,34 @@ def battery(self): @Action(values=(day, month, year, hour, minute, second, AMPM,)) def clock(self, Day, Month, Year, Hour, Minute, Second, aMPM,): - """This command is used to adjust the time and date of the monitor's + """Set the time and date of the monitor's internal clock. (clk) """ self.send_command('*clk {} {} {} {} {} {} {}'.format(Day, Month, Year, - Hour, Minute, - Second, aMPM,)) + Hour, Minute, + Second, aMPM,)) #INSTRUMENT CONTROL COMMANDS backlight = Feat(values={False: 0, True: 1}) + @backlight.setter def backlight(self, value=True): - """This command is used to turn the backlight of the device display on - or off. (blk) + """Set the backlight of the device display on. (blk) """ self.send_command('*bkl {}'.format(value)) @Feat(values={False: 0, True: 1}) def analog_port(self): + """Get whether the output of the current value on the analog port of + the meter is enabled or not. (ano) + """ return self.DeviceStatus['AnalogOutput'] @analog_port.setter def analog_port(self, value): - """This command is used to enable or disable the output of the current - value on the analog port of the meter. (ano) + """Enable or disable the output of the current value on the analog port + of the meter. (ano) """ self.send_command('*ano {}'.format(value)) self.DeviceStatus = self.status # update cached device status @@ -488,8 +498,7 @@ def analog_port(self, value): @Action(values=set((2400, 9600, 14400, 19200, 38400, 155200))) def baud_rate(self, value=True): - """This command is used to change the current baud rate of the serial - port of the device. (brs) + """Set the current baud rate of the serial port of the device. (brs) """ self.send_command('*brs {}'.format(value)) @@ -502,41 +511,11 @@ def query(self, command, *, send_args=(None, None), return answer def send_command(self, s): - self.send(s) - self.wait_instrument_done() - - def wait_instrument_done(self, termination=None, encoding=None, - recv_chunk=None): - """Wait for command completion by instrument. - - :param termination: termination character (overrides class default) - :type termination: str - :param encoding: encoding to transform bytes to string (overrides class - default) - :param recv_chunk: number of bytes to receive (overrides class default) - :return: string encoded from received bytes + """Send a command (@Action or setter to the device) and wait for + RECV_DONE. """ - - termination = termination or self.RECV_DONE - encoding = encoding or self.ENCODING - recv_chunk = recv_chunk or self.RECV_CHUNK - - if not termination: - return str(self.raw_recv(recv_chunk), encoding) - - if self.TIMEOUT is None or self.TIMEOUT < 0: - stop = float('+inf') - else: - stop = time.time() + self.TIMEOUT - - received = self._received - while not termination in received: - if time.time() > stop: - raise LantzTimeoutError - raw_received = self.raw_recv(recv_chunk) - received += str(raw_received, encoding) - - self.log_debug('Received {!r} (len={})', received, len(received)) + self.send(s) + self.recv(termination=self.RECV_DONE) # wait for RECV_DONE if __name__ == '__main__': import argparse @@ -560,10 +539,11 @@ def wait_instrument_done(self, termination=None, encoding=None, inst.display = 'real-time' print(inst.current_value) - print(inst.idn) - print(inst.idn_head) - inst.dBm = False - inst.backlight = True + inst.dBm = True + inst.energy_mode = True +# print(inst.idn) +# inst.dBm = False +# inst.backlight = True # inst.set_statistics = 'disable' # inst.set_statistics = 'reset' # inst.set_statistics = 'enable' From 6af8e5269b6636593e91db6650c2443df9cd46b4 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Thu, 12 Sep 2013 14:50:04 -0400 Subject: [PATCH 31/48] add units to get_statistics() --- lantz/drivers/newport/842PE.py | 85 +++++++++++++++++++++++++++++----- 1 file changed, 73 insertions(+), 12 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 73e83c9..2874a02 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -20,6 +20,8 @@ nanometer = Q_(1, 'nm') watt = Q_(1, 'W') joule = Q_(1, 'J') +second = Q_(1, 's') +hertz = Q_(1, 'Hz') class N842PE(SerialDriver): @@ -116,9 +118,9 @@ def current_value(self): """ out = float(self.parse_query('*cvu', format='Current Value: {}')) - if self.energy_mode: + if self.energy_mode: # joules return Q_(out, joule) - else: + else: # watts return Q_(out, watt) @Feat(values={False: 'New Data Not Available', True: 'New Data Available'}) @@ -134,7 +136,57 @@ def get_statistics(self): """Get all the statistics data, provided that the device has previously been set into statistic mode. (vsu) """ - return self.query('*vsu') + if self.energy_mode: #Joules + out = self.parse_query('*vsu', format = 'Current Value: {[CurrentValue]:f}\t' # joule + 'Maximum: {[Maximum]:f}\t' # joule + 'Minimum: {[Minimum]:f}\t' # joule + 'Average: {[Average]:f}\t' # joule + 'Standard Deviation: {[StandardDeviation]:f}\t' # joule + 'RMS stability: {[RMSstability]:f}%\t' # % + 'PTP stability: {[PTPstability]:f}%\t' # % + 'Pulse Number: {[PulseNumber]:d}\t' # integer + 'Total Pulses: {[TotalPulses]:d}\t' # integer + 'Average Power: {[AveragePower]:f}\t' #joule + 'Rep Rate: {[RepRate]:f}\t' # Hz + 'Uncorrected Value: {[UncorrectedValue]:f}') # joule + + # transform the list of dictionaries into a single dictionary + statistics = reshape_list_dict_in_dict(out) + + #units + statistics['CurrentValue'] = Q_(statistics['CurrentValue'], joule) + statistics['Maximum'] = Q_(statistics['Maximum'], joule) + statistics['Minimum'] = Q_(statistics['Minimum'], joule) + statistics['StandardDeviation'] = Q_(statistics['StandardDeviation'], joule) + statistics['AveragePower'] = Q_(statistics['AveragePower'], joule) + statistics['RepRate'] = Q_(statistics['RepRate'], hertz) + statistics['UncorrectedValue'] = Q_(statistics['UncorrectedValue'], joule) + + else: #Watt + out = self.parse_query('*vsu', format='Current Value: {[CurrentValue]:f}\t' # watt + 'Maximum: {[Maximum]:f}\t' # watt + 'Minimum: {[Minimum]:f}\t' # watt + 'Average: {[Average]:f}\t' # watt + 'Standard Deviation: {[StandardDeviation]:f}\t' # watt + 'RMS stability: {[RMSstability]:f}%\t' # % + 'PTP stability: {[PTPstability]:f}%\t' # % + 'Time: {[Time]:d}\t' # second + 'Acquisition Time: {[AcquisitionTime]:d}\t' # second + 'Uncorrected Value: {[UncorrectedValue]:f}') # watt + + # transform the list of dictionaries into a single dictionary + statistics = reshape_list_dict_in_dict(out) + + #units + statistics['CurrentValue'] = Q_(statistics['CurrentValue'], watt) + statistics['Maximum'] = Q_(statistics['Maximum'], watt) + statistics['Minimum'] = Q_(statistics['Minimum'], watt) + statistics['StandardDeviation'] = Q_(statistics['StandardDeviation'], watt) + statistics['Time'] = Q_(statistics['Time'], second) + statistics['AcquisitionTime'] = Q_(statistics['AcquisitionTime'], second) + statistics['UncorrectedValue'] = Q_(statistics['UncorrectedValue'], watt) + + return statistics logging = Feat(values={'stop': 0, 'start raw': 1, 'start saving': 2, 'save both': 3}) @@ -412,9 +464,7 @@ def status(self): out.append(self.parse_query('', format='AutoScale: {[AutoScale]}')) # transform the list of dictionaries in a single dictionary - DeviceStatus = {} - for i in out: - DeviceStatus.update(i) + DeviceStatus = reshape_list_dict_in_dict(out) # units DeviceStatus['ActiveWavelength'] = Q_(DeviceStatus['ActiveWavelength'], @@ -517,6 +567,13 @@ def send_command(self, s): self.send(s) self.recv(termination=self.RECV_DONE) # wait for RECV_DONE +def reshape_list_dict_in_dict(list_of_dict): + # transform a list of dictionaries in a single dictionary + out = {} + for i in list_of_dict: + out.update(i) + return out + if __name__ == '__main__': import argparse import lantz.log @@ -539,13 +596,17 @@ def send_command(self, s): inst.display = 'real-time' print(inst.current_value) - inst.dBm = True - inst.energy_mode = True +# inst.dBm = False + inst.energy_mode = False # print(inst.idn) # inst.dBm = False # inst.backlight = True -# inst.set_statistics = 'disable' -# inst.set_statistics = 'reset' -# inst.set_statistics = 'enable' - #print(inst.get_statistics) + import time + + #inst.set_statistics = 'disable' + #inst.set_statistics = 'reset' + #inst.set_statistics = 'enable' + #time.sleep(10) + + print(inst.get_statistics) From 001cb976c6c668ddb278143e1cc4c5570e32628b Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Thu, 12 Sep 2013 15:56:59 -0400 Subject: [PATCH 32/48] helper function new_scale() --- lantz/drivers/newport/842PE.py | 43 ++++++++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 2874a02..61aabf9 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -32,7 +32,7 @@ class N842PE(SerialDriver): # This string is returned by the device when the action/setter is done # It is needeed because when there is an error it looks like this: - # 'Error 26: Option only available with photodiode\r\nACK\r\n' + # 'Error XXX: YYY\r\nACK\r\n' # So if we just detect a RECV_TERMINATION the next query will be polluted # To use a command/setter, we then should use send_command() instead of # query() @@ -84,6 +84,30 @@ def scale(self, value): self.send_command('*ssa {}'.format(value)) self.DeviceStatus = self.status # update cached device status + new_scale = Feat(values=set(('decrease','increase'))) + + #An helper function to increase on decrease the scale + @new_scale.setter + def new_scale(self, value): + """Increase or decrease the scale. + """ + current_scale = self.DeviceStatus['CurrentScale'] + #check limits + if self.energy_mode: #Joules + max_scale = self.DeviceStatus['ScaleMaxEnergy'] + min_scale = self.DeviceStatus['ScaleMinEnergy'] + else: + max_scale = self.DeviceStatus['ScaleMaxPower'] + min_scale = self.DeviceStatus['ScaleMinPower'] + #increase or decrease the scale + mod = 1 if (value == 'increase') else -1 + new_scale = current_scale + mod + #cannot go furter limits + if (new_scale > max_scale) or (new_scale < min_scale): + new_scale = current_scale + #actually change the scale + self.scale = self.Scales[new_scale] + dBm = Feat(values={False: 0, True: 1}) @dBm.setter @@ -308,6 +332,7 @@ def offset2(self, offset): 'Continuous': '6', 'Points': '7'} TimeStampEnabled = {False: 0, True: 1} + #TODO units @Feat(values=(None, SampleRateUnit, None, SamplePeriodUnit, None, TotalDurationUnit, TimeStampEnabled,)) def sampling(self): @@ -490,9 +515,18 @@ def status(self): DeviceStatus['Attenuator'] = 1 if (DeviceStatus['Attenuator'] == 'On') else 0 # On, Off or N/A. N/A is when there is not DeviceStatus['AutoScale'] = 1 if (DeviceStatus['AutoScale'] == 'On') else 0 + if DeviceStatus['EnergyMode']: # energy mode (joules) + # We cannot use self.energy_mode in the test condition because it is not + # defined at instrument initialisation, so it creates an error + DeviceStatus['ScaleMinEnergy'] = int(DeviceStatus['ScaleMinEnergy']) + DeviceStatus['ScaleMaxEnergy'] = int(DeviceStatus['ScaleMaxEnergy']) + DeviceStatus['Resolution'] = Q_(DeviceStatus['Resolution'], joule) + else: # power mode (watt) + DeviceStatus['Resolution'] = Q_(DeviceStatus['Resolution'], watt) + #Print dictionary (for debug) - #for key in sorted(DeviceStatus.keys()): - # print ("%s: %s" % (key, DeviceStatus[key])) + for key in sorted(DeviceStatus.keys()): + print ("%s \t %s" % (key, DeviceStatus[key])) return DeviceStatus @@ -609,4 +643,5 @@ def reshape_list_dict_in_dict(list_of_dict): #inst.set_statistics = 'enable' #time.sleep(10) - print(inst.get_statistics) +# print(inst.get_statistics) + inst.new_scale = 'increase' From 7bb9242dd7c33bcb6baef3e50e881c967aa8178f Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Thu, 12 Sep 2013 16:23:33 -0400 Subject: [PATCH 33/48] add units to walength --- lantz/drivers/newport/842PE.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 61aabf9..7810152 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -240,12 +240,12 @@ def get_data(self): #MEASUREMENT COMMANDS - SETUP - @Feat() + @Feat(units='nm') def wavelength(self): """Get the wavelength being used on the detector. (swa) """ - return self.DeviceStatus['ActiveWaveLength'] + return self.DeviceStatus['ActiveWavelength'] @wavelength.setter def wavelength(self, value): @@ -644,4 +644,6 @@ def reshape_list_dict_in_dict(list_of_dict): #time.sleep(10) # print(inst.get_statistics) - inst.new_scale = 'increase' +# inst.new_scale = 'increase' + inst.wavelength = 10000 * nm + print(inst.wavelength) From d05c3aa1fd589c4acf2c0606a42a5946104a6db5 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Tue, 1 Oct 2013 13:17:20 -0400 Subject: [PATCH 34/48] split DeviceStatus['Multiplier'] in two variables, same for DeviceStatus['Offset'] --- lantz/drivers/newport/842PE.py | 44 +++++++++++++--------------------- 1 file changed, 16 insertions(+), 28 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 7810152..95a41f9 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -275,7 +275,7 @@ def attenuator(self, value): def multiplier1(self): """Get the value of multiplier1. (smu) """ - return self.DeviceStatus['Multiplier'][0] + return self.DeviceStatus['Multiplier1'] @multiplier1.setter def multiplier1(self, multiplier): @@ -288,7 +288,7 @@ def multiplier1(self, multiplier): def multiplier2(self): """Get the value of multiplier2. (smu) """ - return self.DeviceStatus['Multiplier'][1] + return self.DeviceStatus['Multiplier2'] @multiplier2.setter def multiplier2(self, multiplier): @@ -301,7 +301,7 @@ def multiplier2(self, multiplier): def offset1(self): """Get the value of offset1. (sou) """ - return self.DeviceStatus['Offset'][0] + return self.DeviceStatus['Offset1'] @offset1.setter def offset1(self, offset): @@ -314,7 +314,7 @@ def offset1(self, offset): def offset2(self): """Get the value of offset2. (sou) """ - return self.DeviceStatus['Offset'][1] + return self.DeviceStatus['Offset2'] @offset2.setter def offset2(self, offset): @@ -498,16 +498,6 @@ def status(self): DeviceStatus['EnergyMode'] = 1 if (DeviceStatus['EnergyMode'] == 'On') else 0 DeviceStatus['Anticipation'] = 1 if (DeviceStatus['Anticipation'] == 'On') else 0 - # Merge the two multipliers - DeviceStatus['Multiplier'] = [DeviceStatus['Multiplier1'], - DeviceStatus['Multiplier2']] - del DeviceStatus['Multiplier1'] - del DeviceStatus['Multiplier2'] - # Merge the two offsets - DeviceStatus['Offset'] = [DeviceStatus['Offset1'], - DeviceStatus['Offset2']] - del DeviceStatus['Offset1'] - del DeviceStatus['Offset2'] DeviceStatus['CurrentlyLoggingData'] = 1 if (DeviceStatus['CurrentlyLoggingData'] == 'Yes') else 0 DeviceStatus['AnalogOutput'] = 1 if (DeviceStatus['AnalogOutput'] == 'On') else 0 DeviceStatus['CurrentlyCalculatingStats'] = 1 if (DeviceStatus['CurrentlyCalculatingStats'] == 'Yes') else 0 @@ -626,24 +616,22 @@ def reshape_list_dict_in_dict(list_of_dict): start_test_app(inst) else: print('Testing instrument...') - print(inst.status) - inst.display = 'real-time' - - print(inst.current_value) # inst.dBm = False inst.energy_mode = False + print(inst.status) + + inst.energy_mode = True + print(inst.status) + # print(inst.idn) # inst.dBm = False # inst.backlight = True - import time - - #inst.set_statistics = 'disable' - #inst.set_statistics = 'reset' - #inst.set_statistics = 'enable' - #time.sleep(10) - -# print(inst.get_statistics) # inst.new_scale = 'increase' - inst.wavelength = 10000 * nm - print(inst.wavelength) + inst.wavelength = 1000 * nanometer +# print(inst.wavelength) + + print(inst.multiplier1) + print(inst.multiplier2) + print(inst.offset1) + print(inst.offset2) From d9b742239a0632185638d9e374dd214ef0e26feb Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Wed, 9 Oct 2013 11:34:15 -0400 Subject: [PATCH 35/48] clock uses struct_time format --- lantz/drivers/newport/842PE.py | 27 ++++++++++++++------------- 1 file changed, 14 insertions(+), 13 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 95a41f9..707b104 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -11,6 +11,7 @@ # Cheched working with following heads: 818-UV, 818P # This device also has a binary mode, witch is not implemented here. +import time import warnings from lantz import Action, Feat, Q_ @@ -526,22 +527,20 @@ def battery(self): """ return self.query('*bat') - day = set(range(1, 32)) - month = set(range(1, 13)) - year = set(range(1970, 3000)) - hour = set(range(24)) - minute = set(range(59)) - second = set(range(59)) - AMPM = {'AM': 0, 'PM': 1} + clock = Feat() - @Action(values=(day, month, year, hour, minute, second, AMPM,)) - def clock(self, Day, Month, Year, Hour, Minute, Second, aMPM,): + @clock.setter + def clock(self, t,): """Set the time and date of the monitor's internal clock. (clk) + + The optional argument is a time.struct_time + If omited, it'll use current time """ - self.send_command('*clk {} {} {} {} {} {} {}'.format(Day, Month, Year, - Hour, Minute, - Second, aMPM,)) + s = time.strftime('*clk %d %m %Y %I %M %S ', t) + pm = '1' if time.strftime('%p', t) == 'PM' else '0' # PM -> 1, AM -> 0 + s += pm + self.send_command(s) #INSTRUMENT CONTROL COMMANDS @@ -576,7 +575,7 @@ def baud_rate(self, value=True): """ self.send_command('*brs {}'.format(value)) - def query(self, command, *, send_args=(None, None), + def query(self, command, send_args=(None, None), recv_args=(None, None)): answer = super().query(command, send_args=send_args, recv_args=recv_args) @@ -635,3 +634,5 @@ def reshape_list_dict_in_dict(list_of_dict): print(inst.multiplier2) print(inst.offset1) print(inst.offset2) + + inst.clock = time.localtime() From 579ca5ffb89127180c86829b1ed650bbfd933032 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Wed, 9 Oct 2013 12:43:38 -0400 Subject: [PATCH 36/48] fix for head 918D-UV-OD3 --- lantz/drivers/newport/842PE.py | 18 ++---------------- 1 file changed, 2 insertions(+), 16 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 707b104..5937727 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -8,7 +8,7 @@ :copyright: 2013 by Lantz Authors, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ -# Cheched working with following heads: 818-UV, 818P +# Cheched working with following heads: 818-UV, 818P, 918D-UV # This device also has a binary mode, witch is not implemented here. import time @@ -456,7 +456,7 @@ def status(self): 'Head Version: {[HeadVersion]}\t' # Is that really the head version? 'Head Serial Number: {[HeadSerialNumber]}\t{[HeadName]}\t' 'Calibration Sensitivity: {[CalibrationSensitivity]:f} V/W\t' # unit V/W - 'Default WaveLength: {[CalibrationWavelength]:f} nm\t' # unit nm, seems non-sense for photodiode + 'Default WaveLength: {[CalibrationWavelength]} nm\t' # unit nm, seems non-sense for photodiodes. 'Active Sensitivity: {[ActiveSensitivity]:f} V/W\t' # unit V/W 'Active WaveLength: {[ActiveWavelength]:f} nm\t' # unit nm 'Scale Min Power : {[ScaleMinPower]:d}\t' @@ -622,17 +622,3 @@ def reshape_list_dict_in_dict(list_of_dict): inst.energy_mode = True print(inst.status) -# print(inst.idn) -# inst.dBm = False -# inst.backlight = True - -# inst.new_scale = 'increase' - inst.wavelength = 1000 * nanometer -# print(inst.wavelength) - - print(inst.multiplier1) - print(inst.multiplier2) - print(inst.offset1) - print(inst.offset2) - - inst.clock = time.localtime() From c3316ddd4810e15ef1cddd8e6cf4ca53be2da27e Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Thu, 17 Oct 2013 21:53:22 -0400 Subject: [PATCH 37/48] prevent setting scale out of range for the head + function to test the device --- lantz/drivers/newport/842PE.py | 100 ++++++++++++++++++++++++--------- 1 file changed, 75 insertions(+), 25 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 5937727..a4e4cbf 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -47,12 +47,39 @@ class N842PE(SerialDriver): PARITY = 'none' STOPBITS = 1 + #These are the whole scales the controller can reach + #No every head can whitstand all of them + Scales = ('auto', '1p', '3p', '10p', '30p', '100p', '300p', '1n', + '3n', '10n', '30n', '100n', '300n', '1u', '3u', '10u', + '30u', '100u', '300u', '1m', '3m', '10m', '30m', + '100m', '300m', '1', '3', '10', '30', '100', '300', + '1k', '3k', '10k', '30k', '100k', '300k', '1M', '3M', + '10M', '30M', '100M', '300M',) + #TODO: is this functin complete? def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.initialize() self.DeviceStatus = self.status # Read the device status + def available_scales(self): + """ + Returns valid scales for the current head + """ + #check limits of the head + if self.energy_mode: #Joules + max_scale = self.DeviceStatus['ScaleMaxEnergy'] + min_scale = self.DeviceStatus['ScaleMinEnergy'] + else: + max_scale = self.DeviceStatus['ScaleMaxPower'] + min_scale = self.DeviceStatus['ScaleMinPower'] + out = list(self.Scales[min_scale:max_scale+1]) + out.insert(0,self.Scales[0]) # 'auto' + return tuple(out) + + #These are the whole scales the head can reach + self.ScalesHead = available_scales(self) + #Display commands display = Feat(values={'real-time': 0, 'histogram': 1, 'statistic': 2, @@ -64,13 +91,6 @@ def display(self, value): """ self.send_command('*sdu {}'.format(value)) - Scales = ('auto', '1p', '3p', '10p', '30p', '100p', '300p', '1n', - '3n', '10n', '30n', '100n', '300n', '1u', '3u', '10u', - '30u', '100u', '300u', '1m', '3m', '10m', '30m', - '100m', '300m', '1', '3', '10', '30', '100', '300', - '1k', '3k', '10k', '30k', '100k', '300k', '1M', '3M', - '10M', '30M', '100M', '300M',) - @Feat(values=set(Scales)) def scale(self): """Get the display range. (ssa) @@ -82,12 +102,14 @@ def scale(self): def scale(self, value): """Set the display of the current data into a specific range. (ssa) """ - self.send_command('*ssa {}'.format(value)) - self.DeviceStatus = self.status # update cached device status + #Prevent setting the controler to a scale not compatible with the head + if value in self.ScalesHead: + self.send_command('*ssa {}'.format(value)) + self.DeviceStatus = self.status # update cached device status new_scale = Feat(values=set(('decrease','increase'))) - #An helper function to increase on decrease the scale + #An helper function to increase or decrease the scale @new_scale.setter def new_scale(self, value): """Increase or decrease the scale. @@ -333,7 +355,7 @@ def offset2(self, offset): 'Continuous': '6', 'Points': '7'} TimeStampEnabled = {False: 0, True: 1} - #TODO units + #TODO units ? @Feat(values=(None, SampleRateUnit, None, SamplePeriodUnit, None, TotalDurationUnit, TimeStampEnabled,)) def sampling(self): @@ -515,10 +537,6 @@ def status(self): else: # power mode (watt) DeviceStatus['Resolution'] = Q_(DeviceStatus['Resolution'], watt) - #Print dictionary (for debug) - for key in sorted(DeviceStatus.keys()): - print ("%s \t %s" % (key, DeviceStatus[key])) - return DeviceStatus @Feat() @@ -590,13 +608,47 @@ def send_command(self, s): self.send(s) self.recv(termination=self.RECV_DONE) # wait for RECV_DONE + #Helper functions + def print_device_status(self): + #Print dictionary (for debug) + for key in sorted(self.DeviceStatus.keys()): + print ("%s \t %s" % (key, self.DeviceStatus[key])) + + def test_instrument(self): + print('Testing instrument...') + + print("Instrument status:") + #print(inst.status) + self.print_device_status() + + #test display type. + #'statistic' and 'lineplot' doesn't seem to produce anything + test = ('real-time', 'histogram', 'statistic', 'needle', 'lineplot',) + for i in test: + time.sleep(2) + print('SET Display type: %s' % (i,)) + self.display = i + time.sleep(.2) + self.display = 'real-time' + + #test display scale + print("Available scales") + print(self.ScalesHead) + print("Test over all scales") + for i in self.Scales: + time.sleep(.5) + print("---") + print('SET Display scale: %s' % (i,)) + self.scale = i + print('GET : %s' % (self.scale,)) + def reshape_list_dict_in_dict(list_of_dict): # transform a list of dictionaries in a single dictionary out = {} for i in list_of_dict: out.update(i) - return out - + return out + if __name__ == '__main__': import argparse import lantz.log @@ -606,19 +658,17 @@ def reshape_list_dict_in_dict(list_of_dict): default=False, help='Show interactive GUI') parser.add_argument('-p', '--port', type=str, default='17', help='Serial port to connect to') + parser.add_argument('-t', '--test', action='store_true', + default=False, help='Test the device') args = parser.parse_args() - lantz.log.log_to_screen(lantz.log.DEBUG) + #lantz.log.log_to_screen(lantz.log.DEBUG) with N842PE(args.port) as inst: if args.interactive: from lantz.ui.qtwidgets import start_test_app start_test_app(inst) + elif args.test: + inst.test_instrument() else: - print('Testing instrument...') -# inst.dBm = False - inst.energy_mode = False - print(inst.status) - - inst.energy_mode = True - print(inst.status) + pass From f82e4df74c985b3dba54c3970d61997d90e108f2 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Fri, 18 Oct 2013 13:05:33 -0400 Subject: [PATCH 38/48] add more tests --- lantz/drivers/newport/842PE.py | 244 +++++++++++++++++++++++++++++---- 1 file changed, 221 insertions(+), 23 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index a4e4cbf..8fd4894 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -442,6 +442,7 @@ def anticipation(self, value): self.send_command('*eaa {}'.format(value)) self.DeviceStatus = self.status # update cached device status + #TODO is it a setter or a getter? set_zero = Feat(values={'off': 0, 'on': 1, 'undo': 2}) @set_zero.getter @@ -617,31 +618,226 @@ def print_device_status(self): def test_instrument(self): print('Testing instrument...') - print("Instrument status:") - #print(inst.status) - self.print_device_status() + if False: + print("Instrument status:") + #print(inst.status) # can also work (but un-ordered) + self.print_device_status() + + if False: + #test display type. + #'statistic' and 'lineplot' doesn't seem to produce anything + test = ('real-time', 'histogram', 'statistic', 'needle', 'lineplot',) + for i in test: + time.sleep(2) + print('SET Display type: %s' % (i,)) + self.display = i + time.sleep(.2) + self.display = 'real-time' + + if False: + #test display scale + print("Available scales") + print(self.ScalesHead) + print("Test over all scales") + for i in self.Scales: + time.sleep(.5) + print("---") + print('SET Display scale: %s' % (i,)) + self.scale = i + print('GET : %s' % (self.scale,)) + + self.energy_mode = False + + if False: + #TODO This test doesn't work because of caching + #test helper function new_scale() + #check limits + if self.energy_mode: #Joules + max_scale = self.DeviceStatus['ScaleMaxEnergy'] + min_scale = self.DeviceStatus['ScaleMinEnergy'] + else: + max_scale = self.DeviceStatus['ScaleMaxPower'] + min_scale = self.DeviceStatus['ScaleMinPower'] + start_scale = int((min_scale + max_scale)/2) + #Put the head to its mid range scale + print("Put scale to mid range") + start_scale_str = self.Scales[start_scale] + self.scale = start_scale_str + print("Increase scale many times") + for i in range((max_scale-min_scale)*2): + self.new_scale = 'increase' + print('New scale : %s' % (self.scale,)) + time.sleep(.5) + print("Decrease scale many times") + for i in range((max_scale-min_scale)*2): + self.new_scale = 'decrease' + print('New scale : %s' % (self.scale,)) + time.sleep(.5) + + if False: + #test dBm mode + print("Testing dBm mode") + test = (True, False,) + for i in test: + print("---") + print('SET : %s' % (i,)) + self.dBm = i + time.sleep(1) + + if False: + print("test high_resolution mode") + test = (True, False,) + for i in test: + print("---") + print('SET : %s' % (i,)) + self.high_resolution = i + print('Get : %s' % (self.high_resolution,)) + time.sleep(1) + + if False: + print("Testing getter current_value") + print("Current Value:") + print(self.current_value) + + if False: + print("Testing getter value_available") + print("Value Available:") + print(self.value_available) + + if False: + print("Testing getter get_statistics") + print("Statistics:") + print(self.get_statistics) + + + # @logging.setter + # def logging(self, value): + + # #Buggy + # @Feat() + # def get_log(self, value): + + # #Buggy + # @Feat() + # def get_data(self): + + # @Feat(units='nm') + # def wavelength(self): + # @wavelength.setter + # def wavelength(self, value): + + if False: + print("test attenuator mode") + test = (True, False,) + for i in test: + print('SET : %s' % (i,)) + self.attenuator = i + print('Get : %s' % (self.attenuator,)) + time.sleep(1) + print("---") + + # @Feat() + # def multiplier1(self): + # @multiplier1.setter + # def multiplier1(self, multiplier): + + # @Feat() + # def multiplier2(self): + # @multiplier2.setter + # def multiplier2(self, multiplier): + + # @Feat() + # def offset1(self): + # @offset1.setter + # def offset1(self, offset): + + # @Feat() + # def offset2(self): + # @offset2.setter + # def offset2(self, offset): + + # @Feat(values=(None, SampleRateUnit, None, SamplePeriodUnit, None, + # TotalDurationUnit, TimeStampEnabled,)) + # def sampling(self): + # @sampling.setter + # def sampling(self, value): + + # @Feat() + # def trigger(self): + # @trigger.setter + # def trigger(self, value): + + # set_statistics = Feat(values={'disable': 0, 'enable': 1, 'reset': 2}) + # @set_statistics.setter + # def set_statistics(self, value=True): + + + if False: + print("test energy_mode mode") + test = (True, False,) + for i in test: + print('SET : %s' % (i,)) + self.energy_mode = i + print('Get : %s' % (self.energy_mode,)) + time.sleep(1) + print("---") + + if False: + print("test anticipation mode") + test = (True, False,) + for i in test: + print('SET : %s' % (i,)) + self.anticipation = i + print('Get : %s' % (self.anticipation,)) + time.sleep(1) + print("---") + + # set_zero = Feat(values={'off': 0, 'on': 1, 'undo': 2}) + # @set_zero.getter + # def set_zero(self, value): + + if True: + print("test idn") + print(self.idn) + time.sleep(1) + print("---") - #test display type. - #'statistic' and 'lineplot' doesn't seem to produce anything - test = ('real-time', 'histogram', 'statistic', 'needle', 'lineplot',) - for i in test: - time.sleep(2) - print('SET Display type: %s' % (i,)) - self.display = i - time.sleep(.2) - self.display = 'real-time' - - #test display scale - print("Available scales") - print(self.ScalesHead) - print("Test over all scales") - for i in self.Scales: - time.sleep(.5) + if True: + print("test status") + print(self.status) + time.sleep(1) print("---") - print('SET Display scale: %s' % (i,)) - self.scale = i - print('GET : %s' % (self.scale,)) + if True: + print("test battery") + print(self.battery) + time.sleep(1) + print("---") + + # clock = Feat() + # @clock.setter + # def clock(self, t,): + + if False: + print("test backlight mode") + test = (True, False,) + for i in test: + print('SET : %s' % (i,)) + self.backlight = i + time.sleep(1) + print("---") + + if False: + print("test analog_port mode") + test = (True, False,) + for i in test: + print('SET : %s' % (i,)) + self.analog_port = i + print('Get : %s' % (self.analog_port,)) + time.sleep(1) + print("---") + + def reshape_list_dict_in_dict(list_of_dict): # transform a list of dictionaries in a single dictionary out = {} @@ -670,5 +866,7 @@ def reshape_list_dict_in_dict(list_of_dict): elif args.test: inst.test_instrument() else: - pass + inst.energy_mode = False + time.sleep(2) + inst.energy_mode = True From 742c02679edbf13548dec383b8a390126cfcebf2 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Fri, 18 Oct 2013 13:49:00 -0400 Subject: [PATCH 39/48] add test for wavelength --- lantz/drivers/newport/842PE.py | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 8fd4894..c2b1d06 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -98,6 +98,9 @@ def scale(self): out = self.DeviceStatus['CurrentScale'] return self.Scales[out] + #TODO Is there is a cleaner way to do this? + #The problem is that the controler accepts a range of scales but the head has a narrower range + #This range (head'd one) is only known after initialisation @scale.setter def scale(self, value): """Set the display of the current data into a specific range. (ssa) @@ -263,6 +266,7 @@ def get_data(self): #MEASUREMENT COMMANDS - SETUP + @Feat(units='nm') def wavelength(self): """Get the wavelength being used on the @@ -270,13 +274,17 @@ def wavelength(self): """ return self.DeviceStatus['ActiveWavelength'] + #TODO is there is a cleaner way to do this? + #I don't know if/how we can use limits, because it depends on the head we are using and only known after initialisation @wavelength.setter def wavelength(self, value): """Set the wavelength being used on the detector. (swa) """ - self.send_command('*swa {}'.format(value)) - self.DeviceStatus = self.status # update cached device status + #Prevent setting to a wavekength outside of the head range + if (value >= self.DeviceStatus['MinWavelengthIndex']) and (value <= self.DeviceStatus['MaxWavelengthIndex']): + self.send_command('*swa {}'.format(value)) + self.DeviceStatus = self.status # update cached device status @Feat(values={False: 0, True: 1}) def attenuator(self): @@ -721,6 +729,16 @@ def test_instrument(self): # @Feat() # def get_data(self): + if True: + print("test wavelength") + test = (500, 700, 900, 1100, 1300, 300, 100, -100,) + for i in test: + print('SET : %s' % (i * nanometer,)) + self.wavelength = i * nanometer + print('Get : %s' % (self.wavelength,)) + time.sleep(1) + print("---") + # @Feat(units='nm') # def wavelength(self): # @wavelength.setter From 6e0dedb6827228b0713ea1b18f5cc955a97f9a7b Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Fri, 18 Oct 2013 14:14:57 -0400 Subject: [PATCH 40/48] add tests for offsets and multipliers --- lantz/drivers/newport/842PE.py | 65 ++++++++++++++++++++++------------ 1 file changed, 43 insertions(+), 22 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index c2b1d06..8a8225f 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -276,6 +276,7 @@ def wavelength(self): #TODO is there is a cleaner way to do this? #I don't know if/how we can use limits, because it depends on the head we are using and only known after initialisation + #TODO value should be a int @wavelength.setter def wavelength(self, value): """Set the wavelength being used on the @@ -729,7 +730,7 @@ def test_instrument(self): # @Feat() # def get_data(self): - if True: + if False: print("test wavelength") test = (500, 700, 900, 1100, 1300, 300, 100, -100,) for i in test: @@ -739,11 +740,6 @@ def test_instrument(self): time.sleep(1) print("---") - # @Feat(units='nm') - # def wavelength(self): - # @wavelength.setter - # def wavelength(self, value): - if False: print("test attenuator mode") test = (True, False,) @@ -754,25 +750,50 @@ def test_instrument(self): time.sleep(1) print("---") - # @Feat() - # def multiplier1(self): - # @multiplier1.setter - # def multiplier1(self, multiplier): + #TODO sometime, we run on Timeouts + import numpy as np + if True: + print("test multiplier1") + for j in range(10): + i = (np.random.random_sample()-.5) * 4 + print('SET : %s' % (i,)) + self.multiplier1 = i + print('Get : %s' % (self.multiplier1,)) + time.sleep(1) + print("---") - # @Feat() - # def multiplier2(self): - # @multiplier2.setter - # def multiplier2(self, multiplier): + import numpy as np + if True: + print("test multiplier2") + for j in range(10): + i = (np.random.random_sample()-.5) * 4 + print('SET : %s' % (i,)) + self.multiplier2 = i + print('Get : %s' % (self.multiplier2,)) + time.sleep(1) + print("---") - # @Feat() - # def offset1(self): - # @offset1.setter - # def offset1(self, offset): + import numpy as np + if True: + print("test offset1") + for j in range(10): + i = (np.random.random_sample()-.5) * 4 + print('SET : %s' % (i,)) + self.offset1 = i + print('Get : %s' % (self.offset1,)) + time.sleep(1) + print("---") - # @Feat() - # def offset2(self): - # @offset2.setter - # def offset2(self, offset): + import numpy as np + if True: + print("test offset2") + for j in range(10): + i = (np.random.random_sample()-.5) * 4 + print('SET : %s' % (i,)) + self.offset2 = i + print('Get : %s' % (self.offset2,)) + time.sleep(1) + print("---") # @Feat(values=(None, SampleRateUnit, None, SamplePeriodUnit, None, # TotalDurationUnit, TimeStampEnabled,)) From a22b8ecb96824615f03eccad7bbab10d8e34fc97 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Fri, 18 Oct 2013 15:03:45 -0400 Subject: [PATCH 41/48] add test for trigger --- lantz/drivers/newport/842PE.py | 34 +++++++++++++++++++++------------- 1 file changed, 21 insertions(+), 13 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 8a8225f..797d8f3 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -396,7 +396,7 @@ def sampling(self, value): """ self.send_command('*dsu {} {} {} {} {} {} {}'.format(*value)) - @Feat() + @Feat(limits=(1,100)) def trigger(self): """Get the internal trigger level when using the device in energy reading mode. (tla) @@ -408,8 +408,12 @@ def trigger(self, value): """Set the internal trigger level when using the device in energy reading mode. (tla) """ - self.send_command('*tla {}'.format(value)) - self.DeviceStatus = self.status # update cached device status + if self.energy_mode: #Energy mode + self.send_command('*tla {}'.format(value)) + self.DeviceStatus = self.status # update cached device status + else: #Watt mode. This command is not valid + pass + #TODO should raise an error as it is not valid to set the trigger in watt mode #MEASUREMENT COMMANDS - MEASUREMENT CONTROL @@ -655,7 +659,7 @@ def test_instrument(self): self.scale = i print('GET : %s' % (self.scale,)) - self.energy_mode = False + self.energy_mode = True if False: #TODO This test doesn't work because of caching @@ -752,7 +756,7 @@ def test_instrument(self): #TODO sometime, we run on Timeouts import numpy as np - if True: + if False: print("test multiplier1") for j in range(10): i = (np.random.random_sample()-.5) * 4 @@ -763,7 +767,7 @@ def test_instrument(self): print("---") import numpy as np - if True: + if False: print("test multiplier2") for j in range(10): i = (np.random.random_sample()-.5) * 4 @@ -774,7 +778,7 @@ def test_instrument(self): print("---") import numpy as np - if True: + if False: print("test offset1") for j in range(10): i = (np.random.random_sample()-.5) * 4 @@ -785,7 +789,7 @@ def test_instrument(self): print("---") import numpy as np - if True: + if False: print("test offset2") for j in range(10): i = (np.random.random_sample()-.5) * 4 @@ -801,16 +805,20 @@ def test_instrument(self): # @sampling.setter # def sampling(self, value): - # @Feat() - # def trigger(self): - # @trigger.setter - # def trigger(self, value): + if False: + print("test trigger") + test = (2,5,10,34,45.45,60.1,60.2,60.3,60.4,60.51,67,99,100,1,) + for i in test: + print('SET : %s' % (i,)) + self.trigger = i + print('Get : %s' % (self.trigger,)) + time.sleep(1) + print("---") # set_statistics = Feat(values={'disable': 0, 'enable': 1, 'reset': 2}) # @set_statistics.setter # def set_statistics(self, value=True): - if False: print("test energy_mode mode") test = (True, False,) From 07ba54a23aa16ed6ebe1b119eaa7da3148ff1b04 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Fri, 18 Oct 2013 15:27:58 -0400 Subject: [PATCH 42/48] new_scale (setter) -> change scale (action) --- lantz/drivers/newport/842PE.py | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 797d8f3..0a88b5f 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -110,11 +110,9 @@ def scale(self, value): self.send_command('*ssa {}'.format(value)) self.DeviceStatus = self.status # update cached device status - new_scale = Feat(values=set(('decrease','increase'))) - + @Action(values=set(('decrease','increase'))) #An helper function to increase or decrease the scale - @new_scale.setter - def new_scale(self, value): + def change_scale(self, value): """Increase or decrease the scale. """ current_scale = self.DeviceStatus['CurrentScale'] @@ -647,6 +645,7 @@ def test_instrument(self): time.sleep(.2) self.display = 'real-time' + #TODO doesn't seems to work with the high power head if False: #test display scale print("Available scales") @@ -662,8 +661,6 @@ def test_instrument(self): self.energy_mode = True if False: - #TODO This test doesn't work because of caching - #test helper function new_scale() #check limits if self.energy_mode: #Joules max_scale = self.DeviceStatus['ScaleMaxEnergy'] @@ -676,14 +673,16 @@ def test_instrument(self): print("Put scale to mid range") start_scale_str = self.Scales[start_scale] self.scale = start_scale_str + print("Increase scale many times") - for i in range((max_scale-min_scale)*2): - self.new_scale = 'increase' + for i in range(int((max_scale-min_scale)/2)+3): + self.change_scale('increase') print('New scale : %s' % (self.scale,)) time.sleep(.5) + print("Decrease scale many times") - for i in range((max_scale-min_scale)*2): - self.new_scale = 'decrease' + for i in range((max_scale-min_scale)+3): + self.change_scale('decrease') print('New scale : %s' % (self.scale,)) time.sleep(.5) From a05de94caa5db01196ee04a812d7882b8a169525 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Fri, 18 Oct 2013 16:17:02 -0400 Subject: [PATCH 43/48] recalculate available scales when we change energy mode --- lantz/drivers/newport/842PE.py | 539 +++++++++++++++++---------------- 1 file changed, 281 insertions(+), 258 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 0a88b5f..4a6e923 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -11,6 +11,9 @@ # Cheched working with following heads: 818-UV, 818P, 918D-UV # This device also has a binary mode, witch is not implemented here. +#TODO sometime it craches, leaving crap in the buffer +# should clear buffer at initialisation + import time import warnings @@ -62,23 +65,24 @@ def __init__(self, *args, **kwargs): self.initialize() self.DeviceStatus = self.status # Read the device status - def available_scales(self): - """ - Returns valid scales for the current head - """ - #check limits of the head - if self.energy_mode: #Joules - max_scale = self.DeviceStatus['ScaleMaxEnergy'] - min_scale = self.DeviceStatus['ScaleMinEnergy'] - else: - max_scale = self.DeviceStatus['ScaleMaxPower'] - min_scale = self.DeviceStatus['ScaleMinPower'] - out = list(self.Scales[min_scale:max_scale+1]) - out.insert(0,self.Scales[0]) # 'auto' - return tuple(out) - #These are the whole scales the head can reach - self.ScalesHead = available_scales(self) + self.ScalesHead = self.available_scales() + + def available_scales(self): + """ + Returns valid scales for the current head + """ + #check limits of the head + if self.energy_mode: #Joules + max_scale = self.DeviceStatus['ScaleMaxEnergy'] + min_scale = self.DeviceStatus['ScaleMinEnergy'] + else: + max_scale = self.DeviceStatus['ScaleMaxPower'] + min_scale = self.DeviceStatus['ScaleMinPower'] + + out = list(self.Scales[min_scale:max_scale+1]) + out.insert(0,self.Scales[0]) # 'auto' + return tuple(out) #Display commands @@ -435,6 +439,7 @@ def energy_mode(self, value): if not('Photodiode' in self.DeviceStatus['HeadType']): self.send_command('*sca {}'.format(value)) self.DeviceStatus = self.status # update cached device status + self.ScalesHead = self.available_scales() else: # energy_mode cannot be activated with photodiodes warnings.warn('Cannot put energy_mode with a Photodiode') @@ -540,11 +545,13 @@ def status(self): DeviceStatus['Attenuator'] = 1 if (DeviceStatus['Attenuator'] == 'On') else 0 # On, Off or N/A. N/A is when there is not DeviceStatus['AutoScale'] = 1 if (DeviceStatus['AutoScale'] == 'On') else 0 - if DeviceStatus['EnergyMode']: # energy mode (joules) + if DeviceStatus['HeadType'] == 'WattMeter': # WattMeters have a valid ScaleMinEnergy and ScaleMaxEnergy # We cannot use self.energy_mode in the test condition because it is not # defined at instrument initialisation, so it creates an error DeviceStatus['ScaleMinEnergy'] = int(DeviceStatus['ScaleMinEnergy']) DeviceStatus['ScaleMaxEnergy'] = int(DeviceStatus['ScaleMaxEnergy']) + + if DeviceStatus['EnergyMode'] == 1: # energy mode (joules) DeviceStatus['Resolution'] = Q_(DeviceStatus['Resolution'], joule) else: # power mode (watt) DeviceStatus['Resolution'] = Q_(DeviceStatus['Resolution'], watt) @@ -630,196 +637,7 @@ def test_instrument(self): print('Testing instrument...') if False: - print("Instrument status:") - #print(inst.status) # can also work (but un-ordered) - self.print_device_status() - - if False: - #test display type. - #'statistic' and 'lineplot' doesn't seem to produce anything - test = ('real-time', 'histogram', 'statistic', 'needle', 'lineplot',) - for i in test: - time.sleep(2) - print('SET Display type: %s' % (i,)) - self.display = i - time.sleep(.2) - self.display = 'real-time' - - #TODO doesn't seems to work with the high power head - if False: - #test display scale - print("Available scales") - print(self.ScalesHead) - print("Test over all scales") - for i in self.Scales: - time.sleep(.5) - print("---") - print('SET Display scale: %s' % (i,)) - self.scale = i - print('GET : %s' % (self.scale,)) - - self.energy_mode = True - - if False: - #check limits - if self.energy_mode: #Joules - max_scale = self.DeviceStatus['ScaleMaxEnergy'] - min_scale = self.DeviceStatus['ScaleMinEnergy'] - else: - max_scale = self.DeviceStatus['ScaleMaxPower'] - min_scale = self.DeviceStatus['ScaleMinPower'] - start_scale = int((min_scale + max_scale)/2) - #Put the head to its mid range scale - print("Put scale to mid range") - start_scale_str = self.Scales[start_scale] - self.scale = start_scale_str - - print("Increase scale many times") - for i in range(int((max_scale-min_scale)/2)+3): - self.change_scale('increase') - print('New scale : %s' % (self.scale,)) - time.sleep(.5) - - print("Decrease scale many times") - for i in range((max_scale-min_scale)+3): - self.change_scale('decrease') - print('New scale : %s' % (self.scale,)) - time.sleep(.5) - - if False: - #test dBm mode - print("Testing dBm mode") - test = (True, False,) - for i in test: - print("---") - print('SET : %s' % (i,)) - self.dBm = i - time.sleep(1) - - if False: - print("test high_resolution mode") - test = (True, False,) - for i in test: - print("---") - print('SET : %s' % (i,)) - self.high_resolution = i - print('Get : %s' % (self.high_resolution,)) - time.sleep(1) - - if False: - print("Testing getter current_value") - print("Current Value:") - print(self.current_value) - - if False: - print("Testing getter value_available") - print("Value Available:") - print(self.value_available) - - if False: - print("Testing getter get_statistics") - print("Statistics:") - print(self.get_statistics) - - - # @logging.setter - # def logging(self, value): - - # #Buggy - # @Feat() - # def get_log(self, value): - - # #Buggy - # @Feat() - # def get_data(self): - - if False: - print("test wavelength") - test = (500, 700, 900, 1100, 1300, 300, 100, -100,) - for i in test: - print('SET : %s' % (i * nanometer,)) - self.wavelength = i * nanometer - print('Get : %s' % (self.wavelength,)) - time.sleep(1) - print("---") - - if False: - print("test attenuator mode") - test = (True, False,) - for i in test: - print('SET : %s' % (i,)) - self.attenuator = i - print('Get : %s' % (self.attenuator,)) - time.sleep(1) - print("---") - - #TODO sometime, we run on Timeouts - import numpy as np - if False: - print("test multiplier1") - for j in range(10): - i = (np.random.random_sample()-.5) * 4 - print('SET : %s' % (i,)) - self.multiplier1 = i - print('Get : %s' % (self.multiplier1,)) - time.sleep(1) - print("---") - - import numpy as np - if False: - print("test multiplier2") - for j in range(10): - i = (np.random.random_sample()-.5) * 4 - print('SET : %s' % (i,)) - self.multiplier2 = i - print('Get : %s' % (self.multiplier2,)) - time.sleep(1) - print("---") - - import numpy as np - if False: - print("test offset1") - for j in range(10): - i = (np.random.random_sample()-.5) * 4 - print('SET : %s' % (i,)) - self.offset1 = i - print('Get : %s' % (self.offset1,)) - time.sleep(1) - print("---") - - import numpy as np - if False: - print("test offset2") - for j in range(10): - i = (np.random.random_sample()-.5) * 4 - print('SET : %s' % (i,)) - self.offset2 = i - print('Get : %s' % (self.offset2,)) - time.sleep(1) - print("---") - - # @Feat(values=(None, SampleRateUnit, None, SamplePeriodUnit, None, - # TotalDurationUnit, TimeStampEnabled,)) - # def sampling(self): - # @sampling.setter - # def sampling(self, value): - - if False: - print("test trigger") - test = (2,5,10,34,45.45,60.1,60.2,60.3,60.4,60.51,67,99,100,1,) - for i in test: - print('SET : %s' % (i,)) - self.trigger = i - print('Get : %s' % (self.trigger,)) - time.sleep(1) - print("---") - - # set_statistics = Feat(values={'disable': 0, 'enable': 1, 'reset': 2}) - # @set_statistics.setter - # def set_statistics(self, value=True): - - if False: - print("test energy_mode mode") + print("test energy_mode") test = (True, False,) for i in test: print('SET : %s' % (i,)) @@ -828,60 +646,265 @@ def test_instrument(self): time.sleep(1) print("---") - if False: - print("test anticipation mode") - test = (True, False,) - for i in test: - print('SET : %s' % (i,)) - self.anticipation = i - print('Get : %s' % (self.anticipation,)) - time.sleep(1) - print("---") - - # set_zero = Feat(values={'off': 0, 'on': 1, 'undo': 2}) - # @set_zero.getter - # def set_zero(self, value): - - if True: - print("test idn") - print(self.idn) - time.sleep(1) - print("---") - - if True: - print("test status") - print(self.status) - time.sleep(1) - print("---") - - if True: - print("test battery") - print(self.battery) + print("test everything else against energy_mode") + test = (False, True,) + for i in test: + print("-----------------------------------------") + print('test with energy mode = %s' % (i,)) + self.energy_mode = i + print('Energy mode : %s' % (self.energy_mode,)) time.sleep(1) - print("---") - - # clock = Feat() - # @clock.setter - # def clock(self, t,): - - if False: - print("test backlight mode") - test = (True, False,) - for i in test: - print('SET : %s' % (i,)) - self.backlight = i - time.sleep(1) + if self.energy_mode != i: + pass # Cannot be in Energy Mode with this detector/head + else: print("---") - if False: - print("test analog_port mode") - test = (True, False,) - for i in test: - print('SET : %s' % (i,)) - self.analog_port = i - print('Get : %s' % (self.analog_port,)) - time.sleep(1) - print("---") + print("Instrument status:") + self.print_device_status() + print(self.status) + print("-----") + + if False: + print("Instrument status:") + #print(inst.status) # can also work (but un-ordered) + self.print_device_status() + + if False: + #test display type. + #'statistic' and 'lineplot' doesn't seem to produce anything + test = ('real-time', 'histogram', 'statistic', 'needle', 'lineplot',) + for i in test: + time.sleep(2) + print('SET Display type: %s' % (i,)) + self.display = i + time.sleep(.2) + self.display = 'real-time' + + #TODO doesn't seems to work with the high power head + if True: + #test display scale + print("Available scales") + print(self.ScalesHead) + print("Test over all scales") + for i in self.Scales: + time.sleep(.5) + print("---") + print('SET Display scale: %s' % (i,)) + self.scale = i + print('GET : %s' % (self.scale,)) + + if False: + #check limits + if self.energy_mode: #Joules + max_scale = self.DeviceStatus['ScaleMaxEnergy'] + min_scale = self.DeviceStatus['ScaleMinEnergy'] + else: + max_scale = self.DeviceStatus['ScaleMaxPower'] + min_scale = self.DeviceStatus['ScaleMinPower'] + start_scale = int((min_scale + max_scale)/2) + #Put the head to its mid range scale + print("Put scale to mid range") + start_scale_str = self.Scales[start_scale] + self.scale = start_scale_str + + print("Increase scale many times") + for i in range(int((max_scale-min_scale)/2)+3): + self.change_scale('increase') + print('New scale : %s' % (self.scale,)) + time.sleep(.5) + + print("Decrease scale many times") + for i in range((max_scale-min_scale)+3): + self.change_scale('decrease') + print('New scale : %s' % (self.scale,)) + time.sleep(.5) + + if False: + #test dBm mode + print("Testing dBm mode") + test = (True, False,) + for i in test: + print("---") + print('SET : %s' % (i,)) + self.dBm = i + time.sleep(1) + + if False: + print("test high_resolution mode") + test = (True, False,) + for i in test: + print("---") + print('SET : %s' % (i,)) + self.high_resolution = i + print('Get : %s' % (self.high_resolution,)) + time.sleep(1) + + if False: + print("Testing getter current_value") + print("Current Value:") + print(self.current_value) + + if False: + print("Testing getter value_available") + print("Value Available:") + print(self.value_available) + + if False: + print("Testing getter get_statistics") + print("Statistics:") + print(self.get_statistics) + + + # @logging.setter + # def logging(self, value): + + # #Buggy + # @Feat() + # def get_log(self, value): + + # #Buggy + # @Feat() + # def get_data(self): + + if False: + print("test wavelength") + test = (500, 700, 900, 1100, 1300, 300, 100, -100,) + for i in test: + print('SET : %s' % (i * nanometer,)) + self.wavelength = i * nanometer + print('Get : %s' % (self.wavelength,)) + time.sleep(1) + print("---") + + if False: + print("test attenuator mode") + test = (True, False,) + for i in test: + print('SET : %s' % (i,)) + self.attenuator = i + print('Get : %s' % (self.attenuator,)) + time.sleep(1) + print("---") + + #TODO sometime, we run on Timeouts + import numpy as np + if False: + print("test multiplier1") + for j in range(10): + i = (np.random.random_sample()-.5) * 4 + print('SET : %s' % (i,)) + self.multiplier1 = i + print('Get : %s' % (self.multiplier1,)) + time.sleep(1) + print("---") + + import numpy as np + if False: + print("test multiplier2") + for j in range(10): + i = (np.random.random_sample()-.5) * 4 + print('SET : %s' % (i,)) + self.multiplier2 = i + print('Get : %s' % (self.multiplier2,)) + time.sleep(1) + print("---") + + import numpy as np + if False: + print("test offset1") + for j in range(10): + i = (np.random.random_sample()-.5) * 4 + print('SET : %s' % (i,)) + self.offset1 = i + print('Get : %s' % (self.offset1,)) + time.sleep(1) + print("---") + + import numpy as np + if False: + print("test offset2") + for j in range(10): + i = (np.random.random_sample()-.5) * 4 + print('SET : %s' % (i,)) + self.offset2 = i + print('Get : %s' % (self.offset2,)) + time.sleep(1) + print("---") + + # @Feat(values=(None, SampleRateUnit, None, SamplePeriodUnit, None, + # TotalDurationUnit, TimeStampEnabled,)) + # def sampling(self): + # @sampling.setter + # def sampling(self, value): + + if False: + print("test trigger") + test = (2,5,10,34,45.45,60.1,60.2,60.3,60.4,60.51,67,99,100,1,) + for i in test: + print('SET : %s' % (i,)) + self.trigger = i + print('Get : %s' % (self.trigger,)) + time.sleep(1) + print("---") + + # set_statistics = Feat(values={'disable': 0, 'enable': 1, 'reset': 2}) + # @set_statistics.setter + # def set_statistics(self, value=True): + + if False: + print("test anticipation mode") + test = (True, False,) + for i in test: + print('SET : %s' % (i,)) + self.anticipation = i + print('Get : %s' % (self.anticipation,)) + time.sleep(1) + print("---") + + # set_zero = Feat(values={'off': 0, 'on': 1, 'undo': 2}) + # @set_zero.getter + # def set_zero(self, value): + + if False: + print("test idn") + print(self.idn) + time.sleep(1) + print("---") + + if False: + print("test status") + print(self.status) + time.sleep(1) + print("---") + + if False: + print("test battery") + print(self.battery) + time.sleep(1) + print("---") + + # clock = Feat() + # @clock.setter + # def clock(self, t,): + + if False: + print("test backlight mode") + test = (True, False,) + for i in test: + print('SET : %s' % (i,)) + self.backlight = i + time.sleep(1) + print("---") + + if False: + print("test analog_port mode") + test = (True, False,) + for i in test: + print('SET : %s' % (i,)) + self.analog_port = i + print('Get : %s' % (self.analog_port,)) + time.sleep(1) + print("---") def reshape_list_dict_in_dict(list_of_dict): From 944a27fb56b441dc7504721cb434232bdfacfc64 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Tue, 22 Oct 2013 14:49:15 -0400 Subject: [PATCH 44/48] add file for tests --- lantz/drivers/newport/842PE.py | 277 +--------------------------- lantz/drivers/newport/test842PE.py | 284 +++++++++++++++++++++++++++++ 2 files changed, 286 insertions(+), 275 deletions(-) create mode 100644 lantz/drivers/newport/test842PE.py diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 4a6e923..46c44a9 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -632,280 +632,6 @@ def print_device_status(self): #Print dictionary (for debug) for key in sorted(self.DeviceStatus.keys()): print ("%s \t %s" % (key, self.DeviceStatus[key])) - - def test_instrument(self): - print('Testing instrument...') - - if False: - print("test energy_mode") - test = (True, False,) - for i in test: - print('SET : %s' % (i,)) - self.energy_mode = i - print('Get : %s' % (self.energy_mode,)) - time.sleep(1) - print("---") - - print("test everything else against energy_mode") - test = (False, True,) - for i in test: - print("-----------------------------------------") - print('test with energy mode = %s' % (i,)) - self.energy_mode = i - print('Energy mode : %s' % (self.energy_mode,)) - time.sleep(1) - if self.energy_mode != i: - pass # Cannot be in Energy Mode with this detector/head - else: - print("---") - - print("Instrument status:") - self.print_device_status() - print(self.status) - print("-----") - - if False: - print("Instrument status:") - #print(inst.status) # can also work (but un-ordered) - self.print_device_status() - - if False: - #test display type. - #'statistic' and 'lineplot' doesn't seem to produce anything - test = ('real-time', 'histogram', 'statistic', 'needle', 'lineplot',) - for i in test: - time.sleep(2) - print('SET Display type: %s' % (i,)) - self.display = i - time.sleep(.2) - self.display = 'real-time' - - #TODO doesn't seems to work with the high power head - if True: - #test display scale - print("Available scales") - print(self.ScalesHead) - print("Test over all scales") - for i in self.Scales: - time.sleep(.5) - print("---") - print('SET Display scale: %s' % (i,)) - self.scale = i - print('GET : %s' % (self.scale,)) - - if False: - #check limits - if self.energy_mode: #Joules - max_scale = self.DeviceStatus['ScaleMaxEnergy'] - min_scale = self.DeviceStatus['ScaleMinEnergy'] - else: - max_scale = self.DeviceStatus['ScaleMaxPower'] - min_scale = self.DeviceStatus['ScaleMinPower'] - start_scale = int((min_scale + max_scale)/2) - #Put the head to its mid range scale - print("Put scale to mid range") - start_scale_str = self.Scales[start_scale] - self.scale = start_scale_str - - print("Increase scale many times") - for i in range(int((max_scale-min_scale)/2)+3): - self.change_scale('increase') - print('New scale : %s' % (self.scale,)) - time.sleep(.5) - - print("Decrease scale many times") - for i in range((max_scale-min_scale)+3): - self.change_scale('decrease') - print('New scale : %s' % (self.scale,)) - time.sleep(.5) - - if False: - #test dBm mode - print("Testing dBm mode") - test = (True, False,) - for i in test: - print("---") - print('SET : %s' % (i,)) - self.dBm = i - time.sleep(1) - - if False: - print("test high_resolution mode") - test = (True, False,) - for i in test: - print("---") - print('SET : %s' % (i,)) - self.high_resolution = i - print('Get : %s' % (self.high_resolution,)) - time.sleep(1) - - if False: - print("Testing getter current_value") - print("Current Value:") - print(self.current_value) - - if False: - print("Testing getter value_available") - print("Value Available:") - print(self.value_available) - - if False: - print("Testing getter get_statistics") - print("Statistics:") - print(self.get_statistics) - - - # @logging.setter - # def logging(self, value): - - # #Buggy - # @Feat() - # def get_log(self, value): - - # #Buggy - # @Feat() - # def get_data(self): - - if False: - print("test wavelength") - test = (500, 700, 900, 1100, 1300, 300, 100, -100,) - for i in test: - print('SET : %s' % (i * nanometer,)) - self.wavelength = i * nanometer - print('Get : %s' % (self.wavelength,)) - time.sleep(1) - print("---") - - if False: - print("test attenuator mode") - test = (True, False,) - for i in test: - print('SET : %s' % (i,)) - self.attenuator = i - print('Get : %s' % (self.attenuator,)) - time.sleep(1) - print("---") - - #TODO sometime, we run on Timeouts - import numpy as np - if False: - print("test multiplier1") - for j in range(10): - i = (np.random.random_sample()-.5) * 4 - print('SET : %s' % (i,)) - self.multiplier1 = i - print('Get : %s' % (self.multiplier1,)) - time.sleep(1) - print("---") - - import numpy as np - if False: - print("test multiplier2") - for j in range(10): - i = (np.random.random_sample()-.5) * 4 - print('SET : %s' % (i,)) - self.multiplier2 = i - print('Get : %s' % (self.multiplier2,)) - time.sleep(1) - print("---") - - import numpy as np - if False: - print("test offset1") - for j in range(10): - i = (np.random.random_sample()-.5) * 4 - print('SET : %s' % (i,)) - self.offset1 = i - print('Get : %s' % (self.offset1,)) - time.sleep(1) - print("---") - - import numpy as np - if False: - print("test offset2") - for j in range(10): - i = (np.random.random_sample()-.5) * 4 - print('SET : %s' % (i,)) - self.offset2 = i - print('Get : %s' % (self.offset2,)) - time.sleep(1) - print("---") - - # @Feat(values=(None, SampleRateUnit, None, SamplePeriodUnit, None, - # TotalDurationUnit, TimeStampEnabled,)) - # def sampling(self): - # @sampling.setter - # def sampling(self, value): - - if False: - print("test trigger") - test = (2,5,10,34,45.45,60.1,60.2,60.3,60.4,60.51,67,99,100,1,) - for i in test: - print('SET : %s' % (i,)) - self.trigger = i - print('Get : %s' % (self.trigger,)) - time.sleep(1) - print("---") - - # set_statistics = Feat(values={'disable': 0, 'enable': 1, 'reset': 2}) - # @set_statistics.setter - # def set_statistics(self, value=True): - - if False: - print("test anticipation mode") - test = (True, False,) - for i in test: - print('SET : %s' % (i,)) - self.anticipation = i - print('Get : %s' % (self.anticipation,)) - time.sleep(1) - print("---") - - # set_zero = Feat(values={'off': 0, 'on': 1, 'undo': 2}) - # @set_zero.getter - # def set_zero(self, value): - - if False: - print("test idn") - print(self.idn) - time.sleep(1) - print("---") - - if False: - print("test status") - print(self.status) - time.sleep(1) - print("---") - - if False: - print("test battery") - print(self.battery) - time.sleep(1) - print("---") - - # clock = Feat() - # @clock.setter - # def clock(self, t,): - - if False: - print("test backlight mode") - test = (True, False,) - for i in test: - print('SET : %s' % (i,)) - self.backlight = i - time.sleep(1) - print("---") - - if False: - print("test analog_port mode") - test = (True, False,) - for i in test: - print('SET : %s' % (i,)) - self.analog_port = i - print('Get : %s' % (self.analog_port,)) - time.sleep(1) - print("---") - def reshape_list_dict_in_dict(list_of_dict): # transform a list of dictionaries in a single dictionary @@ -933,7 +659,8 @@ def reshape_list_dict_in_dict(list_of_dict): from lantz.ui.qtwidgets import start_test_app start_test_app(inst) elif args.test: - inst.test_instrument() + import test842PE + test842PE.test_instrument(inst) else: inst.energy_mode = False time.sleep(2) diff --git a/lantz/drivers/newport/test842PE.py b/lantz/drivers/newport/test842PE.py new file mode 100644 index 0000000..6d8fea6 --- /dev/null +++ b/lantz/drivers/newport/test842PE.py @@ -0,0 +1,284 @@ +# -*- coding: utf-8 -*- +""" + lantz.drivers.newport.842PE + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + Newport 842-PE powermeter + + :copyright: 2013 by Lantz Authors, see AUTHORS for more details. + :license: BSD, see LICENSE for more details. +""" +# Test functionnalities of the powermeter + +def test_instrument(inst): + print('Testing instrument...') + + if False: + print("test energy_mode") + test = (False, True,) + for i in test: + print('SET : %s' % (i,)) + inst.energy_mode = i + print('Get : %s' % (inst.energy_mode,)) + time.sleep(1) + print("---") + + print("test everything else against energy_mode") + test = (False, True,) + for i in test: + print("-----------------------------------------") + print('test with energy mode = %s' % (i,)) + inst.energy_mode = i + print('Energy mode : %s' % (inst.energy_mode,)) + time.sleep(1) + if inst.energy_mode != i: + pass # Cannot be in Energy Mode with this detector/head + else: + print("---") + + print("Instrument status:") + inst.print_device_status() + print(inst.status) + print("-----") + + if False: + print("Instrument status:") + #print(inst.status) # can also work (but un-ordered) + inst.print_device_status() + + if False: + #test display type. + #'statistic' and 'lineplot' doesn't seem to produce anything + test = ('real-time', 'histogram', 'statistic', 'needle', 'lineplot',) + for i in test: + time.sleep(2) + print('SET Display type: %s' % (i,)) + inst.display = i + time.sleep(.2) + inst.display = 'real-time' + + if True: + #test display scale + print("Available scales") + print(inst.ScalesHead) + print("Test over all scales") + for i in inst.Scales: + time.sleep(.5) + print("---") + print('SET Display scale: %s' % (i,)) + inst.scale = i + print('GET : %s' % (inst.scale,)) + + if False: + #check limits + if inst.energy_mode: #Joules + max_scale = inst.DeviceStatus['ScaleMaxEnergy'] + min_scale = inst.DeviceStatus['ScaleMinEnergy'] + else: + max_scale = inst.DeviceStatus['ScaleMaxPower'] + min_scale = inst.DeviceStatus['ScaleMinPower'] + start_scale = int((min_scale + max_scale)/2) + #Put the head to its mid range scale + print("Put scale to mid range") + start_scale_str = inst.Scales[start_scale] + inst.scale = start_scale_str + + print("Increase scale many times") + for i in range(int((max_scale-min_scale)/2)+3): + inst.change_scale('increase') + print('New scale : %s' % (inst.scale,)) + time.sleep(.5) + + print("Decrease scale many times") + for i in range((max_scale-min_scale)+3): + inst.change_scale('decrease') + print('New scale : %s' % (inst.scale,)) + time.sleep(.5) + + if False: + #test dBm mode + print("Testing dBm mode") + test = (True, False,) + for i in test: + print("---") + print('SET : %s' % (i,)) + inst.dBm = i + time.sleep(1) + + if False: + print("test high_resolution mode") + test = (True, False,) + for i in test: + print("---") + print('SET : %s' % (i,)) + inst.high_resolution = i + print('Get : %s' % (inst.high_resolution,)) + time.sleep(1) + + if False: + print("Testing getter current_value") + print("Current Value:") + print(inst.current_value) + + if False: + print("Testing getter value_available") + print("Value Available:") + print(inst.value_available) + + if False: + print("Testing getter get_statistics") + print("Statistics:") + print(inst.get_statistics) + + + # @logging.setter + # def logging(inst, value): + + # #Buggy + # @Feat() + # def get_log(inst, value): + + # #Buggy + # @Feat() + # def get_data(inst): + + if False: + print("test wavelength") + test = (500, 700, 900, 1100, 1300, 300, 100, -100,) + for i in test: + print('SET : %s' % (i * nanometer,)) + inst.wavelength = i * nanometer + print('Get : %s' % (inst.wavelength,)) + time.sleep(1) + print("---") + + if False: + print("test attenuator mode") + test = (True, False,) + for i in test: + print('SET : %s' % (i,)) + inst.attenuator = i + print('Get : %s' % (inst.attenuator,)) + time.sleep(1) + print("---") + + #TODO sometime, we run on Timeouts + import numpy as np + if False: + print("test multiplier1") + for j in range(10): + i = (np.random.random_sample()-.5) * 4 + print('SET : %s' % (i,)) + inst.multiplier1 = i + print('Get : %s' % (inst.multiplier1,)) + time.sleep(1) + print("---") + + import numpy as np + if False: + print("test multiplier2") + for j in range(10): + i = (np.random.random_sample()-.5) * 4 + print('SET : %s' % (i,)) + inst.multiplier2 = i + print('Get : %s' % (inst.multiplier2,)) + time.sleep(1) + print("---") + + import numpy as np + if False: + print("test offset1") + for j in range(10): + i = (np.random.random_sample()-.5) * 4 + print('SET : %s' % (i,)) + inst.offset1 = i + print('Get : %s' % (inst.offset1,)) + time.sleep(1) + print("---") + + import numpy as np + if False: + print("test offset2") + for j in range(10): + i = (np.random.random_sample()-.5) * 4 + print('SET : %s' % (i,)) + inst.offset2 = i + print('Get : %s' % (inst.offset2,)) + time.sleep(1) + print("---") + + # @Feat(values=(None, SampleRateUnit, None, SamplePeriodUnit, None, + # TotalDurationUnit, TimeStampEnabled,)) + # def sampling(inst): + # @sampling.setter + # def sampling(inst, value): + + if False: + print("test trigger") + test = (2,5,10,34,45.45,60.1,60.2,60.3,60.4,60.51,67,99,100,1,) + for i in test: + print('SET : %s' % (i,)) + inst.trigger = i + print('Get : %s' % (inst.trigger,)) + time.sleep(1) + print("---") + + # set_statistics = Feat(values={'disable': 0, 'enable': 1, 'reset': 2}) + # @set_statistics.setter + # def set_statistics(inst, value=True): + + if False: + print("test anticipation mode") + test = (True, False,) + for i in test: + print('SET : %s' % (i,)) + inst.anticipation = i + print('Get : %s' % (inst.anticipation,)) + time.sleep(1) + print("---") + + # set_zero = Feat(values={'off': 0, 'on': 1, 'undo': 2}) + # @set_zero.getter + # def set_zero(inst, value): + + if False: + print("test idn") + print(inst.idn) + time.sleep(1) + print("---") + + if False: + print("test status") + print(inst.status) + time.sleep(1) + print("---") + + if False: + print("test battery") + print(inst.battery) + time.sleep(1) + print("---") + + # clock = Feat() + # @clock.setter + # def clock(inst, t,): + + if False: + print("test backlight mode") + test = (True, False,) + for i in test: + print('SET : %s' % (i,)) + inst.backlight = i + time.sleep(1) + print("---") + + if False: + print("test analog_port mode") + test = (True, False,) + for i in test: + print('SET : %s' % (i,)) + inst.analog_port = i + print('Get : %s' % (inst.analog_port,)) + time.sleep(1) + print("---") + From 02544b1716dbd7035a4e6b1f2037f225d3ddc008 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Tue, 22 Oct 2013 16:22:23 -0400 Subject: [PATCH 45/48] add test + corrections for sampling --- lantz/drivers/newport/842PE.py | 7 +++++++ lantz/drivers/newport/test842PE.py | 28 ++++++++++++++++++++++------ 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 46c44a9..62e04c0 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -396,6 +396,13 @@ def sampling(self, value): """Set the data sampling parameters for the logging and statistics environments. (dsu) """ + # Using '% of pulses' as SampleRateUnit + # or 'Pulses' as SamplePeriodUnit + # is not valid in Power Mode (and will create an error) + if not self.energy_mode: # we are in Power Mode + if (value[1] == '4') or (value[3] == '5'): + warnings.warn('Setting not available with Power Mode') + return self.send_command('*dsu {} {} {} {} {} {} {}'.format(*value)) @Feat(limits=(1,100)) diff --git a/lantz/drivers/newport/test842PE.py b/lantz/drivers/newport/test842PE.py index 6d8fea6..de8b24d 100644 --- a/lantz/drivers/newport/test842PE.py +++ b/lantz/drivers/newport/test842PE.py @@ -9,6 +9,7 @@ :license: BSD, see LICENSE for more details. """ # Test functionnalities of the powermeter +import time def test_instrument(inst): print('Testing instrument...') @@ -57,7 +58,7 @@ def test_instrument(inst): time.sleep(.2) inst.display = 'real-time' - if True: + if False: #test display scale print("Available scales") print(inst.ScalesHead) @@ -207,11 +208,26 @@ def test_instrument(inst): time.sleep(1) print("---") - # @Feat(values=(None, SampleRateUnit, None, SamplePeriodUnit, None, - # TotalDurationUnit, TimeStampEnabled,)) - # def sampling(inst): - # @sampling.setter - # def sampling(inst, value): + if True: + from random import choice + import numpy as np + print("test sampling") + for j in range(1000): + sample_rate = np.random.random_integers(1,999) + sample_rate_unit = choice(['Seconds', 'Minutes', 'Hours', 'Days', '% of pulses']) + sample_period = np.random.random_integers(1,100) + sample_period_unit = choice(['Seconds', 'Minutes', 'Hours', 'Days', 'Weeks', 'Pulses']) + total_duration = np.random.random_integers(1,100) + total_duration_unit = choice(['Period', 'Seconds', 'Minutes', 'Hours', 'Days', 'Weeks', 'Continuous', 'Points']) + timestamp = choice([False, True]) + sampling_settings = (sample_rate, sample_rate_unit, sample_period, sample_period_unit, total_duration, total_duration_unit, timestamp) + #sampling_settings = (90, 'Days', 30, 'Hours', 44, 'Weeks', True) + + print('SET : RATE: %s %s, PERIOD %s %s, TOTAL DURATION: %s %s, TIMESTAMP %s' % sampling_settings ) + inst.sampling = sampling_settings + print('GET : : %s %s, %s %s, : %s %s, %s' % inst.sampling) + #time.sleep(1) + print("---") if False: print("test trigger") From 5e7851a8f9d51ef4b9cf0e2a2d5c05c367827983 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Tue, 22 Oct 2013 17:01:28 -0400 Subject: [PATCH 46/48] new tests --- lantz/drivers/newport/842PE.py | 3 +-- lantz/drivers/newport/test842PE.py | 29 ++++++++++++++++++++++------- 2 files changed, 23 insertions(+), 9 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index 62e04c0..a42a14a 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -465,10 +465,9 @@ def anticipation(self, value): self.send_command('*eaa {}'.format(value)) self.DeviceStatus = self.status # update cached device status - #TODO is it a setter or a getter? set_zero = Feat(values={'off': 0, 'on': 1, 'undo': 2}) - @set_zero.getter + @set_zero.setter def set_zero(self, value): """Set the instrument zero mode. (eoa) diff --git a/lantz/drivers/newport/test842PE.py b/lantz/drivers/newport/test842PE.py index de8b24d..938839b 100644 --- a/lantz/drivers/newport/test842PE.py +++ b/lantz/drivers/newport/test842PE.py @@ -37,6 +37,10 @@ def test_instrument(inst): else: print("---") + print("Set auto scale") + inst.scale = 'auto' + time.sleep(5) + print("Instrument status:") inst.print_device_status() print(inst.status) @@ -208,7 +212,7 @@ def test_instrument(inst): time.sleep(1) print("---") - if True: + if False: from random import choice import numpy as np print("test sampling") @@ -239,9 +243,15 @@ def test_instrument(inst): time.sleep(1) print("---") - # set_statistics = Feat(values={'disable': 0, 'enable': 1, 'reset': 2}) - # @set_statistics.setter - # def set_statistics(inst, value=True): + #TODO : No error, but how to test it really? + if False: + print("test set_statistics") + test = ('disable', 'enable', 'reset') + for i in test: + print('SET : %s' % (i,)) + set_statistics = i + time.sleep(1) + print("---") if False: print("test anticipation mode") @@ -253,9 +263,14 @@ def test_instrument(inst): time.sleep(1) print("---") - # set_zero = Feat(values={'off': 0, 'on': 1, 'undo': 2}) - # @set_zero.getter - # def set_zero(inst, value): + if False: + print("test set_zero") + test = ('off', 'on', 'undo') + for i in test: + print('SET : %s' % (i,)) + inst.set_zero = i + time.sleep(1) + print("---") if False: print("test idn") From db9323a73f7f6b0019c148541dd5935c1930d937 Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Tue, 22 Oct 2013 17:38:38 -0400 Subject: [PATCH 47/48] new tests --- lantz/drivers/newport/842PE.py | 5 ++--- lantz/drivers/newport/test842PE.py | 18 ++++++++++++------ 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index a42a14a..f1250b8 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -573,12 +573,11 @@ def battery(self): clock = Feat() @clock.setter - def clock(self, t,): + def clock(self, t): """Set the time and date of the monitor's internal clock. (clk) - The optional argument is a time.struct_time - If omited, it'll use current time + t is time.struct_time """ s = time.strftime('*clk %d %m %Y %I %M %S ', t) pm = '1' if time.strftime('%p', t) == 'PM' else '0' # PM -> 1, AM -> 0 diff --git a/lantz/drivers/newport/test842PE.py b/lantz/drivers/newport/test842PE.py index 938839b..c0169b2 100644 --- a/lantz/drivers/newport/test842PE.py +++ b/lantz/drivers/newport/test842PE.py @@ -39,7 +39,7 @@ def test_instrument(inst): print("Set auto scale") inst.scale = 'auto' - time.sleep(5) + time.sleep(2) print("Instrument status:") inst.print_device_status() @@ -136,8 +136,14 @@ def test_instrument(inst): print(inst.get_statistics) - # @logging.setter - # def logging(inst, value): + if True: + print("test logging (setter)") + test = ('start raw', 'stop', 'start saving', 'stop', 'save both', 'stop') + for i in test: + print('SET : %s' % (i,)) + inst.logging = i + time.sleep(1) + print("---") # #Buggy # @Feat() @@ -290,9 +296,9 @@ def test_instrument(inst): time.sleep(1) print("---") - # clock = Feat() - # @clock.setter - # def clock(inst, t,): + if False: + print("test clock (setter)") + inst.clock = time.localtime() if False: print("test backlight mode") From bc2a0d26b6c16878727719530ba1b444f27b152e Mon Sep 17 00:00:00 2001 From: "Colin-N. Brosseau" Date: Fri, 7 Mar 2014 23:31:46 -0500 Subject: [PATCH 48/48] minor corrections --- lantz/drivers/newport/842PE.py | 13 ++++++++++--- lantz/drivers/newport/test842PE.py | 21 ++++++++++++++++++--- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/lantz/drivers/newport/842PE.py b/lantz/drivers/newport/842PE.py index f1250b8..52ba2b2 100644 --- a/lantz/drivers/newport/842PE.py +++ b/lantz/drivers/newport/842PE.py @@ -50,6 +50,8 @@ class N842PE(SerialDriver): PARITY = 'none' STOPBITS = 1 + TIMEOUT = 10 + #These are the whole scales the controller can reach #No every head can whitstand all of them Scales = ('auto', '1p', '3p', '10p', '30p', '100p', '300p', '1n', @@ -251,10 +253,15 @@ def logging(self, value): #Buggy @Feat() - def get_log(self, value): + def get_log(self): """Retrieve a logged file from the device. (fdl) """ #return self.send_command('*fdl {}'.format(value)) + #return self.send_command('*fdl 0') + self.send('*fdl 0') + time.sleep(1) + return self.recv(termination='chr(26)\n') + warnings.warn('This function does not work!') #Buggy @@ -577,7 +584,7 @@ def clock(self, t): """Set the time and date of the monitor's internal clock. (clk) - t is time.struct_time + t is a time.struct_time """ s = time.strftime('*clk %d %m %Y %I %M %S ', t) pm = '1' if time.strftime('%p', t) == 'PM' else '0' # PM -> 1, AM -> 0 @@ -658,7 +665,7 @@ def reshape_list_dict_in_dict(list_of_dict): default=False, help='Test the device') args = parser.parse_args() - #lantz.log.log_to_screen(lantz.log.DEBUG) + lantz.log.log_to_screen(lantz.log.DEBUG) with N842PE(args.port) as inst: if args.interactive: from lantz.ui.qtwidgets import start_test_app diff --git a/lantz/drivers/newport/test842PE.py b/lantz/drivers/newport/test842PE.py index c0169b2..17686ff 100644 --- a/lantz/drivers/newport/test842PE.py +++ b/lantz/drivers/newport/test842PE.py @@ -39,7 +39,7 @@ def test_instrument(inst): print("Set auto scale") inst.scale = 'auto' - time.sleep(2) + time.sleep(1) print("Instrument status:") inst.print_device_status() @@ -136,7 +136,7 @@ def test_instrument(inst): print(inst.get_statistics) - if True: + if False: print("test logging (setter)") test = ('start raw', 'stop', 'start saving', 'stop', 'save both', 'stop') for i in test: @@ -145,6 +145,19 @@ def test_instrument(inst): time.sleep(1) print("---") + + if True: + print("test get_log") + print("set sampling") + # Set a single data acquisition run for 5 seconds with timestamps at 10 hertz. + sampling_settings = (2, 'Seconds', 1, 'Seconds', 1, 'Period', True) + inst.sampling = sampling_settings + print("start acquisition") + inst.logging = 'save both' + print("wait...") + time.sleep(2) + inst.get_log(0) + # #Buggy # @Feat() # def get_log(inst, value): @@ -231,13 +244,15 @@ def test_instrument(inst): total_duration_unit = choice(['Period', 'Seconds', 'Minutes', 'Hours', 'Days', 'Weeks', 'Continuous', 'Points']) timestamp = choice([False, True]) sampling_settings = (sample_rate, sample_rate_unit, sample_period, sample_period_unit, total_duration, total_duration_unit, timestamp) - #sampling_settings = (90, 'Days', 30, 'Hours', 44, 'Weeks', True) + #sampling_settings = (10, 'Seconds', 10, 'Seconds', 1, 'Period', True) print('SET : RATE: %s %s, PERIOD %s %s, TOTAL DURATION: %s %s, TIMESTAMP %s' % sampling_settings ) inst.sampling = sampling_settings print('GET : : %s %s, %s %s, : %s %s, %s' % inst.sampling) #time.sleep(1) print("---") + + if False: print("test trigger")