Пример #1
0
def _dnCntrTest():
	epics.caput(prefix+"SG:sseq1.PROC","0", wait=True, timeout=1000000.0)
	time.sleep(1.5)
	divBy = []
	divBy.append(epics.caget(prefix+"SG:DnCntr-1_PRESET"))
	divBy.append(epics.caget(prefix+"SG:DnCntr-2_PRESET"))
	divBy.append(epics.caget(prefix+"SG:DnCntr-3_PRESET"))
	divBy.append(epics.caget(prefix+"SG:DnCntr-4_PRESET"))
	cnt = []
	cnt.append(epics.caget(prefix+"SG:UpCntr-1_COUNTS"))
	cnt.append(epics.caget(prefix+"SG:UpCntr-2_COUNTS"))
	cnt.append(epics.caget(prefix+"SG:UpCntr-3_COUNTS"))
	cnt.append(epics.caget(prefix+"SG:UpCntr-4_COUNTS"))
	cntClock = epics.caget(prefix+"SG:UpDnCntr-1_COUNTS")

	success = True
	diff = -1
	for i in range(4):
		d = abs(cntClock/divBy[i] - cnt[i])
		if d > 1:
			success = 0
			if d > diff:
				diff = d

	if success:
		print "dnCntrTest: Passed"
	else:
		print "dnCntrTest: Failed: max diff=", diff
		print "cntClock=", cntClock, "cnt=", cnt, "divBy=", divBy
	return success
Пример #2
0
    def run(self):
        ''' Process itself '''
        #--- Save pvValues
        for entry in self.options.oscillatePvs:
            pvName, amplitude, action = entry.split(',')
            oscillatePv = _OscillatePv(pvName, float(amplitude), action)
            if self.options.verbose : 
               timestamp = time.asctime(time.localtime())
               print "[%s] [0/0] %s -> %f" % (timestamp, oscillatePv.pvName, oscillatePv.valueAtInit)

            self._oscillatePvs.append(oscillatePv)
        #--- Go!
        for periodNumber in range(self.options.numberOfPeriods):
            for stepNumber in range(1,self.options.stepsPerPeriod+1):
                for oscillatePv in self._oscillatePvs:
                    if oscillatePv.action == 'Sine':
                        inc = oscillatePv.amplitude*math.sin(2*math.pi*stepNumber/self.options.stepsPerPeriod)
                        pvValNew = oscillatePv.valueAtInit + inc
                    elif oscillatePv.action == 'Ramp':
                        inc = oscillatePv.amplitude * (stepNumber-1) / (self.options.stepsPerPeriod-1)
                        pvValNew = oscillatePv.valueAtInit + inc 
                    else:
                        raise Exception('Invalid action')
                    #--- Write
                    if self.options.dryRun or self.options.verbose : 
                        timestamp = time.asctime(time.localtime())
                        print "[%s] [%d/%d] %s -> %f" % (timestamp,periodNumber,stepNumber,pvName,pvValNew)
                    if not self.options.dryRun :
                        epics.caput(pvName,pvValNew,wait=WAIT,timeout=TIMEOUT)
                sec = self.options.periodDuration/self.options.stepsPerPeriod
                time.sleep(sec)
        #--- Restore
        self.restoreInitValues()
Пример #3
0
def _UpDnCntrTest():
	epics.caput("zzz:SG:sseq1.PROC","0", wait=True, timeout=1000000.0)
	time.sleep(1.5)
	divBy = []
	divBy.append(epics.caget("zzz:SG:UpDnCntr-1_PRESET"))
	divBy.append(epics.caget("zzz:SG:UpDnCntr-2_PRESET"))
	divBy.append(epics.caget("zzz:SG:UpDnCntr-3_PRESET"))
	divBy.append(epics.caget("zzz:SG:UpDnCntr-4_PRESET"))
	cnt = []
	cnt.append(epics.caget("zzz:SG:UpCntr-1_COUNTS"))
	cnt.append(epics.caget("zzz:SG:UpCntr-2_COUNTS"))
	cnt.append(epics.caget("zzz:SG:UpCntr-3_COUNTS"))
	cnt.append(epics.caget("zzz:SG:UpCntr-4_COUNTS"))
	#cntClock = epics.caget("zzz:SG:DnCntr-1_COUNTS")  # doesn't exist yet
	cts = epics.caget("zzz:reg1_RB8")
	preset = epics.caget("zzz:SG:DnCntr-1_PRESET")
	cntClock = preset - cts
	success = True
	diff = -1
	for i in range(4):
		d = abs(cntClock/divBy[i] - cnt[i])
		if d > 1:
			success = 0
			if d > diff:
				diff = d

	if success:
		print "UpDnCntrTest: Passed"
	else:
		print "UpDnCntrTest: Failed: max diff=", diff
		#print "cntClock=", cntClock, "cnt=", cnt, "divBy=", divBy
	return success
Пример #4
0
def test(motor_record='XF:31IDA-OP{Tbl-Ax:X1}Mtr'):
    config.setup_logging([__name__, 'pypvserver.motor'])
    server = config.get_server()
    mrec = EpicsMotor(motor_record)

    # give the motor time to connect
    time.sleep(1.0)

    logger.info('--> PV Positioner, using put completion and a DONE pv')
    # PV positioner, put completion, done pv
    pos = PVPositioner(mrec.field_pv('VAL'),
                       readback=mrec.field_pv('RBV'),
                       done=mrec.field_pv('MOVN'), done_val=0,
                       stop=mrec.field_pv('STOP'), stop_val=1,
                       put_complete=True,
                       limits=(-2, 2),
                       )

    ppv_motor = PypvMotor('m1', pos, server=server)
    print(ppv_motor.severity)
    record_name = ppv_motor.full_pvname
    for i in range(2):
        epics.caput(record_name, i, wait=True)
        print(pos.position)
    return ppv_motor
Пример #5
0
    def us_calculations_changed(self):
        if self.model.us_calibration_filename is not None:
            self.widget.us_calibration_filename_lbl.setText(os.path.basename(self.model.us_calibration_filename))
        else:
            self.widget.us_calibration_filename_lbl.setText('Select File...')

        self.widget.us_etalon_filename_lbl.setText(os.path.basename(self.model.us_etalon_filename))
        self.widget.us_etalon_rb.setChecked(self.model.us_temperature_model.calibration_parameter.modus)
        self.widget.us_temperature_txt.setText(str(self.model.us_temperature_model.calibration_parameter.temperature))

        if len(self.model.us_corrected_spectrum):
            us_plot_spectrum = self.model.us_corrected_spectrum
        else:
            us_plot_spectrum = self.model.us_data_spectrum

        self.widget.graph_widget.plot_us_data(*us_plot_spectrum.data)
        self.widget.graph_widget.plot_us_fit(*self.model.us_fit_spectrum.data)
        self.widget.graph_widget.update_us_temperature_txt(self.model.us_temperature,
                                                           self.model.us_temperature_error)
        self.widget.graph_widget.update_us_roi_max_txt(self.model.us_temperature_model.data_roi_max)

        if self.widget.connect_to_epics_cb.isChecked():
            if epics is not None:
                epics.caput("13IDD:us_las_temp", self.model.us_temperature)
                epics.caput("13IDD:up_t_int", str(self.model.us_roi_max))
Пример #6
0
def no_simulator_updates():
    '''Context manager which pauses and resumes simulator PV updating'''
    try:
        caput(pvnames.pause_pv, 1)
        yield
    finally:
        caput(pvnames.pause_pv, 0)
Пример #7
0
def SelectNFDetector():             # NFDet_select
    '''
    NFDet_select
    '''
    SignalsInput_1ide()
    ep.caput('1ide:sg:FO24_Signal','NFExp',wait=True) # RetExp signal to 1id
    return
Пример #8
0
def SignalsInput_1ide():            # _signals_input_1ide
    '''
    _signals_input_1ide
    '''
    ep.caput('1ide:sg:FI15_Signal','NFExp',wait=True)
    ep.caput('1ide:sg:FI16_Signal','TomoExp',wait=True)
    return
Пример #9
0
def find_max_intensity(readpv, drivepv, vals, minval=0.1):
    """find a max in an intensity while sweeping through an
    array of drive values,  around a current position, and
    move to the position with max intensity.

    Parameters
    ----------
    readpv:   PV for reading intensity
    drivepv:  PV for driving positions
    vals:     array of RELATIVE positions (from current value)
    minval:   minimum acceptable intensity [defualt = 0.1]

    Notes:
    -------
     1. PRIVATE method, not exposed in user-macros
     2. if the best intensity is below minval, the position is
        moved back to the original position.
     
    """
    _orig = _best = caget(drivepv)
    i0max = caget(readpv)
    for val in _orig+vals:
        caput(drivepv, val)
        sleep(0.1)
        i0 = caget(readpv)
        if i0 > i0max:
            i0max, _best = i0, val
        #endif
    #endfor
    if i0max < minval: _best = _orig
    caput(drivepv, _best)
    return i0max, _best
Пример #10
0
def FS_SweepControl():              # FS_Sweep_control
    '''
    FS_Sweep_control
    '''
    SignalsInput_1id()
    ep.caput('1id:softGlue:FO24_Signal','Sweep',wait=True) # to fast shutter
    return
Пример #11
0
    def save_image(self, fname=None):
        "save image to file"
        self.waiting_for_imagefile = True
        if self.cam_type.lower().startswith('web'):
            try:
                img = urlopen(self.cam_weburl).read()
            except:
                self.write_message('could not open camera: %s' % self.cam_weburl)
                return 

            if fname is None:
                fname = FileSave(self, 'Save Image File',
                                 wildcard='JPEG (*.jpg)|*.jpg|All files (*.*)|*.*',
                                 default_file='sample.jpg')
            if img is not None and fname is not None:
                out = open(fname,"wb")
                out.write(img)
                out.close()
                self.write_message('saved image to %s' % fname)
        else: # areaDetector
            cname = "%s%s1:"% (self.cam_adpref, self.cam_adform.upper())
            caput("%sFileName" % cname, fname)
            time.sleep(0.001)
            caput("%sWriteFile" % cname, 1)
            self.write_message('saved image to %s' % fname)
            time.sleep(0.50)
        self.waiting_for_imagefile = False
        return fname
Пример #12
0
 def rename_roi(self, i, newname):
     roi = self._xmap.mcas[0].rois[i]
     roi.NM = newname
     rootname = roi._prefix
     for imca in range(1, len(self._xmap.mcas)):
         pvname = rootname.replace('mca1', 'mca%i'  % (1+imca))
         epics.caput(pvname+'NM', newname)
Пример #13
0
def test1(i):
	e = expressions[i]
	epics.caput(calc,e[0], wait=True)
	#time.sleep(5)
	rtry = epics.caget(result)
	atry = epics.caget(aresult)
	if (e[1]):
		r = eval(e[1])
		print "\n", e[0], "-->", e[1]
	else:
		r = eval(e[0])
		print "\n", e[0]
	if ((type(r) == type(1.0)) or (type(r) == type(1))):
		if (abs(r - rtry) < small):
			print "OK\t", "rtry=",rtry, ", r=",r
			return(0)
		else:
			print "ERROR\t", "rtry=",rtry, ", atry=",atry, ", r=",r
			return(1)
	elif (type(r) == type(True)):
		if ((abs(rtry) < small) == (r == False)):
			print "OK\t", "rtry=",rtry, ", r=",r
			return(0)
		else:
			print "ERROR\t", "rtry=",rtry, ", atry=",atry, ", r=",r
			return(1)
	else:
		print "ERROR\t", "rtry=",rtry, ", atry=",atry, ", r=",r
		return(1)
Пример #14
0
def collect_wide_data(detector_position_x, detector_position_z, omega_start, omega_end, exposure_time, x, y, z):
    # performs the actual wide measurement

    # prepare the stage:
    prepare_stage(detector_position_x, detector_position_z, omega_start, x, y, z)

    # prepare the detector
    previous_shutter_mode = prepare_detector()
    detector_checker = MarCCDChecker(epics_config['detector_control'])

    # start data collection
    # perform_background_collection()
    collect_data(exposure_time + 50)

    # start trajectory scan
    omega_range = omega_end - omega_start
    print omega_range
    run_omega_trajectory(omega_range, exposure_time)

    # stop detector and wait for the detector readout
    time.sleep(0.1)
    caput(epics_config['detector_control'] + ':Acquire', 0)
    caput(epics_config['detector_control'] + ':ShutterMode', previous_shutter_mode, wait=True)
    while not detector_checker.is_finished():
        time.sleep(0.01)
    logger.info('Wide data collection finished.\n')
    return
Пример #15
0
    def move(self, motor, position, timeout):
        """
        Move motor to position. We use put_callback
        and check final position is within RDBD.
        """
    
        try:
            caput(motor, position, wait=True, timeout=timeout)
        except:
            e = sys.exc_info()
            print str(e)
            print "ERROR: caput failed."
            print (motor + " pos:" + str(position) + " timeout:" + str(timeout))
            return self.__g.FAIL
        
        rdbd = motor + ".RDBD"
        rbv = motor + ".RBV"

        final_pos = caget(rbv)
        deadband = caget(rdbd)

        success = True

        if ((final_pos < position-deadband) or (final_pos > position+deadband)):
            print "ERROR: final_pos out of deadband."
            print (motor + " " + str(position) + " " + str(timeout) + " " 
                   + str(final_pos) + " " + str(deadband))
            success = False

        if (success):
            return self.postMoveCheck(motor)
        else:
            self.postMoveCheck(motor)
            return self.__g.FAIL
Пример #16
0
    def set_lfo(self, freq):
        """set the low frequency output"""
#        self.sig_gen_socket.write(':LFO:FREQ ' + str(freq))
        epics.caput(self.sig_gen_idn + "",)
#        self.sig_gen_socket.write(':LFO:FREQ:MODE FIXED')
#        self.sig_gen_socket.write(':LFO:STAT ON')
        return
Пример #17
0
	def start_ioc_Event(self, event):
		
		# Put the terminal command into a tuple (start_ioc, detector)
		
		if not(self.processes['IOC']['running']):
			
			#Have the psthread wait
			startIOC=threading.Condition()
			startIOC.acquire()
			# Start the subprocess
			subprocess.Popen(['/local/DPbin/Scripts/start_ioc', detector],  preexec_fn=os.setsid)
			# Grab the subprocess I.D.
			self.processes['IOC']['pid'] = DPOStools.waitforprocess(binary)
			self.processes['IOC']['running']=True
		
			print "\nOpening IOC..."
		
			# Set the Button Colour
			self.ioc_alive() 
			startIOC.release()
			self.SetWindowStyleFlag(wx.STAY_ON_TOP)
			self.SetWindowStyle(not(wx.STAY_ON_TOP))
			
			# Initialize camera in pvCam IOC
			epics.caput((pv_Prefix + ':cam1:Initialize'),1)
			
		else:
			print "\nIOC already running!"
def moveUserPosition(motor, tc_no, destination, velocity, acceleration):
    time_to_wait = 30
    if velocity > 0:
        distance = math.fabs(epics.caget(motor + '.RBV', use_monitor=False) - destination)
        time_to_wait += distance / velocity + 2 * acceleration
    epics.caput(motor + '.VAL', destination)
    done = waitForStartAndDone(motor, tc_no, time_to_wait)
Пример #19
0
def test():
    loggers = ('ophyd.controls.cas',
               )

    config.setup_loggers(loggers)

    logger = config.logger
    session = config.session
    server = session.cas

    motor_record = config.motor_recs[0]
    mrec = EpicsMotor(motor_record)

    logger.info('--> PV Positioner, using put completion and a DONE pv')
    # PV positioner, put completion, done pv
    pos = PVPositioner(mrec.field_pv('VAL'),
                       readback=mrec.field_pv('RBV'),
                       done=mrec.field_pv('MOVN'), done_val=0,
                       stop=mrec.field_pv('STOP'), stop_val=1,
                       put_complete=True,
                       limits=(-2, 2),
                       egu='unknown',
                       )

    def updated(value=None, **kwargs):
        print('Updated to: %s' % value)

    cas_motor = CasMotor('m1', pos, server=server)
    print(cas_motor.severity)
    record_name = cas_motor.full_pvname
    for i in range(2):
        epics.caput(record_name, i, wait=True)
        print(pos.position)
    return cas_motor
Пример #20
0
 def update_time_remaining(self, **kwargs):
     try:
         if self.stepfly == 'step':
             dwell = epics.caget('2xfm:userTran1.P', timeout=0.1)
             n_pts = self.scan1.NPTS
             n_lines = self.scan2.NPTS
             c_line = self.scan2.CPT
             oh = cfg.time_estimate_overhead['step']
         elif self.stepfly == 'fly':
             dwell = epics.caget('2xfm:FlySetup:DwellTime.VAL', timeout=0.1)*1e-3
             n_pts = self.FscanH.NPTS
             n_lines = self.Fscan1.NPTS
             c_line = self.Fscan1.CPT
             oh = cfg.time_estimate_overhead['fly']
         if c_line>n_lines:
             c_line = n_lines
         time_per_line = oh[0]+dwell*n_pts*oh[1]
         time_per_image = oh[2]+time_per_line*(n_lines-c_line)*oh[3]
         epics.caput(self.soft_prefix+'hr_remaining.VAL', np.floor(time_per_image/3600.0), timeout=0.1)
         epics.caput(self.soft_prefix+'min_remaining.VAL', np.mod(time_per_image, 3600.0)/60.0, timeout=0.1)
     except TypeError:
         # Probably a caget timed out
         pass
     except AttributeError:
         raise
Пример #21
0
 def on_runsinglepoint(self, positionStruct, name = ''):
     result = 0
     for index,positioner in enumerate(positionStruct['positioner']):
         result += caput(positioner, positionStruct['position'][index], wait = True)
     if (name != ''):
         result += caput(filenamePV, name)
     result += caput(triggerPV, 1)
Пример #22
0
def set_lm(positioner, limits):
    """Set the positioner limits

    Note : Currently this only works for EpicsMotor instances
    :param positioner: A single positioner or a collection of
                       positioners to move
    :param limits: A single tupple or a collection of tuples for
                       the form (+ve, -ve) limits.

    """

    print('')

    for p in positioner:
        if not isinstance(p, EpicsMotor):
            raise ValueError("Positioners must be EpicsMotors to set limits")

    for p, lim in zip(positioner, limits):
        lim1 = max(lim)
        lim2 = min(lim)
        if not caput(p._record + ".HLM", lim1):
            # Fixme : Add custom exception class
            raise Exception("Unable to set limits for %s", p.name)
        msg = "Upper limit set to {:{fmt}} for positioner {}".format(
              lim1, p.name, fmt=VALUE_FMT)
        print(msg)
        logger.info(msg)

        if not caput(p._record + ".LLM", lim2):
            raise Exception("Unable to set limits for %s", p.name)
        msg = "Lower limit set to {:{fmt}} for positioner {}".format(
              lim2, p.name, fmt=VALUE_FMT)
        print(msg)
        logger.info(msg)
Пример #23
0
def FS_RetigaControl():             # FS_Retiga_control
    '''
    FS_Retiga_control
    '''
    SignalsInput_1id()
    ep.caput('1id:softGlue:FO24_Signal','RetExp',wait=True) # to fast shutter
    return
 def test_TC_401(self):
     tc_no = "TC-401-10-percent-dialPosition"
     print '%s' % tc_no
     print '%s' % tc_no
     epics.caput(self.m1 + '.CNEN', 1)
     destination =  (1 * self.saved_HLM + 9 * self.saved_LLM) / 10
     epics.caput(self.m1 + '.VAL', destination, wait=True)
Пример #25
0
def set_SRSgain(sens, unit, prefix='13IDE:A1', offset=100):
    """set pre-amplifier sensitivity, units, and offset

    Parameters
    ----------
    sens:   number for sensitivity
            one of (1, 2, 5, 10, 20, 50, 100, 200, 500)
    units:  string for units
            one of  ('pA/V', 'nA/V', 'uA/V', 'mA/V')
    prefix: string for SRS Amplifier PV prefix [default '13IIDE:A1']
    offset: number for current offset  [default 100]

    Examples
    --------
    set_SRSamp_gain(100, 'nA/V', prefix='13IDE:A2', offset=105)
    """
    steps = [1, 2, 5, 10, 20, 50, 100, 200, 500]
    units = ['pa/v', 'na/v','ua/v', 'ma/v']

    sens_val = steps.index(sens)
    unit_val = units.index(unit.lower())

    caput("%ssens_unit.VAL" % prefix, unit_val)
    caput("%ssens_num.VAL"  % prefix, sens_val)
    if sens_val > 2:
        sens_val -= 3
    else:
        sens_val += 6
        unit_val -= 1
    #endif
    caput("%soffset_unit.VAL" % prefix, unit_val)
    caput("%soffset_num.VAL"  % prefix, sens_val)
    caput("%soff_u_put.VAL"   % prefix, offset)
Пример #26
0
def DICLiveImage(det, HutchLetter=None, expTime=None):
    if HutchLetter is None:
        print "hutch letter missing."
        print "e: 1-id-e"
        HutchLetter = raw_input("enter hutch letter : ")

    ## LIGHT CONTROL
    if HutchLetter is "e":
        # DIODE FOR OVERHEAD LIGHTS
        pvname = "1ide1:IPC1:ch3"
        #        while mac1id.IsLightOn(pvname):
        #            spec.sleep(0.5)

        # PULIZZI LIGHT SWITCH
        pv_indicator = "1ide1:IPC1:ch3"
        pv_on_switch = "1ide1:IPC1:on_ch3.PROC"
        pv_off_switch = "1ide1:IPC1:off_ch3.PROC"
        if ep.caget(pv_indicator) is False:
            print "pulizzi dic light is off"
            while ep.caget(pv_indicator) is False:
                ep.caput(pv_on_switch, 1)
                spec.sleep(0.25)
            print "pulizzi dic light is on"
    else:
        print "no photo diodes / dic lights implemented"

    AD.AD_set(det, "image_mode", 2)
    AD.AD_set(det, "autosave", 0)
    AD.AD_set(det, "acquire_time", expTime)
    print "python console control returned"
    print "press STOP button to finish live dic feed"
    AD.AD_set(det, "acquire", 1)
Пример #27
0
 def select_rois_to_save(self, roilist):
     """copy rois from MCA record to arrays to be saved
     by XSPress3"""
     roilist = list(roilist)
     if len(roilist) < 4: roilist.append((50, 4050))
     pref = self._prefix
     self._save_rois = []
     for iroi, roiname in enumerate(roilist):
         label = roiname
         if isinstance(roiname, tuple):
             lo, hi = roiname
             label = '[%i:%i]'  % (lo, hi)
         else:
             rname = roiname.lower().strip()
             lo, hi = 50, 4050
             for ix in range(MAX_ROIS):
                 nm = caget('%smca1.R%iNM' % (pref, ix))
                 if nm.lower().strip() == rname:
                     lo = caget('%smca1.R%iLO' % (pref, ix))
                     hi = caget('%smca1.R%iHI' % (pref, ix))
                     break
         self._save_rois.append(label)
         for imca in range(1, self.nmca+1):
             pv_lo = "%sC%i_MCA_ROI%i_LLM" % (pref, imca, iroi+1)
             pv_hi = "%sC%i_MCA_ROI%i_HLM" % (pref, imca, iroi+1)
             caput(pv_hi, hi)
             caput(pv_lo, lo)
Пример #28
0
def motorscan(motor="m1", start=0, end=1, npts=11):
	epics.caput("zzz:scan1.P1PV",("zzz:%s.VAL" % motor), wait=True, timeout=1000000.0)
	epics.caput("zzz:scan1.P1SP",start, wait=True, timeout=1000000.0)
	epics.caput("zzz:scan1.P1EP",end, wait=True, timeout=1000000.0)
	epics.caput("zzz:scan1.NPTS",npts, wait=True, timeout=1000000.0)
	# example of time delay
	time.sleep(.1)
	epics.caput("zzz:scan1.EXSC","1", wait=True, timeout=1000000.0)
Пример #29
0
def shopen():
    #caput('XF:23ID1-VA{Diag:06-GV:1}Cmd:Opn-Cmd', 1, wait=True)
    #caput('XF:23ID1-PPS{PSh}Cmd:Opn-Cmd', 1, wait=True)
    caput('XF:23IDA-EPS{DP:1-Sh:1}Cmd:Out-Cmd',1)
    #time.sleep(1)
    while not shchk():
        #raise Exception('Inconsistent shutter status!')
        time.sleep(0.5)
Пример #30
0
def shclose():
    #caput('XF:23ID1-VA{Diag:06-GV:1}Cmd:Cls-Cmd', 1, wait=True)  # wears our valve. don't use
    #caput('XF:23ID1-PPS{PSh}Cmd:Cls-Cmd', 1, wait=True) 	  # use if DP:1-Sh:1 is broken
    caput('XF:23IDA-EPS{DP:1-Sh:1}Cmd:In-Cmd',1)
    #time.sleep(1)
    while shchk():
        #raise Exception('Inconsistent shutter status!')
        time.sleep(0.5)
Пример #31
0
def fly1d_user(motor, start, end, num_pos, exp):
    caput('XF:03IDC-ES{Flt:2}sendCommand.VAL', "R1")
    RE(fly1d(motor, start, end, num_pos, exp))
    caput('XF:03IDC-ES{Flt:2}sendCommand.VAL', "I1")
Пример #32
0
def start():
    global debug, prefix, wake, doStartMacro, doStopMacro, doReloadMacros, doexecuteMacro
    global doSelectMacro, doAbortMacro, executingMacro, msgQueue
    global allowedUsers, forbiddenUsers, allowedHosts, forbiddenHosts
    global commandMonitorList, exitProgram, doEditMacros, macroFileName

    wake.clear()

    # this monitor will kill us if a new copy of the program is executed
    epics.camonitor(prefix + "caputRecorderStartTime",
                    callback=startTimeMonFunc)

    # Build lists of the PVs we'll monitor while recording
    userPrefixes = epics.caget(prefix + "caputRecorderPrefixes",
                               as_string=True)
    if userPrefixes:
        makeCommandMonitorList(userPrefixes)

    epics.camonitor(prefix + "caputRecorderMacroStopStart",
                    callback=stopStartMonFunc)
    epics.camonitor(prefix + "caputRecorderReloadMacros",
                    callback=reloadMacrosMonFunc)
    epics.camonitor(prefix + "caputRecorderMacro", callback=selectMacroMonFunc)
    epics.camonitor(prefix + "caputRecorderExecuteMacro",
                    callback=executeMacroMonFunc)
    epics.camonitor(prefix + "caputRecorderAbortMacro",
                    callback=abortMacroMonFunc)
    epics.camonitor(prefix + "caputRecorderUsers", callback=usersMonFunc)
    epics.camonitor(prefix + "caputRecorderHosts", callback=hostsMonFunc)
    epics.camonitor(prefix + "caputRecorderPrefixes", callback=prefixesMonFunc)
    reloadMacros()
    # We probably won't get a monitor from Users or Hosts, so do cagets
    users = epics.caget(prefix + "caputRecorderUsers", as_string=True)
    (allowedUsers, forbiddenUsers) = calcAllowed(users)
    if (debug):
        print "allowedUsers='%s', forbiddenUsers='%s'" % (allowedUsers,
                                                          forbiddenUsers)
    hosts = epics.caget(prefix + "caputRecorderHosts", as_string=True)
    (allowedHosts, forbiddenHosts) = calcAllowed(hosts)
    if (debug):
        print "allowedHosts='%s', forbiddenHosts='%s'" % (allowedHosts,
                                                          forbiddenHosts)

    # heartbeat
    heartbeatThread = threading.Thread(target=heartbeat)
    heartbeatThread.daemon = True
    heartbeatThread.start()

    # message and queue
    msgQueue = Queue.Queue(maxsize=100)
    writeThread = threading.Thread(target=writer)
    writeThread.daemon = True
    writeThread.start()

    while (1):
        try:
            wake.wait(1)
        except:
            pass

        if wake.is_set():
            if debug: print "start: wake.is_set()"
            wake.clear()
        if doStartMacro:
            if debug: print "start: doStartMacro=True"
            doStartMacro = 0
            startMacro()
        if doStopMacro:
            if debug: print "start: doStopMacro=True"
            doStopMacro = 0
            endMacro()
        if doReloadMacros:
            if debug: print "start: doReloadMacros=True"
            doReloadMacros = 0
            reloadMacros()
        if doSelectMacro:
            if debug: print "start: doSelectMacro=True"
            doSelectMacro = 0
            selectMacro()
        if doexecuteMacro:
            if debug: print "start: doexecuteMacro=True"
            executeMacro()
            doexecuteMacro = 0
            epics.caput(prefix + "caputRecorderExecuteMacro", 0)
        if doAbortMacro:
            doAbortMacro = 0
            epics.caput(prefix + "caputRecorderAbortMacro", 0)
        if doEditMacros:
            doEditMacros = 0
            epics.caput(prefix + "caputRecorderEditMacros", 0)
            editor = os.environ['EDITOR']
            os.system(editor + " " + macroFileName + "&")
        if exitProgram:
            sys.exit()
    stop()
This is for X-piezo scan (stage coordinates) and Y-combined (stage coordinates) batch flyscan with different sample_Z postions.

The max scan width in X direction is 80 um.

'''
import epics
from epics import caput, caget
from epics import PV
import time
import numpy as np
import pdb
'''
please enter the scan prameters below:
scans [x-center(um), y-center.(um), z-position (um), x-width.(um), y-width.(um), x-stepsize.(um), Y-stepsize.(um), dwell.(ms)]
'''
caput('9idbTAU:SM:Ps:xyDiffMotion.VAL', 1)

scans = []

# add some lines to check the beam alignment

pvs = [
    '9idbTAU:SM:PX:RqsPos', '9idbTAU:SY:PY:RqsPos', '9idbTAU:SM:SZ:RqsPos',
    '9idbBNP:scan1.P1WD', '9idbBNP:scan2.P1WD', '9idbBNP:scan1.P1SI',
    '9idbBNP:scan2.P1SI', '9idbBNP:scanTran3.C PP'
]

sm_px_RqsPos = PV('9idbTAU:SM:PX:RqsPos')
sm_px_ActPos = PV('9idbTAU:SM:PX:ActPos')
sm_py_RqsPos = PV('9idbTAU:SY:PY:RqsPos')
sm_py_ActPos = PV('9idbTAU:SY:PY:ActPos')
Пример #34
0
 def ImageReady(self, sender, image):
     if self.getParam('XSYNC') == 3:
         caput(XRAY_IOC + 'EXPOSE' , 0)
     print str(datetime.datetime.now())[:-3], 'Image Ready'
     # if not scanning or scanning and all images acquired then go back to standby mode.
     if caget(SCANPROGRESS_IOC +'running') == 1:
         # check if all images from scan are done. 
         if (NFINISHED.get() + 1 == NTOTAL.get()):
             self.stopXray()
     else:
         self.stopXray()
     ###############################
     # Determine Filename and type
     ###############################
     num = int(self.getParam('FILENUM'))
     pathname = self.getParam('FILEPATH') + \
     self.getParam('FILENAME') + str(num)
     if image.Type == Nikon.NikonImageType.Jpeg:
         writename = pathname + ".jpg"
     elif image.Type == Nikon.NikonImageType.Raw:
         writename = pathname + ".nef"
     else:
         writename = pathname + ".tiff"
     if os.path.exists(writename):
         print "Warning filename already exists- Overwriting!"
     ################################
     # Write file directly from camera
     ################################
     if self.getParam('SAVEIMG') == 1:
         self.savecamfile(image, writename)
     elif image.Type == Nikon.NikonImageType.Raw & \
          self.getParam('NEFTOTIFF') == 1:
         self.savecamfile(image, writename)
     ################################
     # Write 16bit linear tiff
     ################################
     if self.getParam('NEFTOTIFF') == 1 & image.Type == Nikon.NikonImageType.Raw:
         try:
             if self.getParam('TIFFFILEPATH') == '':
                 tiffpathname = self.getParam('FILEPATH') + \
                 self.getParam('FILENAME') + str(num)
             else:
                 tiffpathname = self.getParam('TIFFFILEPATH') + \
                 self.getParam('FILENAME') + str(num)
             self.nid = mp.Process(target=self.imgconvert.ntt, \
                        args=(writename, writename, \
                        self.getParam('SAVEIMG'), tiffpathname+".tif", \
                        self.getParam('YSIZE'), self.getParam('XSIZE'), \
                        self.getParam('Y0CROP'), self.getParam('X0CROP'), \
                        self.getParam('BIN'), self.getParam('GREEN')))
             self.nid.start()
         except Exception as e:
             self.imgconvert = None
             print "nef conversion failed", e
             if self.getParam('SAVEIMG') == 0:
                 print "saving nef as backup"
                 s = System.IO.FileStream(writename, System.IO.FileMode.Create, System.IO.FileAccess.Write)
                 s.Write(image.Buffer, 0, image.Buffer.Length)
                 s.Close()
     ###############################
     # Post Array data
     ###############################
     if self.getParam('IMAGEJ') == 1:
         if self.getParam('FILE_TYPE') in [0, 1, 2]:
             self.lid = threading.Thread(target=self.postarray, args=(image, ))
             self.lid.daemon = True
             self.lid.start()
     ################################
     # Update relevant pvs, document
     ################################
     if self.getParam('DOC') == 1:
         if self.getParam('SAVEIMG') == 1:
             f = open(pathname + '.txt', 'w')
             f.write(self.documentString)
         if self.getParam('NEFTOTIFF') == 1:
             f = open(tiffpathname + '.txt', 'w')
             f.write(self.documentString)
         self.documentString = ''
     self.setParam('STATUS_RBV', 0)
     if self.getParam('AUTOINCR') == 1:
         self.setParam('FILENUM', num + 1)
     self.setParam('LASTFILE_RBV', writename)
     self.setParam('FIRE', 0)
     caput(SCAN_IOC + 'scan1.WAIT', 0)
     caput(SCAN_IOC + 'scan2.WAIT', 0)
     caput(SCAN_IOC + 'scan3.WAIT', 0)
     self.updatePVs()
Пример #35
0
 def write_ps_en(self, enables):
   epics.caput(self.writepv, cmd_make(0, self.ps_en_address, enables))
from python_quadscan_methods import *

# Scanner
scanner = "melba_020:scan"

if len(sys.argv) != 5:
    print(
        "Usage: python3 {} <quad_no=1> <i_init=-0.05> <i_final=0.15> <di=0.05>, shutter can be closed, picamera should be ready for trigger"
        .format(sys.argv[0]))
    sys.exit()

# Try communication with laser shutter
try:
    epics.caget('steam:laser_shutter:ls_set')
    epics.caput('steam:laser:dc_set', 0)

except:
    print("Could not read laser shutter status or dc could not be set off.")
    print("Aborting script.")
    abort_script()

else:
    if epics.caget('steam:laser_shutter:ls_set.DISP') == 1:
        print(
            "Laser shutter can not be opened due to ls_set.DISP=1. Aborting script."
        )
        abort_script(True)
    if epics.caget('steam:laser:trig_get') != 1:
        epics.caput('steam:laser:trig_set', 1)
Пример #37
0
 def set_value(self, device_name, val):
     return epics.caput(device_name + ':BCTRL', val)
Пример #38
0
def test_local_root():
    """
    Test Epics Server
    """
    return

    # Test both autogeneration and mapping of PV names
    pv_map_states = [False, True]

    for s in pv_map_states:
        with LocalRootWithEpics(use_map=s) as root:
            time.sleep(1)

            # Device EPICS PV name prefix
            device_epics_prefix = epics_prefix + ':LocalRoot:myDevice'

            # Test dump method
            root.epics.dump()

            # Test list method
            root.epics.list()
            time.sleep(1)

            # Test RW a variable holding an scalar value
            pv_name = device_epics_prefix + ':var'
            test_value = 314
            caput(pv_name, test_value)
            time.sleep(1)
            test_result = caget(pv_name)
            if test_result != test_value:
                raise AssertionError('pv_name={}: test_value={}; test_result={}'.format(\
                                        pv_name, test_value, test_result))

            # Test RW a variable holding a float value
            pv_name = device_epics_prefix + ':var_float'
            test_value = 5.67
            caput(pv_name, test_value)
            time.sleep(1)
            test_result = round(caget(pv_name), 2)
            if test_result != test_value:
                raise AssertionError('pvStates={} pv_name={}: test_value={}; test_result={}'.format(\
                                        s, pv_name, test_value, test_result))

        # Allow epics client to reset
        time.sleep(5)
    """
    Test EPICS server with a non-started tree
    """
    try:
        root = pyrogue.Root(name='LocalRoot', description='Local root')
        root.epics = pyrogue.protocols.epics.EpicsCaServer(base=epics_prefix,
                                                           root=root)
        root.epics.start()
        raise AssertionError(
            'Attaching a pyrogue.epics to a non-started tree did not throw exception'
        )
    except Exception as e:
        pass
    """
    Test createMaster and createSlave methods
    """
    with LocalRootWithEpics() as root:
        slave = root.epics.createSlave(name='slave',
                                       maxSize=1000,
                                       type='UInt16')
        master = root.epics.createMaster(name='master',
                                         maxSize=1000,
                                         type='UInt16')
Пример #39
0
    detector = '13MARCCD2:cam1'
    # detector = '13MAR345_2:cam1'

    caput('13IDD:Unidig2Bo5', 0)  #move in beamsteop
    caput('13IDD:Unidig1Bo9', 1)  #move out photodiod
    time.sleep(1.5)  # wait for completion

    caput(detector + ':AcquireTime', exposure_time)
    caput(detector + ':Acquire', 1, wait=True, timeout=99999999)
    print "DETECTOR: data collection FINISHED"


if __name__ == '__main__':
    # # perform_rotation(35.65, 20, -0.33)

    caput('13IDD:m96', -100.7, wait=True)

    cur_pos_m83 = caget('13IDD:m83')
    caput('13IDD:m83', cur_pos_m83 - 0.010)

    collect_data(
        center_offset=35.65,
        collection_time=300,
        angle=3.205,  # 3.205
        theta_offset=-0.33)

    caput('13IDD:m83', cur_pos_m83)
    time.sleep(110)
    collect_data(
        center_offset=35.65,
        collection_time=300,
Пример #40
0
def zero(nx=527):
    for j in range(0, nx):
        lname = "[" + str(j) + "]"
        pv = base_name + lname
        epics.caput(pv, 0)
 def set_diamter(self, dia, pump=1):
     caput(self.PV_diameter % pump, dia)
     print('Set the diameter of the pump %s as %s mm.' % (pump, dia))
 def set_rate(self, rate, pump=1):
     caput(self.PV_set_rate % pump, rate)
     print('Set the rate of the pump %s as %s.' % (pump, rate))
Пример #43
0
def startMacro():
    global debug, macroFile, prefix, macroFunctionNames
    global commandMonitorList, connected, timeOfLastPut, ifMacroExists
    global macroFileName, recordingActive

    if debug: print("startMacro: entry\n")
    if not connected:
        return

    busy = epics.caget(prefix + "caputRecorderMacroRecording")
    if (busy):
        epics.caput(prefix + "caputRecorderUserMessage",
                    "a macro is already being recorded")
        return
    tryMacroName = epics.caget(prefix + "caputRecorderMacroName")

    # check macroName for problems
    if (tryMacroName == ""):
        epics.caput(prefix + "caputRecorderUserMessage",
                    "*** macro name is empty")
        epics.caput(prefix + "caputRecorderMacroStopStart", 0)
        return
    # function name must start with a letter
    macroName = ""
    if tryMacroName[0] not in string.letters:
        macroName = "a"
    # function name must consist of letters, digits, and underscores
    for c in tryMacroName:
        if c in legalChars:
            macroName += c
        else:
            macroName += "_"
    # function name must be 25 characters or less (mbboRecord string length)
    if len(macroName) > 25: macroName = macroName[:25]
    if (macroName in keyword.kwlist):
        epics.caput(prefix + "caputRecorderUserMessage",
                    "*** macro name is a python keyword")
        epics.caput(prefix + "caputRecorderMacroStopStart", 0)
        return
    # See of function name is already defined
    appending = False
    if debug: print "startMacro: ifMacroExists=", ifMacroExists
    if macroName in macroFunctionNames:
        if debug: print "ifMacroExists=%s" % ifMacroExists
        if ifMacroExists == "Fail":
            epics.caput(prefix + "caputRecorderUserMessage",
                        "*** macro name is already in use")
            epics.caput(prefix + "caputRecorderMacroStopStart", 0)
            return
        if ifMacroExists == "Replace":
            timeString = time.strftime("_%y%m%d-%H%M%S")
            shutil.copy(macroFileName, macroFileName + timeString)
        dl = deleteFunction(macroFileName, macroName)
        if ifMacroExists == "Append":
            macroFile = open(macroFileName, "a")
            macroFile.writelines(dl)
            macroFile.close()
            appending = True
            epics.caput(prefix + "caputRecorderUserMessage",
                        "appending to existing macro")
        else:
            # replace

            epics.caput(prefix + "caputRecorderUserMessage",
                        "replacing existing macro")

    epics.caput(prefix + "caputRecorderMacroRecording", 1)
    epics.caput(prefix + "caputRecorderUserMessage", "Recording")
    macroFile = open(macroFileName, "a")
    if appending == False:
        macroFile.write("def %s():\n" % macroName)
    else:
        macroFile.write("\t# appended to existing macro...\n")

    # It's not legal to have a python function with no commands in it.
    # Defend against user stopping recording without doing any caputs
    # by writing dummy command to set the record date.
    now = time.strftime("%c")
    macroFile.write("\trecordDate = \"%s\"\n" % now)
    macroFile.flush()
    timeOfLastPut = None
    epics.camonitor(prefix + "caputRecorderComment", callback=commentMonFunc)
    epics.camonitor(prefix + "caputRecorderAddDelayCmd", callback=delayMonFunc)

    # If this is the first time we're connecting to a commandMonitorList pv,
    # we might get an initial value callback.  We want to ignore that, because the
    # user didn't do it.  So, monitor and unmonitor all the commandMonitorList pvs,
    # to flush out any initial value callbacks, then monitor the pvs and set
    # recordingActive==True.
    for pv in commandMonitorList:
        epics.camonitor(pv, callback=commandMonFunc)

    for pv in commandMonitorList:
        epics.camonitor_clear(pv)

    for pv in commandMonitorList:
        epics.camonitor(pv, callback=commandMonFunc)
    recordingActive = True
Пример #44
0
def zp_mesh_scan(xs, xe, xn, ys, ye, yn, exposure):
    zpssx_0 = zpssx.position
    zpssy_0 = zpssy.position
    x_step_size = (xe - xs) / xn
    y_step_size = (ye - ys) / yn
    print(xs, xe, xn, x_step_size, ys, ye, yn, y_step_size)

    caput('XF:03IDC-ES{Merlin:2}cam1:Acquire', 0)
    caput('XF:03IDC-ES{Merlin:1}cam1:Acquire', 0)

    caput('XF:03IDC-ES{Merlin:1}cam1:AcquireTime', exposure)
    yield from bps.sleep(5)
    caput('XF:03IDC-ES{Merlin:2}cam1:AcquireTime', exposure)
    yield from bps.sleep(5)

    caput('XF:03IDC-ES{Merlin:1}cam1:AcquirePeriod', exposure + 0.1)
    yield from bps.sleep(5)
    caput('XF:03IDC-ES{Merlin:2}cam1:AcquirePeriod', exposure + 0.1)
    yield from bps.sleep(5)
    yield from bps.movr(zpssx, xs)
    yield from bps.movr(zpssy, ys)

    for i in range(xn + 1):
        for j in range(yn + 1):
            print(i, j, zpssx.position, zpssy.position)

            caput('XF:03IDC-ES{Merlin:2}TIFF1:Capture', 1)
            yield from bps.sleep(2)
            caput('XF:03IDC-ES{Merlin:1}TIFF1:Capture', 1)
            yield from bps.sleep(2)

            print('start exposure ...')
            caput('XF:03IDC-ES{Merlin:2}cam1:Acquire', 1)
            yield from bps.sleep(2)
            caput('XF:03IDC-ES{Merlin:1}cam1:Acquire', 1)
            yield from bps.sleep(2)

            print('wait ...')
            yield from bps.sleep(exposure + 5)

            yield from bps.movr(zpssx, x_step_size)

        yield from bps.mov(zpssx, zpssx_0 + xs)
        yield from bps.movr(zpssy, y_step_size)

    yield from bps.mov(zpssx, zpssx_0)
    yield from bps.mov(zpssy, zpssy_0)
Пример #45
0
import cin_register_map
import cin_functions
import time
#from epics import caget, caput, cainfo

#cin_functions.setCameraOn()
from epics import caget
from epics import caput
from epics import cainfo

#import subprocess
cin_functions.setCameraOff()
cin_functions.CINPowerDown()

# turn off clocks and bias and put into single mode
caput ("FCCD:cam1:fccd_clock_on",0)
time.sleep(1.0)
caput ("FCCD:cam1:fccd_bias_on",0)
time.sleep(1.0)
caput ("FCCD:cam1:ImageMode", "0")


####################
# make sure acopian is power up
# 1 verity power ioc is running?
###results=subprocess.check_output(["pgrep", "-f", "fccd2App"])
# 2 if not running exit
# 3 if running verify that it is powered on
powerStatus = caget('fccd2:WebRelay1:Y0OutB.VAL')
print "Power Supply Status (0=off, 1=on) = " + str(powerStatus)
Пример #46
0
def writer():
    global debug, macroFile, prefix, msgQueue, doexecuteMacro, executeLevel, postponeStop
    global doStartMacro, doStopMacro, connected, recordTiming, timeOfLastPut, waitCompletion, recordingActive

    while (1):
        (msg, char_value) = msgQueue.get()
        if debug: print "writer: type=%d, char_value='%s'" % (msg, char_value)
        if executeLevel and (msg != MSG_DO):
            continue
        if not connected:
            continue
        if msg == MSG_COMMAND:
            now = time.time()
            if timeOfLastPut:
                if debug: print "writer: recordTiming = %d" % recordTiming
                dt = now - timeOfLastPut
                if recordTiming and dt > 0:
                    macroFile.write("\ttime.sleep(%.3f)\n" % dt)
            timeOfLastPut = now

            (pvname, value, user_host) = char_value.split(',')
            recordablePV = 1
            # Ignore caputs to caputRecorder PVs
            if char_value.find(prefix + "caputRecorder") >= 0:
                recordablePV = 0

            if recordablePV:
                # check user and host
                allowed = True
                if user_host:
                    (user, host) = user_host.split("@")
                    host = host.split(".")[0]
                    if debug: print "writer: user=%s, host=%s" % (user, host)
                    allowed = userHostAllowed(user, host)
                if allowed:
                    # If DBF_UCHAR (TPRO, DISP, PROC, UDF, syn.AQR, mbbiDirect.Bn), write int value to avoid bug in PyEpics 3.4.2
                    # None but PROC are at all likely
                    dbf_uchar_fields = (".PROC", ".TPRO", ".DISP", ".UDF")
                    if waitCompletion:
                        putWaitSeconds = epics.caget(prefix +
                                                     "caputRecorderWaitCBSec",
                                                     use_monitor=True)
                        if pvname.endswith(dbf_uchar_fields):
                            macroFile.write(
                                "\tepics.caput(\"%s\",%d, wait=True, timeout=%.1f)\n"
                                % (pvname, int(value), putWaitSeconds))
                        else:
                            macroFile.write(
                                "\tepics.caput(\"%s\",\"%s\", wait=True, timeout=%.1f)\n"
                                % (pvname, value, putWaitSeconds))
                    else:
                        if pvname.endswith(dbf_uchar_fields):
                            macroFile.write("\tepics.caput(\"%s\",%d)\n" %
                                            (pvname, int(value)))
                        else:
                            macroFile.write("\tepics.caput(\"%s\",\"%s\")\n" %
                                            (pvname, value))
                    macroFile.flush()
            msgQueue.task_done()
        elif msg == MSG_COMMENT:
            macroFile.write("\t# %s\n" % char_value)
            macroFile.flush()
        elif msg == MSG_DELAY:
            delayTime = epics.caget(prefix + "caputRecorderDelaySec")
            macroFile.write("\ttime.sleep(%.3f)\n" % delayTime)
            macroFile.flush()
            epics.caput(prefix + "caputRecorderAddDelayCmd", 0)
        elif msg == MSG_DO:
            if debug: print "writer:MSG_DO, char_value='%s'" % char_value
            try:
                busy = epics.caget(prefix + "caputRecorderMacroRecording")
            except:
                return
            if char_value == "Do":
                if (busy):

                    # if ExecuteLoops > 1, write a loop
                    loops = epics.caget(prefix + "caputRecorderExecuteLoops")
                    loops = max(1, loops)
                    if loops > 1:
                        indent = "\t\t"
                        cmd = "\tfor i in range(%s):\n" % loops
                        macroFile.write(cmd)
                    else:
                        indent = "\t"

                    # add call to selected function to macro file
                    fname = epics.caget(prefix + "caputRecorderMacro")
                    cmd = indent + fname + "("
                    for j in range(1, maxArgs + 1):
                        argName = epics.caget(prefix +
                                              ("caputRecorderArg%dName" % j))
                        argValue = epics.caget(prefix +
                                               ("caputRecorderArg%dValue" % j))
                        if argName:
                            if j > 1:
                                cmd = cmd + ","
                            cmd = cmd + argName + "=" + argValue
                        else:
                            break
                    cmd = cmd + ")\n"
                    macroFile.write(cmd)
                    macroFile.flush()
                    # execute macro, but stop recording while it executes
                    executeLevel += 1
                    if executeLevel:
                        epics.caput(prefix + "caputRecorderUserMessage",
                                    "recording suppressed during execution")
                    doexecuteMacro = 1
                    wake.set()
                else:
                    doexecuteMacro = 1
                    wake.set()
            else:
                if executeLevel > 0:
                    executeLevel -= 1
                    if executeLevel == 0:
                        epics.caput(prefix + "caputRecorderUserMessage", "")
                        if postponeStop:
                            if debug: print "writer: executing postponed Stop"
                            doStopMacro = 1
                            postponeStop = 0
                            wake.set()
Пример #47
0
    async def toFixed(self, device: Device, voltage: int,
                      channels_selected: List[bool]):
        self.timerStatus.emit({"device": device.prefix, "status": "to Fixed"})

        pv = device.prefix + ":Step-SP"
        actual_value = epics.caget(device.prefix + ":Step-RB",
                                   timeout=EPICS_TOUT)
        if actual_value is None:
            logger.critical(
                "Failed to get {} value, aborting operation.".format(
                    device.prefix + ":Step-RB"))
            self.timerStatus.emit({
                "device": device.prefix,
                "status": "failed to get readback"
            })
            return

        val = actual_value
        for _, selected, shift in zip(device.channels, channels_selected,
                                      range(len(channels_selected))):
            if selected:
                val &= ~(1 << shift)

        logger.info("Channel {}  {:04b} -> {:04b} {}".format(
            pv, actual_value, val, channels_selected))

        self.timerStatus.emit({
            "device":
            device.prefix,
            "status":
            'to Fixed "{:04b}"->"{:04b}"'.format(actual_value, val),
        })

        if epics.caput(pv, val, timeout=EPICS_TOUT) == 1:
            await asyncio.sleep(CMD_TOUT)

            for ch, selected in zip(device.channels, channels_selected):
                if not selected:
                    continue
                pv, val = ch.prefix + ":VoltageTarget-SP", voltage

                self.timerStatus.emit({
                    "device":
                    device.prefix,
                    "status":
                    "{} Voltage -> {}V".format(pv, val),
                })

                logger.info("set {} {}".format(pv, val))
                epics.caput(pv, val, timeout=EPICS_TOUT)

                # @fixme: Two devices at the same serial network should have an actual delay!
                time.sleep(TIMER_BETWEEN_DEVICES)
                await asyncio.sleep(CMD_TOUT)

            self.timerStatus.emit({"device": device.prefix, "status": "Done"})
        else:
            self.timerStatus.emit({
                "device": device.prefix,
                "status": "Failed"
            })
Пример #48
0
def EDXD_COLLECTING(tth, pvsize, phsize, svsize, shsize, dvsize, dhsize,
                    stime):
    current_tth = caget('16BMA:m5.RBV')
    current_beamstop = caget('16BMA:Unidig2Bo0')

    MOVE_TTH(tth, current_tth, current_beamstop)

    #set the slit and 2theta condition
    caput('16BMA:pm14.VAL', pvsize)
    caput('16BMA:pm16.VAL', phsize)
    caput('16BMA:pm18.VAL', svsize)
    caput('16BMA:pm20.VAL', shsize)
    caput('16BMA:m40.VAL', dvsize)
    caput('16BMA:m38.VAL', dhsize)

    #start collecting data
    caput('16BMA:aim_adc1Erase', 1)
    time.sleep(0.2)
    caput('16BMA:aim_adc1Start', 1)
    livetime = caget('16BMA:aim_adc1.ELTM')
    while livetime < stime - 0.1:
        livetime = caget('16BMA:aim_adc1.ELTM')
        time.sleep(0.2)
    caput('16BMA:aim_adc1Stop', 1)
    time.sleep(0.2)
Пример #49
0
 def write_relays(self, relay):  # relay is the bit partern to set
   epics.caput(self.writepv, cmd_make(0, self.relay_address, relay))
Пример #50
0
    Primary_hsize0 = caget('16BMA:pm16.RBV')
    Secondary_vsize0 = caget('16BMA:pm18.RBV')
    Secondary_hsize0 = caget('16BMA:pm20.RBV')
    Detector_vsize0 = caget('16BMA:m40.RBV')
    Detector_hsize0 = caget('16BMA:m38.RBV')

    for n in range(0, rep):
        print "Iteration =", n + 1
        for j in range(0, num_angles):
            EDXD_COLLECTING(exp_conditions[j, 0], exp_conditions[j, 1],
                            exp_conditions[j, 2], exp_conditions[j, 3],
                            exp_conditions[j, 4], exp_conditions[j, 5],
                            exp_conditions[j, 6], exp_conditions[j, 7])
            time.sleep(1.0)
            now = time.localtime(time.time())
            t = time.strftime("%a_%d%b%y_%H_%M", now)
            try:
                print "2th =", exp_conditions[
                    j, 0], "EDXD_COLLECTING finished at", t
            except:
                print "End of data collection"
        time.sleep(10.0)

    caput('16BMA:m5.VAL', twotheta0)
    caput('16BMA:pm14.VAL', Primary_vsize0)
    caput('16BMA:pm16.VAL', Primary_hsize0)
    caput('16BMA:pm18.VAL', Secondary_vsize0)
    caput('16BMA:pm20.VAL', Secondary_hsize0)
    caput('16BMA:m40.VAL', Detector_vsize0)
    caput('16BMA:m38.VAL', Detector_hsize0)
def main():
    print "Beginning pulsing script"
    # this trigger width used to be 100 ns Alex changed it to 50 ns on 2018-Oct-3.
    caput('FCAL:pulser:TRIG:width_w', 50)
    test = False
    Status = -1
    while 1:
        MustPulse = ShouldWePulse()
        mins = int(time.strftime("%M"))
        # the test allows changes every minutes instead of every 10
        if test:
            val = mins % 6
            if mins == 1:
                Period = 1
            elif val == 2:
                Period = 2
            elif val == 3:
                Period = 3
            elif val == 4:
                Period = 4
            elif val == 5:
                Period = 5
            else:
                Period = 0
        else:
            if mins < 10:
                Period = 1
            elif mins < 20:
                Period = 2
            elif mins < 30:
                Period = 3
            elif mins < 40:
                Period = 4
            elif mins < 50:
                Period = 5
            else:
                Period = 0
        print "Status=", Status, "Minute=", mins, " Period=", Period, " Running=", MustPulse

        if MustPulse:
            if (MustPulse and Status != 0 and Period == 0):
                Status = 0
                LEDsOff()
            if (MustPulse and Status != 1 and Period == 1):
                Status = 1
                LEDsPowerOn()
                RunVioletLow()
            if (MustPulse and Status != 2 and Period == 2):
                Status = 2
                LEDsPowerOn()
                RunBlueLow()
            if (MustPulse and Status != 3 and Period == 3):
                Status = 3
                LEDsPowerOn()
                RunGreen()
            if (MustPulse and Status != 4 and Period == 4):
                Status = 4
                LEDsPowerOn()
                RunVioletHigh()
            if (MustPulse and Status != 5 and Period == 5):
                Status = 5
                LEDsPowerOn()
                RunBlueHigh()
        else:
            if (Status != 0):
                Status = 0
                LEDsOff()

        time.sleep(2)
Пример #52
0
    def ConfigCamera(self):
        if not self.cam_type.lower().startswith('web'):
            if not self.cam_adpref.endswith(':'):
                self.cam_adpref = "%s:" % self.cam_adpref
            cname = "%s%s1:" % (self.cam_adpref, self.cam_adform.upper())
            caput("%sEnableCallbacks" % cname, 1)
            thisdir = os.path.abspath(os.getcwd())
            thisdir = thisdir.replace('\\',
                                      '/').replace('T:/', '/Volumes/Data/')

            caput("%sFilePath" % cname, thisdir)
            caput("%sAutoSave" % cname, 0)
            caput("%sAutoIncrement" % cname, 0)
            caput("%sFileTemplate" % cname, "%s%s")
            if self.cam_adform.upper() == 'JPEG':
                caput("%sJPEGQuality" % cname, 90)
Пример #53
0
 def write(self, reason, value):
     if reason == 'FIRE' and value == 1:
         # Set status to idle and make sure camera is connected before firing
         if self.getParam('INITSTAT_RBV') == 1 and self.getParam('STATUS_RBV') == 0:
             self.tid = threading.Thread(target=self.capt, args=())
             self.tid.daemon = True
             self.tid.start()
     if reason == 'LV':
         self.setParam(reason, value)
         self.tid = threading.Thread(target=self.lv, args=(value, ))
         self.tid.daemon = True
         self.tid.start()
     elif reason == 'INIT_RBV':
         if self.getParam('INITSTAT_RBV') == 0:
             self.tid = threading.Thread(target=self.init, args=())
             self.tid.daemon = True
             self.tid.start()
     # Currently Shutter index is not used. Trying to find a better way to display all nikon enums
     elif reason == 'SHUTTER_INDEX':
         if self.getParam('INITSTAT_RBV') == 1 and self.getParam('STATUS_RBV') == 0:
             nicam.setenum('SHUTTER', value)
     # setting all nikon enums
     elif reason == 'FILE_TYPE' or reason == 'SHUTTER' or \
          reason == 'JPEGSIZE' or reason == 'ISO':
         if self.getParam('INITSTAT_RBV') == 1 and self.getParam('STATUS_RBV') == 0:
             nicam.setenum(reason, value)
     elif reason == "DEINIT_RBV" and value == 1:
         self.deinit()
     # set filepath here
     elif reason == "FILEPATH":
         self.setParam(reason, value)
         if value != '' and value[-1] != '\\':
             caput(prefix + 'FILEPATH', value + '\\')
         if os.path.isdir(value):
             self.setParam("FILEPATHEXISTS_RBV", 1)
         else:
             self.setParam("FILEPATHEXISTS_RBV", 0)
    # set tiff filepath here
     elif reason == "TIFFFILEPATH":
         self.setParam(reason, value)
         if value != '' and value[-1] != '\\':
             caput(prefix + 'TIFFFILEPATH', value + '\\')
     elif reason == "FILENAME":
         self.setParam(reason, value)
         if value != '' and value[-1] != '_':
             caput(prefix + 'FILENAME', value + '_')
         self.setParam('FILENUM', 0)
         fp = self.getParam('FILEPATH')
         fn = str(int(self.getParam('FILENUM')))
         if os.path.exists(fp + value + fn + '.jpg'):
             self.setParam("FILENAMEEXISTS_RBV", 1)
         elif os.path.exists(fp+value + fn + '.nef'):
             self.setParam("FILENAMEEXISTS_RBV", 1)
         else:
             self.setParam("FILENAMEEXISTS_RBV", 0)
     elif reason == 'RAWBIT':
         nicam.setBit(value)
         self.setParam(reason, value)    
     elif reason == "RAWCOMPRESS":
         nicam.setCompress(value)
         self.setParam(reason, value)
     elif reason == "XSYNC":
        self.setParam(reason, value)
     else:
         self.setParam(reason, value)
     self.setParam(reason, value)
     self.updatePVs()
     self.getinfo()
Пример #54
0
def fly2d_user(motor1, start1, end1, num1, motor2, start2, end2, num2, exp):
    caput('XF:03IDC-ES{Flt:2}sendCommand.VAL', "R1")
    RE(fly2d(motor1, start1, end1, num1, motor2, start2, end2, num2, exp))
    caput('XF:03IDC-ES{Flt:2}sendCommand.VAL', "I1")
 def set_vol(self, vol, pump=1):
     caput(self.PV_set_vol % pump, vol)
     print('Set the liquid volume of the pump %s as %s.' % (pump, vol))
Пример #56
0
def reloadMacros():
    global macros
    global debug, prefix, macroFunctionNames, macroFunctions, menuFields
    global _macroFunctionNames, _macroFunctions, connected

    if debug: print "reloadMacros:entry"
    if not connected:
        if debug: print "reloadMacros:not connected"
        return

    success = 0
    functions = []
    _macroFunctionNames = []
    _macroFunctions = []
    macroFunctionNames = []
    macroFunctions = []

    if debug: print "reloadMacros: dir(macros)=", dir(macros)
    try:
        reload(macros)
        success = 1
    except:
        epics.caput(prefix + "caputRecorderUserMessage",
                    "Macro file contains error(s)")
    if debug: print "reloadMacros: dir(macros)=", dir(macros)

    # erase menu strings
    epics.caput(prefix + "caputRecorderClearMacros", 1, wait=True, timeout=5)

    if success:
        functions = [o for o in getmembers(macros) if isfunction(o[1])]
        if debug: print "reloadMacros:functions=", functions
        (_macroFunctionNames, _macroFunctions) = zip(*functions)
        # don't add functions whose names begin with '_' to function menu
        macroFunctionNames = list(copy.deepcopy(_macroFunctionNames))
        macroFunctions = list(copy.deepcopy(_macroFunctions))
        i = 0
        while i < len(macroFunctionNames):
            if macroFunctionNames[i][0] == '_':
                del macroFunctionNames[i]
                del macroFunctions[i]
            else:
                i += 1
        if debug: print "reloadMacros:macroFunctionNames=", macroFunctionNames
        i = 0
        numItems = [0] * maxMacroMenus
        itemNames = [""] * 16 * maxMacroMenus
        for (name, func, field) in zip(macroFunctionNames, macroFunctions,
                                       menuFields * maxMacroMenus):
            menu = i / len(menuFields) + 1
            epics.caput(prefix + ("caputRecorderMacros%d." % menu) + field,
                        name)
            i += 1
            numItems[menu] += 1

        for i in range(maxMacroMenus):
            itemNum = epics.caget(prefix + ("caputRecorderMacros%d" % (i + 1)))
            if itemNum > numItems[i]:
                epics.caput(prefix + ("caputRecorderMacros%d" % menu), 0)

    selectMacro()
    epics.caput(prefix + "caputRecorderUserMessage",
                "Macro (re)load succeeded")
    epics.caput(prefix + "caputRecorderNeedRefresh", 1)
    epics.caput(prefix + "caputRecorderReloadMacros", 0)
Пример #57
0
def set_bit(pv, mask, val):  # sets a bit without changeing others
    print("pv = ", pv)
    old = epics.caget(pv)  # old value
    tmp = old & (0xffffffff - mask)  # everything but hte mask value
    new = tmp + (val & mask)
    epics.caput(pv, new)
Пример #58
0
def increment_vals():
    for j in range(0, 528):
        lname = "[" + str(j) + "]"
        pv = base_name + lname
        epics.caput(pv, j * 32)
Пример #59
0
def stop():
    global debug, prefix

    epics.camonitor_clear(prefix + "caputRecorderMacroStopStart")
    epics.camonitor_clear(prefix + "caputRecorderReloadMacros")
    epics.camonitor_clear(prefix + "caputRecorderMacro")
    epics.camonitor_clear(prefix + "caputRecorderExecuteMacro")
    epics.camonitor_clear(prefix + "caputRecorderAbortMacro")
    epics.camonitor_clear(prefix + "caputRecorderUsers")
    epics.camonitor_clear(prefix + "caputRecorderHosts")
    epics.camonitor_clear(prefix + "caputRecorderPrefixes")
    epics.camonitor_clear(prefix + "caputRecorderAddDelayCmd")
    epics.camonitor_clear(prefix + "caputRecorderComment")

    # clear all busy records, and the bo record caputRecorderEditMacros
    epics.caput(prefix + "caputRecorderMacroStopStart", 0)
    epics.caput(prefix + "caputRecorderMacroRecording", 0)
    epics.caput(prefix + "caputRecorderExecuteMacro", 0)
    epics.caput(prefix + "caputRecorderEditMacros", 0)
    epics.caput(prefix + "caputRecorderAbortMacro", 0)
    epics.caput(prefix + "caputRecorderAddDelayCmd", 0)
 def set_direction(self, direct, pump=1):
     caput(self.PV_direction % pump, direct)
     print('Set the direction of the pump %s as %s.' %
           (pump, self.direction_units[direct]))