def __init__(self, base_directory, config_file, logger=None, simulate=False): self.base_directory=base_directory self.config_file = self.base_directory + '/config/' + config_file # set up the log file if logger == None: self.logger = utils.setup_logger(base_directory + '/log/', 'calstage') else: self.logger = logger # read the config file config = ConfigObj(self.config_file) # read the config file if os.path.exists(self.config_file): config = ConfigObj(self.config_file) else: self.logger.error('Config file not found: (' + self.config_file + ')') sys.exit() self.science_position = float(config['SCIENCEPOS']) self.sky_position = float(config['SKYPOS']) self.out_position = float(config['OUTPOS']) self.sn = config['SNCALSTAGE'] self.model = config['MODEL'] self.sn_controller = config['SNCONTROLLER'] self.model_controller = config['MODELCONTROLLER'] self.minpos = None self.maxpos = None self.simulate = simulate self.simulated_position = 0.0 # use the PI python library to initialize the device if not self.simulate: self.calstage = GCSDevice()
def init_piezo_stage(self): if self.pi_device is None: self.pi_device = GCSDevice("E-710") # Creates a Controller instant self.pi_device.ConnectNIgpib(board=0, device=4) # Connect to GPIB board self.ui.status_textBrowser.append('Connected: {}'.format( self.pi_device.qIDN().strip())) # print('connected: {}'.format(self.pi_device.qIDN().strip())) self.axes = self.pi_device.axes[ 0:2] # selecting x and y axis of the stage self.pi_device.INI() self.pi_device.REF(axes=self.axes) self.pi_device.SVO( axes=self.axes, values=[True, True]) # Turn on servo control for both axes self.ui.status_textBrowser.append( "Current Stage Position:\n{}".format( self.pi_device.qPOS(axes=self.axes))) # print(self.pi_device.qPOS(axes=self.axes)) else: self.ui.status_textBrowser.append( "Piezo Stage Is Already Initialized!")
def __init__(self): CONTROLLERNAME = 'C-863.11' #STAGES = None STAGES = ('M-110.1DG') REFMODE = ('FNL') self.pidevice = GCSDevice() print(self.pidevice.EnumerateUSB()) # InterfaceSetupDlg() is an interactive dialog. There are other methods to # connect to an interface without user interaction. serialstring = self.pidevice.EnumerateUSB() #pidevice.InterfaceSetupDlg(key='sample') # pidevice.ConnectRS232(comport=1, baudrate=115200) self.pidevice.ConnectUSB(serialnum=serialstring[0]) # pidevice.ConnectTCPIP(ipaddress='192.168.178.42') # Each PI controller supports the qIDN() command which returns an # identification string with a trailing line feed character which # we "strip" away. print('connected: {}'.format(self.pidevice.qIDN().strip())) # Show the version info which is helpful for PI support when there # are any issues. if self.pidevice.HasqVER(): print('version info: {}'.format(self.pidevice.qVER().strip()))
def __init__(self, module_params=None, qt_settings=None, **kwds): super().__init__(module_params, qt_settings, **kwds) ## __init__ # @param board The DAQ board to use. # @param line The analog output line to use # @param scale (Optional) Conversion from microns to volts (default is 10.0/250.0) print(f"Serial number: {SERIALNUM}") # Connect to piezo pidevice = GCSDevice(CONTROLLERNAME) pidevice.ConnectUSB(SERIALNUM) print("Connected: {}".format(pidevice.qIDN().strip())) # In the module pipython.pitools there are some helper # functions to make using a PI device more convenient. The "startup" # function will initialize your system. There are controllers that # cannot discover the connected stages hence we set them with the # "stages" argument. The desired referencing method (see controller # user manual) is passed as "refmode" argument. All connected axes # will be stopped if they are moving and their servo will be enabled. # set volaltile reference mode to analog input print("Setting up analog input") pidevice.SPA('Z', 0x06000500, 2) self.pidevice = pidevice # Connect to the piezo. self.good = 1
def open_instr(self): from pipython import GCSDevice, pitools, GCSError self.pitools = pitools self.pi_device = GCSDevice( self.PI_CONTROLLERNAME) # Load PI Python Libraries try: if self.PI_conn_meth == 'usb': self.pi_device.ConnectUSB( self.PIezo_USB_ID) # Connect to the controller via USB else: self.pi_device.ConnectRS232( comport=self.PI_comport, baudrate=self.PI_baud ) # # the timeout is very long, 30 sec !! except Exception as err: if ( type(err) == GCSError and err.val == -9 ): # # 'There is no interface or DLL handle with the given ID (-9)' print('No PI device !!') else: print('PI device lead to UNKNOWN error!!') self.PI_is_here = False else: self.PI_is_here = True print('PI device here.') self.pi_device.SVO( self.pi_device.axes, self.PI_SERVOMODE ) # 1 = servo on (closed-loop operation) ; 0 = open-loop (servo OFF) # # open loop resolution (0.4nm) is a lower value than the closed loop resolution (0.7nm) due to the noise of the sensor signal. Open loop is subject to hysteresis, meaning the position could be off by up to 15%. When operated in closed loop, the hysteresis is compensated for, and virtually eliminated. self.getpos_motor_PI() self.PI_ishere_signal.emit(self.PI_is_here)
def connect(self): # Open connection to the device: self.pi_device = GCSDevice("E-710") # Creates a Controller instant self.pi_device.ConnectNIgpib(board=0, device=4) # Connect to GPIB board self.axes = self.pi_device.axes[ 0:2] # selecting x and y axis of the stage self.pi_device.INI() self.pi_device.REF(axes=self.axes) self.pi_device.SVO(axes=self.axes, values=[True, True ]) # Turn on servo control for both axes #Connect settings to hardware: LQ = self.settings.as_dict() LQ["x_position"].hardware_read_func = self.getX LQ["y_position"].hardware_read_func = self.getY LQ["x_position"].hardware_set_func = self.abs_mov LQ["y_position"].hardware_set_func = self.abs_mov LQ["x_position"].hardware_set_func = self.rel_mov LQ["y_position"].hardware_set_func = self.rel_mov #Take an initial sample of the data. self.read_from_hardware()
def on_activate(self): """Initialisation performed during activation of the module.""" self._galvo = self.galvo() self._piezo = GCSDevice(devname=self._piezoModel, gcsdll=self._piezoDllPath) self._piezo.ConnectUSB(self._piezoSerial) self._piezo_axis = self._piezo.axes[0]
def __init__(self, serialnum1='0109029920', serialnum2='0109029922' ): # should become a parameter, see other stages print(serialnum1, serialnum2, sep='\n') pidevice1 = GCSDevice(CONTROLLERNAME) pidevice1.ConnectUSB(serialnum1)
def __init__(self): """ Provide a device, connected via the PI GCS DLL. def pipython.gcsdevice.GCSDevice.__init__ ( self, devname = '', gcsdll = '') Parameters devname : Name of device, chooses according DLL which defaults to PI_GCS2_DLL. gcsdll : Name or path to GCS DLL to use, overwrites 'devname'. Returns ------- None. """ try: CONTROLLERNAME = 'C-863.11' #STAGES = None STAGES = ('M-110.1DG') REFMODE = ('FNL') # Get the path to dll in the same folder. abspath = os.path.abspath(__file__) dname = os.path.dirname(abspath) + '/PI_GCS2_DLL_x64.dll' print(dname) self.pidevice = GCSDevice(gcsdll=dname) print(self.pidevice.EnumerateUSB()) # InterfaceSetupDlg() is an interactive dialog. There are other methods to # connect to an interface without user interaction. serialstring = self.pidevice.EnumerateUSB() print(serialstring[0]) #pidevice.InterfaceSetupDlg(key='sample') # pidevice.ConnectRS232(comport=1, baudrate=115200) self.pidevice.ConnectUSB( serialnum='PI C-863 Mercury SN 0185500828') # pidevice.ConnectTCPIP(ipaddress='192.168.178.42') # Each PI controller supports the qIDN() command which returns an # identification string with a trailing line feed character which # we "strip" away. print('connected: {}'.format(self.pidevice.qIDN().strip())) # Show the version info which is helpful for PI support when there # are any issues. if self.pidevice.HasqVER(): print('version info: {}'.format(self.pidevice.qVER().strip())) # allaxes = self.pidevice.qSAI_ALL() # return self.pidevice except: print("PI device not initilized.")
def config_pi(self): CONTROLLERNAME = 'C-863.11' # 'C-863' will also work STAGES = ['M-111.1VG'] REFMODES = ['FNL', 'FRF'] self.pi = GCSDevice(CONTROLLERNAME) self.pi.ConnectUSB(serialnum='0165500259') pitools.startup(self.pi, stages=STAGES, refmodes=REFMODES) self.pi.VEL(1, self.velocity) self.pi.MOV(1, self.pos_max) pitools.waitontarget(self.pi, axes=1)
def __init__(self, objective_motor_handle=None): # Connect the objective motor if it is not given if objective_motor_handle == None: self.objective = GCSDevice( gcsdll=__file__ + '/../../' + '/PI_ObjectiveMotor/PI_GCS2_DLL_x64.dll') self.objective.ConnectUSB( serialnum='PI C-863 Mercury SN 0185500828') else: self.objective = objective_motor_handle
def connect(self): S = self.settings import os #dll_path = os.path.normpath(sibling_path(__file__, "PI_GCS2_DLL_x64.dll")) #print(dll_path) self.gcs = GCSDevice()#gcsdll=dll_path) time.sleep(0.1) if S['port'].startswith('USB:'): ser_num = S['port'].split(':')[-1] #print(ser_num) self.gcs.ConnectUSB(ser_num) print(self.gcs.qIDN()) else: raise ValueError("Port of undefined type {}".format(S['port'])) for ax_num, ax_name in self.axes.items(): lq = S.get_lq(ax_name + "_position") lq.connect_to_hardware( read_func = lambda n=ax_num: self.gcs.qPOS()[str(n)] ) lq.read_from_hardware() lq = S.get_lq(ax_name + "_target") lq.connect_to_hardware( read_func = lambda n=ax_num: self.gcs.qMOV()[str(n)], write_func = lambda new_target, n=ax_num: self.gcs.MOV(n, new_target) ) lq.read_from_hardware() lq = S.get_lq(ax_name + "_servo") lq.connect_to_hardware( read_func = lambda n=ax_num: self.gcs.qSVO()[str(n)], write_func = lambda enable, n=ax_num: self.gcs.SVO(n, enable ) ) lq.read_from_hardware() lq = S.get_lq(ax_name + "_on_target") lq.connect_to_hardware( read_func = lambda n=ax_num: self.gcs.qONT()[str(n)], ) lq.read_from_hardware() lq = S.get_lq(ax_name + "_velocity") lq.connect_to_hardware( read_func = lambda n=ax_num: self.gcs.qVEL()[str(n)], write_func = lambda new_vel, n=ax_num: self.gcs.VEL(n, new_vel ) ) lq.read_from_hardware() self.update_thread_interrupted = False self.update_thread = threading.Thread(target=self.update_thread_run) self.update_thread.start()
def __init__(self, t0): self.t0 = t0 self.stage = GCSDevice('E-873') self.stage.ConnectUSB(serialnum=119040925) self.axis = '1' self.timeout = 5000 self.pos_max = 13.0 self.pos_min = -13.0 self.set_max_min_times() self.stage.VEL(self.axis, 3.0) # set the velocity to some low value to avoid crashes! pitools.startup(self.stage)
def __init__(self, t0): self.t0 = t0 self.stage = GCSDevice('HYDRA') # alternatively self.stage = GCSDevice(gcsdll='PI_HydraPollux_GCS2_DLL_x64.dll') for a fail safe option self.stage.ConnectTCPIP(ipaddress='192.168.0.2', ipport=400) self.axis = '1' self.timeout = 5000 self.pos_max = 610.0 self.pos_min = 0.0 self.set_max_min_times() self.stage.VEL(self.axis, 30.0) # set the velocity to some low value to avoid crashes! pitools.startup(self.stage)
def initialize(self): """ | The external core.Motor object is already initialized by executing super().__init__(self.serial). | So this function is just so that higher layers dont give errors. """ pidevice = GCSDevice('C-863.10') pidevice.InterfaceSetupDlg(key='sample') print('connected: {}'.format(pidevice.qIDN().strip())) print('initialize connected stages...') pitools.startup(pidevice, stages=self.STAGES, refmode=self.REFMODE) return pidevice self.logger.info('initialized PI motorcontroller')
def Dialog_connect(M_read): print("Dialog") gcs = GCSDevice(M_read[0]) if len(M_read) == 1: gcs.InterfaceSetupDlg() else: gcs.InterfaceSetupDlg(M_read[1]) messagebox.showinfo(message='Device: {}\n connected'.format( gcs.qIDN().strip()), title='Connection Succesfull') self.Devices_connected[M_read[0]] = gcs
def __init__(self, base_directory, config_file, logger=None, simulate=False): self.base_directory = base_directory self.config_file = self.base_directory + '/config/' + config_file self.simulate = simulate # set up the log file if logger == None: self.logger = utils.setup_logger(base_directory + '/log/', 'calstage') else: self.logger = logger # read the config file if os.path.exists(self.config_file): config = ConfigObj(self.config_file) else: self.logger.error('Config file not found: (' + self.config_file + ')') sys.exit() # serial number of the TIP/TILT stage and controller self.sn = config['SN_TIPTILT'] self.model = config['MODEL_TIPTILT'] self.sn_controller = config['SN_CONTROLLER'] self.model_controller = config['MODEL_CONTROLLER'] # stage steps per arcsecond on the sky self.steps_per_arcsec = float(config['STEPS_PER_ARCSEC']) # angle between North and axis A, in radians self.theta = float(config['THETA']) * math.pi / 180.0 # if there's a flip in the mapping, apply it if config['FLIP']: self.sign = -1.0 else: self.sign = 1.0 # use the PI python library to initialize the device if not self.simulate: self.tiptilt = GCSDevice() # range of motion self.mintip = None self.maxtip = None self.mintilt = None self.maxtilt = None self.position = {'A': None, 'B': None}
def connectPIMachine(name, mode, **kwargs): """ 连接PI设备具有三种方式 :param name: 控制器的名称 :param mode: 连接的模式,可以为RS232,USB,TCPIP :param kwargs: 对应连接模式下具体的参数 :return: 返回目标设备对象 """ dllname = 'PI_GCS2_DLL' if architecture()[0] == '64bit': dllname += '_x64' dllname += '.dll' if dllname in os.listdir(os.getcwd()): pidevice = GCSDevice(name, os.path.join(os.getcwd(), dllname)) else: pidevice = GCSDevice(name) if mode == 'RS232': pidevice.ConnectRS232(comport=kwargs['comport'], baudrate=kwargs['baudrate']) elif mode == 'USB': pidevice.ConnectUSB(serialnum=kwargs['serialnum']) elif mode == 'TCPIP': pidevice.ConnectTCPIP(ipaddress=kwargs['ipaddress']) else: print( dedent(''' specify a mode "RS232", "USB", "TCPIP" # pidevice.ConnectRS232(comport=1, baudrate=115200) # pidevice.ConnectUSB(serialnum='123456789') # pidevice.ConnectTCPIP(ipaddress='192.168.178.42') ''')) return print('connected: {}'.format(pidevice.qIDN().strip())) return pidevice
def ini_device(self): """ load the correct dll given the chosen device See Also -------- DAQ_Move_base.close """ try: self.close() except: pass device = self.settings.child(('devices')).value() if self.settings.child( ('connect_type')).value() == 'TCP/IP' or self.settings.child( ('connect_type')).value() == 'RS232': dll_path_tot = self.settings.child(('gcs_lib')).value() else: # device = self.settings.child(('devices')).value().rsplit(' ') # dll = None # flag = False # for dll_tmp in DLLDEVICES: # for dev in DLLDEVICES[dll_tmp]: # for d in device: # if (d in dev or dev in d) and d != '': # res=self.check_dll_exist(dll_tmp) # if res[0]: # dll = res[1] # flag = True # break # if flag: # break # if flag: # break # # if dll is None: # raise Exception('No valid dll found for the given device') # dll_path = os.path.split(self.settings.child(('gcs_lib')).value())[0] # dll_path_tot = os.path.join(dll_path,dll) #dll_name = get_dll_name(self.settings.child(('devices')).value()) #dll_path_tot = get_dll_path(dll_name) #self.settings.child(('gcs_lib')).setValue(dll_path_tot) dll_path_tot = self.settings.child(('gcs_lib')).value() self.controller = GCSDevice(gcsdll=dll_path_tot) self.enumerate_devices()
def main(): """Connect three controllers on a daisy chain.""" with GCSDevice('C-863.11') as c863: c863.OpenRS232DaisyChain(comport=1, baudrate=115200) # c863.OpenUSBDaisyChain(description='1234567890') # c863.OpenTCPIPDaisyChain(ipaddress='192.168.178.42') daisychainid = c863.dcid c863.ConnectDaisyChainDevice(3, daisychainid) with GCSDevice('E-861') as e861: e861.ConnectDaisyChainDevice(7, daisychainid) with GCSDevice('C-867') as c867: c867.ConnectDaisyChainDevice(1, daisychainid) print('\n{}:\n{}'.format(c863.GetInterfaceDescription(), c863.qIDN())) print('\n{}:\n{}'.format(e861.GetInterfaceDescription(), e861.qIDN())) print('\n{}:\n{}'.format(c867.GetInterfaceDescription(), c867.qIDN()))
def on_activate(self): """ Initialise and activate the hardware module. @return: error code (0:OK, -1:error) """ try: self.pidevice = GCSDevice(self._controllername) self.pidevice.ConnectTCPIP(self._ipaddress, self._ipport) device_name = self.pidevice.qIDN().strip() self.log.info('PI controller {} connected'.format(device_name)) pitools.startup(self.pidevice, stages=self._stages) return 0 except GCSError as error: self.log.error(error) return -1
def connectStage(self): gcs = GCSDevice() try: gcs.InterfaceSetupDlg() msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setText(gcs.qIDN()) msg.exec_() self.stage = gcs self.openStageBtn.setEnabled(False) except: msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText('Could not connect stage') msg.exec_()
def main(): """Connect to a PIPython device.""" # We recommend to use GCSDevice as context manager with "with". with GCSDevice() as pidevice: # Choose the interface which is appropriate to your cabling. pidevice.ConnectTCPIP(ipaddress='192.168.178.42') # pidevice.ConnectUSB(serialnum='123456789') # pidevice.ConnectRS232(comport=1, baudrate=115200) # Each PI controller supports the qIDN() command which returns an # identification string with a trailing line feed character which # we "strip" away. print('connected: {}'.format(pidevice.qIDN().strip())) # Show the version info which is helpful for PI support when there # are any issues. if pidevice.HasqVER(): print('version info: {}'.format(pidevice.qVER().strip())) print('done - you may now continue with the simplemove.py example...')
def connectStage(self): gcs = GCSDevice( gcsdll="C:/Software/PI C863/PI_GCS2_DLL/PI_GCS2_DLL_x64.dll") try: gcs.InterfaceSetupDlg() msg = QMessageBox() msg.setIcon(QMessageBox.Information) msg.setText(gcs.qIDN()) msg.exec_() self.stage = gcs self.openStageBtn.setEnabled(False) except: msg = QMessageBox() msg.setIcon(QMessageBox.Critical) msg.setText('Could not connect stage') msg.exec_()
def two_items_one_value(): """Sample for a command that answers with two items (e.g. axis and option) and one value.""" with GCSDevice() as pidevice: answer = pidevice.ReadGCSCommand('FOO? 1 2 1 4 2 6') # This will return: # 1 2 = 1.23 # 1 4 = 2.00 # 2 6 = 3.45 # There is a helper function to get a dict of this answer. gcscommands.getdict_twoitems(answer, items1=None, items2=None, itemconv=[], valueconv=[]) # Answer: {'1': {'2': '1.23', '4': '2.00'}, '2': {'6': '3.45'}} # Remember, all keys and values are strings because the function # does not now how to convert. gcscommands.getdict_twoitems(answer, items1=None, items2=None, itemconv=[int, str], valueconv=(float, ))
def one_item_one_value(): """Sample for a command that answers with one item (e.g. axis) and one value.""" with GCSDevice() as pidevice: answer = pidevice.ReadGCSCommand('FOO? 1 2 3') # This will return: # 1 = 1.23 # 2 = 2.00 # 3 = 3.45 # There is a helper function to get a dict of this answer. gcscommands.getdict_oneitem(answer, items=None) # Answer: {'1': '1.23', '2': '2.00', '3': '3.45'} # Remember, all keys and values are strings because the function # does not now how to convert. gcscommands.getdict_oneitem(answer, items=None, itemconv=int) # Answer: {1: '1.23', 2: '2.00', 3: '3.45'} # Now the keys are int. gcscommands.getdict_oneitem(answer, items=None, itemconv=int, valueconv=(float, )) # Answer: {1: 1.23, 2: 2.0, 3: 3.45} # Now the keys are int and the values are float. # Remember the 'valueconv' argument must be a list or a tuple! gcscommands.getdict_oneitem(answer, items=None, itemconv=int, valueconv=(True, ))
class PIMotor: """ Physik Intrumente Objective motor control The objective is attached to a motor that can move it up and down. This file is a minimalistic version of xinmeng's 'focuser.py' but contains the exact same functionality. """ def __init__(self, objective_motor_handle=None): # Connect the objective motor if it is not given if objective_motor_handle == None: self.objective = GCSDevice( gcsdll=__file__ + '/../../' + '/PI_ObjectiveMotor/PI_GCS2_DLL_x64.dll') self.objective.ConnectUSB( serialnum='PI C-863 Mercury SN 0185500828') else: self.objective = objective_motor_handle def disconnect(self): """ Disconnects the objective motor, initialization necessary to use it again. """ self.objective.CloseConnection() def moveAbs(self, z): """ Moves the objective motor to a target position, 'z' is the position on the z-axis in millimeters. Example: z = 3.45 moves the objective 3.45 millimeters above zero. """ self.objective.MOV(self.objective.axes, z) pitools.waitontarget(self.objective) # below this line is not really necessary positions = self.objective.qPOS(self.objective.axes) for axis in self.objective.axes: print('position of axis {} = {:.5f}'.format(axis, positions[axis])) def getPos(self): """ Reports the position of the objective motor in units of 10 micron. Example: position = 3.45 means the motor position is 3.45 millimeters from 0 """ positions = self.objective.qPOS(self.objective.axes) return positions['1']
def main(): """Connect controller, setup stages and move all axes to targets read from CSV file 'DATAFILE'.""" with GCSDevice(CONTROLLERNAME) as pidevice: pidevice.InterfaceSetupDlg(key='sample') print('connected: {}'.format(pidevice.qIDN().strip())) print('initialize connected stages...') pitools.startup(pidevice, stages=STAGES, refmode=REFMODE) movetotargets(pidevice)
def main(): """Connect controller, setup stages and start wave generator.""" with GCSDevice(CONTROLLERNAME) as pidevice: pidevice.InterfaceSetupDlg(key='sample') print('connected: {}'.format(pidevice.qIDN().strip())) print('initialize connected stages...') pitools.startup(pidevice, stages=STAGES, refmode=REFMODE) runwavegen(pidevice)
def __init__(self, controller_name='C-863.11', stage_name='L-511', ref_mode='FNL', spindle_pitch_microns=2000, steps_per_revolution=20000): QObject.__init__(self) self.axis_orientation = 1 self.controller_name = controller_name self.stage_name = stage_name self.ref_mode = ref_mode self.gcs = GCSDevice(self.controller_name) self.projector_locked = True self.spindle_pitch_microns = spindle_pitch_microns # mm self.steps_per_revolution = steps_per_revolution self.step_length_microns = self.spindle_pitch_microns / self.steps_per_revolution # microns self.is_connected = False