Example #1
0
class DisplayEpicsPVClass(ScannableBase):
    '''Create PD to display single EPICS PV'''
    def __init__(self, name, pvstring, unitstring, formatstring):
        self.setName(name)
        self.setInputNames([])
        self.setExtraNames([name])
        self.Units = [unitstring]
        self.setOutputFormat([formatstring])
        self.setLevel(3)
        self.cli = CAClient(pvstring)

    def atStart(self):
        if not self.cli.isConfigured():
            self.cli.configure()

    def getPosition(self):
        if self.cli.isConfigured():
            return float(self.cli.caget())
        else:
            self.cli.configure()
            return float(self.cli.caget())
            self.cli.clearup()

    def isBusy(self):
        return 0

    def atEnd(self):
        if self.cli.isConfigured():
            self.cli.clearup()
Example #2
0
class KepkoCurrent(ScannableMotionBase):
    def __init__(self, name, pv):
        self.setName(name)
        self.setInputNames(['Ampere'])
        self.setOutputFormat(['%2.4f'])
        self.setLevel(6)
        self.ch = CAClient(pv)
        self.ch.configure()

    def atScanStart(self):
        return

    def atScanEnd(self):
        return

    def getPosition(self):
        return float(self.ch.caget()) * 0.4

    def asynchronousMoveTo(self, newpos):
        self.ch.caput(newpos / 0.4)
        sleep(0.5)
        return None

    def isBusy(self):
        return False
Example #3
0
class BeamCurrent(ScannableMotionBase):
    def __init__(self, name):
        self.setName(name)
        self.setInputNames([])
        self.setExtraNames([])
        self.setOutputFormat([])
        self.setLevel(7)
        self.MinLevel = 1
        self.ricur = CAClient("SR21C-DI-DCCT-01:SIGNAL")
        self.ricur.configure()
        self.shutter = CAClient("FE05I-PS-SHTR-02:STA")
        self.shutter.configure()
        self.wasOff = False

    def isBusy(self):
        if float(self.ricur.caget()) < self.MinLevel:
            if self.wasOff == False:
                self.wasOff = True
            return True
        return False

    def getPosition(self):
        return None

    def asynchronousMoveTo(self, newPosition):
        self.MinLevel = newPosition
Example #4
0
class ScalerEpicsPVClass:
	def __init__(self, name, strPV, time):
		self.setName(name);
		self.setInputNames([])
		self.setExtraNames([name]);
#		self.setOutputFormat(['%d'])
		self.setLevel(3)
		self.chTP=CAClient(strPV+'.TP')
		self.chCNT=CAClient(strPV+'.CNT')
		self.chFREQ=CAClient(strPV+'.FREQ')
		
		for n in range(64):
			self.chScalerValue[n]=CAClient(strPV+'.S' + n)
			#self.chPreset[n]= CAClient(strPV+'.PR' + n)

	def atScanStart(self):
		if not self.cli.isConfigured():
			self.cli.configure()

	def getPosition(self):
		return float(0)

	def asynchronousMoveTo(self,new_position):
		np = new_position;
		try:
			if self.chCNT.isConfigured():
				self.chCNT.caput(np)
			else:
				self.chCNT.configure()
				self.chCNT.caput(np)
				self.incli.clearup()	
		except Exception, e :
			print "error in asynchronousMoveTo"
			print e
Example #5
0
class EpicsReadWritePVClass(ScannableMotionBase):
	'''Create PD to display single EPICS PV'''
	def __init__(self, name, pvstring, unitstring, formatstring):
		self.setName(name);
		self.setInputNames([name])
		self.Units=[unitstring]
		self.setOutputFormat([formatstring])
		self.setLevel(8)
		self.outcli=CAClient(pvstring)

	def rawGetPosition(self):
		output=0.0
		try:
			if not self.outcli.isConfigured():
				self.outcli.configure()
			output=float(self.outcli.caget())
			output = self.getOutputFormat()[0] % output
			return float(output)
		except:
			print "Error returning position"
			return 0

	def rawAsynchronousMoveTo(self,position):
		self.new_position=position	# need this attribute for some other classes
		try:
			if self.outcli.isConfigured():
				self.outcli.caput(position)
			else:
				self.outcli.configure()
				self.outcli.caput(position)
		except:
			print "error moving to position %f" % float(position)

	def rawIsBusy(self):
		return 0
Example #6
0
def sample_stage_home():
    if is_live():
        print('Homing sample stage')
        caClient = CAClient()
        try:
            caClient.configure()
            caClient.caput('BL08I-EA-TABLE-01:HM:HMGRP', 'All', 1)
            caClient.caput('BL08I-EA-TABLE-01:HM:HOME', 1, 30)
        finally:
            caClient.clearup()
    else:
        print('Homing sample stage (dummy)')
        SampleX.getMotor().home()
        SampleY.getMotor().home()
        SampleX_coarse.getMotor().home()
        SampleY_coarse.getMotor().home()
        SampleX_fine.getMotor().home()
        SampleY_fine.getMotor().home()

        SampleX.waitWhileBusy()
        SampleY.waitWhileBusy()
        SampleX_coarse.waitWhileBusy()
        SampleY_coarse.waitWhileBusy()
        SampleX_fine.waitWhileBusy()
        SampleY_fine.waitWhileBusy()

    print('Finished homing sample stage')
Example #7
0
class EpicsSetGetClass(ScannableMotionBase):
    '''Create PD for single EPICS positioner'''
    def __init__(self, name, pvinstring, pvoutstring, unitstring,
                 formatstring):
        self.setName(name)
        self.setInputNames([name])
        self.Units = [unitstring]
        self.setOutputFormat([formatstring])
        self.setLevel(3)
        self.incli = CAClient(pvinstring)
        self.outcli = CAClient(pvoutstring)

    def getPosition(self):
        try:
            self.outcli.configure()
            output = float(self.outcli.caget())
            self.outcli.clearup()
            return output
        except:
            print "Error returning position"
            return 0

    def asynchronousMoveTo(self, new_position):
        try:
            self.incli.configure()
            self.incli.caput(new_position)
            self.incli.clearup()
        except:
            print "error moving to position"

    def isBusy(self):
        return 0
Example #8
0
class DisplayEpicsPVClass(ScannableMotionBase):
	'''Create PD to display single EPICS PV'''
	def __init__(self, name, pvstring, unitstring, formatstring):
		self.setName(name);
		self.setInputNames([name])
		self.Units=[unitstring]
		self.setOutputFormat([formatstring])
		self.setLevel(8)
		self.outcli=CAClient(pvstring)

	def rawGetPosition(self):
		output=0.0
		try:
			if not self.outcli.isConfigured():
				self.outcli.configure()
			output=float(self.outcli.caget())
			#print output
			#sleep(10)
			#self.outcli.clearup()
			output = self.getOutputFormat()[0] % output
			return float(output)
		except:
			print "Error returning position"
			return 0

	def rawAsynchronousMoveTo(self,position):
		return

	def rawIsBusy(self):
		return 0
Example #9
0
def caget(pvstring):
	'caget from Jython'
	cli=CAClient(pvstring)
	cli.configure()
	out=cli.caget()
	cli.clearup()
	return out
Example #10
0
class EnumPVScannable(ScannableMotionBase):
    '''
    support get and set a multiple values Enum PV. There is no wait or check on set a value to the PV.
    Once instantiated the object must be configured first before use
    '''
    def __init__(self, name, pv):
        '''
        Constructor
        '''
        self.setName(name)
        self.setInputNames([name])
        self.pvcli = CAClient(pv)
        self.availablePositions = []
        self.pvcli.configure()
        sleep(1)
        self.availablePositions = self.pvcli.cagetLables()

    def getPosition(self):
        return self.pvcli.caget()

    def asynchronousMoveTo(self, newpos):
        if newpos in self.availablePositions:
            self.pvcli.caput(self.availablePositions.index(newpos))
        else:
            raise Exception("Requested mode %s is not available in list %s" %
                            (newpos, self.availablePositions))

    def isBusy(self):
        return False

    def toFormattedString(self):
        return "%s: %s" % (self.getName(), self.getPosition())

    def __del__(self):
        self.pvcli.clearup()
Example #11
0
class WaveformCapturer(DetectorBase):
    '''
    read-only detector to capture a data array from specified PV
    '''
    def __init__(self, name, pvname):
        '''
        Constructor
        '''
        self.setName(name)
        self.pv=pvname
        self.caclient=CAClient(pvname)
        self.pointNumber=0
        
    def collectData(self):
        #read-only waveform does not need to be triggered
        pass
    
    def getStatus(self):
        #read-only waveform always available
        return 0
    
    def readout(self):
        try:
            if not self.caclient.isConfigured():
                self.caclient.configure()
                output=self.caclient.cagetArrayDouble()
                self.caclient.clearup()
            else:
                output=self.caclient.cagetArrayDouble()
            return self.writeDataToFile(output)
        except Exception, err:
            print "Error returning current position", err
            raise Exception
Example #12
0
class MonitorEpicsPVClass(ScannableMotionBase):
	def __init__(self, name, strPV, strUnit, strFormat):
		self.setName(name);
		self.setInputNames([])
		self.setExtraNames([name]);
		self.Units=[strUnit]
		self.setOutputFormat([strFormat])
		self.setLevel(3)
		self.cli=CAClient(strPV)

	def atScanStart(self):
		if not self.cli.isConfigured():
			self.cli.configure()

	def getPosition(self):
		if self.cli.isConfigured():
			return float(self.cli.caget())
		else:
			self.cli.configure()
			return float(self.cli.caget())

	def isBusy(self):
		return 0
	
	def atScanEnd(self):
		if self.cli.isConfigured():
			self.cli.clearup()
Example #13
0
def caget(pvstring):
    'caget from Jython'
    cli = CAClient(pvstring)
    cli.configure()
    out = cli.caget()
    cli.clearup()
    return out
class DisplayEpicsPVClass(ScannableBase):
    """Create PD to display single EPICS PV"""

    def __init__(self, name, pvstring, unitstring, formatstring):
        self.setName(name)
        self.setInputNames([])
        self.setExtraNames([name])
        self.Units = [unitstring]
        self.setOutputFormat([formatstring])
        self.setLevel(3)
        self.cli = CAClient(pvstring)

    def atStart(self):
        if not self.cli.isConfigured():
            self.cli.configure()

    def getPosition(self):
        if self.cli.isConfigured():
            return float(self.cli.caget())
        else:
            self.cli.configure()
            return float(self.cli.caget())
            self.cli.clearup()

    def isBusy(self):
        return 0

    def atEnd(self):
        if self.cli.isConfigured():
            self.cli.clearup()
Example #15
0
class BimorphVoltage(ScannableMotionBase):
    def __init__(self, name, pvName, unitstring, formatstring):
        self.setName(name)
        self.voltagePv = CAClient(pvName)
        self.Units = [unitstring]
        self.setOutputFormat([formatstring])

    def getPosition(self):
        try:
            if self.voltagePv.isConfigured():
                return float(self.voltagePv.caget())
            else:
                self.voltagePv.configure()
                return float(self.voltagePv.caget())
        except:
            print "Error getting position"

    def asynchronousMoveTo(self, new_position):
        self.currentposition = new_position
        try:
            if self.voltagePv.isConfigured():
                self.voltagePv.caput(new_position)
            else:
                self.voltagePv.configure()
                self.voltagePv.caput(new_position)
                self.voltagePv.clearup()
        except:
            print "Error in moveTo"

    def isBusy(self):
        return 0
Example #16
0
class HexapodAxis(PseudoDevice):
	'''scannable or pseudo device for an individual, single Hexapod axis, it takes 8 inputs in the following order:
		1. the name string of this object
		2. the PV string for input target value
		3. the PV string for read-back value
		4. the PV string that control or start the motion
		5. the positional tolerance within which the motor is treated as in-position
		6. the unit string used for the measurement, keyworded as 'unitstring'
		7. the format string for the return data, keyworded as 'formatstring'
		8. the hexapod controller instance
		
		for example,
			hpx=HexapodAxis('hpx', 'ME02P-MO-BASE-01:UCS_X','ME02P-MO-BASE-01:UCSXR', 'ME02P-MO-BASE-01:START.PROC', 0.01, 'mm', '%9.4f', hexapodController)
			
	'''
	def __init__(self, name, pvinstring, pvoutstring, pvctrlstring, tolerance=0.01, unitstring='mm', formatstring='%9.4f', controller=None):
		self.setName(name);
		self.setInputNames([name])
		self.Units=[unitstring]
		self.setOutputFormat([formatstring])
		self.setLevel(3)
		self.incli=CAClient(pvinstring)
		self.outcli=CAClient(pvoutstring)
		self.movecli=CAClient(pvctrlstring)
		self.lastpos=0.0
		self.currentpos=0.0
		self.targetpos=0.0
		self._tolerance=tolerance
		self.controller=controller

	def atScanStart(self):
		if not self.incli.isConfigured():
			self.incli.configured()
		if not self.outcli.isConfigured():
			self.outcli.configured()
		if not self.movecli.isConfigured():
			self.movecli.configured()

	def atScanEnd(self):
		if self.incli.isConfigured():
			self.incli.clearup()
		if self.outcli.isConfigured():
			self.outcli.clearup()
		if self.movecli.isConfigured():
			self.movecli.clearup()
			
	def rawGetPosition(self):
		try:
			if self.outcli.isConfigured():
				self.currentpos=float(self.outcli.caget())
			else:
				self.outcli.configure()
				self.currentpos=float(self.outcli.caget())
				self.outcli.clearup()
			return  self.currentpos
		except Exception, err:
			print "Error returning current position" + err
			return 0
Example #17
0
class DelayLineClass(ScannableMotionBase):
    '''Create PD for single EPICS positioner which respond only to set and get'''
    def __init__(self,
                 name,
                 pvinstring,
                 pvoutstring,
                 pvieos,
                 unitstring,
                 formatstring,
                 hlp=None):
        self.setName(name)
        if hlp is not None:
            self.__doc__ += '\nHelp specific to ' + self.name + ':\n' + hlp
        self.setInputNames([name])
        self.Units = [unitstring]
        self.setOutputFormat([formatstring])
        self.setLevel(5)
        self.incli = CAClient(pvinstring)
        self.incli.configure()
        self.outcli = CAClient(pvoutstring)
        self.outcli.configure()
        self.pvieos = pvieos
        self.verbose = False

    def getPosition(self):
        t = CAClient()
        t.caput(self.pvieos, "\r\n")
        sleep(1)
        self.incli.caput('DEL?')
        sleep(1)
        s = self.outcli.caget()
        if self.verbose:
            print "Return: " + s
            print

        counts = float(s.lstrip("?DEL\\n\\r"))
        return counts

    def asynchronousMoveTo(self, time):
        t3 = CAClient()
        t3.caput(self.pvieos, "\n")
        sleep(1)
        temp2 = "DEL " + str(time)
        if self.verbose:
            print temp2
        self.incli.caput(temp2)
        sleep(1)

    def isBusy(self):
        sleep(1)
        return False


#print "Colby delay line Stage delay created"
#exec("delay=None")
#delay=DelayLineClass('delay', 'BL06J-EA-USER-01:ASYN3.AOUT',
#    'BL06J-EA-USER-01:ASYN3.TINP', "BL06J-EA-USER-01:ASYN3.IEOS",
#    '%', '%.15f', 'GDA read of ITC T2')
class FunctionGenerator(ScannableMotionBase):
    
    def __init__(self, name):
        self.setName(name)
        num = int(name[-1])
        #EPICS PVs
        func="BL11I-EA-FGEN-0%d:FUNC" % num
        output="BL11I-EA-FGEN-0%d:OUT" % num
        freq="BL11I-EA-FGEN-0%d:FREQ" % num
        freqrbv="BL11I-EA-FGEN-0%d:FREQ:RBV" % num
        amp="BL11I-EA-FGEN-0%d:AMP" % num
        amprbv="BL11I-EA-FGEN-0%d:AMP:RBV" % num
        offset="BL11I-EA-FGEN-0%d:OFF" % num
        offsetrbv="BL11I-EA-FGEN-0%d:OFF:RBV" % num
        sym="BL11I-EA-FGEN-0%d:SYMM" % num
        symrbv="BL11I-EA-FGEN-0%d:SYMM:RBV" % num
        
        dutycyc="BL11I-EA-FGEN-0%d:DCYC" % num
        dutycycrbv="BL11I-EA-FGEN-0%d:DCYC:RBV" % num
        trigger="BL11I-EA-FGEN-0%d:TRIGSRC" % num
        burstmode="BL11I-EA-FGEN-0%d:BURSTMODE" % num
        burstncyc="BL11I-EA-FGEN-0%d:BURSTNCYC" % num
        burstncycrbv="BL11I-EA-FGEN-0%d:BURSTNCYC:RBV" % num
        burststate="BL11I-EA-FGEN-0%d:BURST" % num
        disable="BL11I-EA-FGEN-0%d:DISABLE" % num        
        
        self.setInputNames(["frequency","amplitude","shift","symmetry"])
        self.setExtraNames([])
        self.function=CAClient(func)
        self.output=CAClient(output)
        self.frequency=CAClient(freq)
        self.frequencyrbv=CAClient(freqrbv)
        self.amplitude=CAClient(amp)
        self.amplituderbv=CAClient(amprbv)
        self.shiftcli=CAClient(offset)
        self.shiftrbv=CAClient(offsetrbv)
        self.symmetry=CAClient(sym)
        self.symmetryrbv=CAClient(symrbv)
        self.dutycycle=CAClient(dutycyc)
        self.dutycyclerbv=CAClient(dutycycrbv)
        self.triggersrc=CAClient(trigger)
        self.burstmode=CAClient(burstmode)
        self.burstncyc=CAClient(burstncyc)
        self.burstncycrbv=CAClient(burstncycrbv)
        self.burststate=CAClient(burststate)
        self.disable=CAClient(disable)
        
    # function generator controls
    def setFunction(self, function):
        try:
            if not self.function.isConfigured():
                self.function.configure()
            self.function.caputWait(function)
        except FactoryException, e:
            print "create channel error (%s): %s" % (self.function.getChannel().getName(),e)
        except CAException, e:
            print "caput Error (%s): %s" % (self.function.getChannel().getName(),e)
class ADCChannel(ScannableMotionBase, MonitorListener):
    
    def __init__(self, name, pv):
        self.setName(name)
        self.setInputNames([])
        self.pvcli=CAClient(pv)
        self.nordcli=CAClient(pv+".NORD")
        self.monitoradded=False
        self.counter=0
        self.numberofgates=0
        self.numberofframes=0
        self.filename=None
        self.filenames=[]
        self.collectionNumber=0 #0 means no collectionNumber
        self.voltagesmonitor=None
        self.firstMonitor = True
        self.voltages = {}
        
    def resetCounter(self):
        self.counter=0
        
    def resetRepetition(self):
        self.collectionNumber=0
        
    def setCollectionNumber(self, num):
        self.collectionNumber=num
        
    def setNumberOfGates(self, num):
        self.numberofgates=num
        
    def setNumberOfFrames(self, num):
        self.numberofframes=num
        
    def getNumberOfGates(self):
        return self.numberofgates
    
    def getNumberOfFrames(self):
        return self.numberofframes
    
    def setFilename(self, filename):
        self.filename=filename
        
    def getFilename(self):
        return self.filename
    
    def getFilenames(self):
        return self.filenames
    
    def getValues(self):
        try:
            if not self.pvcli.isConfigured():
                self.pvcli.configure()
            return self.pvcli.cagetArrayDouble()
        except FactoryException, e:
            print "create channel error (%s): %s" % (self.pvcli.getChannel().getName(),e)
        except CAException, e:
            print "caput Error (%s): %s" % (self.pvcli.getChannel().getName(),e)
Example #20
0
def assignStruckChannel(channelNo, nameList, namespace):
	allNames = ''
	for name in nameList:
		namespace[name] = ScalerSubsetScannable(name,globals()['struck1'],[channelNo])
		allNames += name + '/'
	allNames = allNames[:-1]

	print "ch%i: %s" % (channelNo, allNames)
	cac = CAClient(ScalerSubsetScannable.struckRootPv+'SCALER.NM%i' % channelNo)
	cac.configure()
	cac.caput(allNames)
	cac.clearup()
class DataCapturer(ScannableMotionBase, MonitorListener):
    
    def __init__(self, name, adc, hv=adcppv, el=adcepv, gate=adcgatepv): 
        self.setName(name)
        self.setInputNames(["HV","Electrometer","gate"])
        self.hv=hv
        self.el=el
        self.gate=gate
        self.voltagecli=CAClient(hv)
        self.electrometercli=CAClient(el)
        self.gatecli=CAClient(gate)
        self.monitoradded=False
        self.filename=None
        self.voltagemonitor=None
        self.electrometermonitor=None
        self.gatemonitor=None
        self.firstMonitor = True
        self.data={hv:[],el:[],gate:[]}
        self.voltages = []      # for holding voltage data array
        self.electrometers=[]   # for holding electrometer data array
        self.gates=[]
        self.firstData = True
        self.updatecounter=0
        self.capturecounter=0
        self.adc=adc
    
    def reset(self):
        self.electrometers = []
        self.voltages = []
        self.gates=[]
        self.updatecounter=0
        self.capturecounter=0
        self.firstData = True
        self.adc.disable()
        self.data={self.hv:[],self.el:[],self.gate:[]}
        
    def setFilename(self, filename):
        self.filename=filename
        
    def getFilename(self):
        return self.filename
    
    def getElectrometer(self, num):
        ''' retrieve electrometer data from Keithley amplifier.
        '''
        try:
            if not self.electrometercli.isConfigured():
                self.electrometercli.configure()
            return self.electrometercli.cagetArrayDouble(num)
        except FactoryException, e:
            print "create channel error (%s): %s" % (self.electrometercli.getChannel().getName(),e)
        except CAException, e:
            print "caget Error (%s): %s" % (self.electrometercli.getChannel().getName(),e)
Example #22
0
	def initPVs(self):
		# make a hashtable of key:CAClient pairs for setting directional field strengths
		i06MagnetPvRoot = "BL06J-EA-MAG-01:"
		i06MagnetPvNames = ["X:DMD", "X:RBV", "Y:DMD", "Y:RBV", "Z:DMD", "Z:RBV", "RAMPSTATUS", "LIMITSTATUS", "MODE", "STARTRAMP.PROC"]
		self.pvs = {}
		for pvKey in i06MagnetPvNames:
			pvName = i06MagnetPvRoot + pvKey
			#print "pvName: " + pvName
			pv = CAClient(pvName)
			pv.configure()
			self.pvs[pvKey] = pv
		print "pvs: " + str(self.pvs)
Example #23
0
def restart_ioc():
    if is_live():
        print('Restarting the IOC')
        caClient = CAClient()
        try:
            caClient.configure()
            caClient.caput('BL08I-CS-RSTRT-01:PSC:RESTART', 1, 0)
        finally:
            caClient.clearup()
    else:
        print('Restarting the IOC (dummy mode)')
        time.sleep(2)

    print('IOC restarted')
Example #24
0
class PilatusThreshold(ScannableMotionBase):
    def __init__(self, name, pvbase):
        self.setName(name)
        self.waitstep = waitstep
        self.setInputNames([name])
        self.setExtraNames([])
        self.Units = ['keV']
        self.setOutputFormat(['%4.2f'])
        self.setLevel(7)
        self.timer = tictoc()
        self.waitUntilTime = 0
        self.demand = 0.0
        self.gain = CAClient(pvbase + ":GainMenu")
        self.thres = CAClient(pvbase + ":ThresholdEnergy")
        self.gain.configure()
        self.thres.configure()
        self.gainranges = {0: [6.5, 19.7], 1: [4.4, 14.0], 2: [3.8, 11.4]}
        self.thresholdtolerance = 0.1
        self.waittime = 30

    def rawGetPosition(self):
        return [self.thres.caget() * 2.0]

    def rawAsynchronousMoveTo(self, newpos):
        gain = int(self.gain.caget())
        if newpos >= self.gainranges[gain][0] and newpos <= self.gainranges[
                gain][1]:
            # gain ok
            pass
        else:
            for i in self.gainranges.keys():
                if newpos >= self.gainranges[i][
                        0] and newpos <= self.gainranges[i][1]:
                    self.gain.caput(i)
                    self.timer.reset()
                    break
            # raise exception, value out of range
        thres = self.thres.caget()
        if abs((thres * 2.0) - newpos) < newpos * self.thresholdtolerance:
            # threshold ok
            pass
        else:
            self.thres.caput(newpos / 2.0)
            self.timer.reset()

    def isBusy(self):
        return (self.timer() < self.waittime)
Example #25
0
class SingleEpicsPositionerClass(ScannableMotionBase):
	'''Create PD for single EPICS positioner'''
	def __init__(self, name, pvinstring, pvoutstring, pvstatestring, pvstopstring, unitstring, formatstring):
		self.setName(name);
		self.setInputNames([name])
		self.Units=[unitstring]
		self.setOutputFormat([formatstring])
		self.setLevel(3)
		self.incli=CAClient(pvinstring)
		self.outcli=CAClient(pvoutstring)
		self.statecli=CAClient(pvstatestring)
		self.stopcli=CAClient(pvstopstring)

	def rawGetPosition(self):
		output=0.0
		try:
			if not self.outcli.isConfigured():
				self.outcli.configure()
			output=float(self.outcli.caget())
			#self.outcli.clearup()
			return float(output)
		except:
			print "Error returning position"
			return 0

	def rawAsynchronousMoveTo(self,new_position):
		try:
			if self.incli.isConfigured():
				self.incli.caput(new_position)
			else:
				self.incli.configure()
				self.incli.caput(new_position)
				#self.incli.clearup()
		except:
			print "error moving to position"

	def rawIsBusy(self):
		try:
			if self.statecli.isConfigured():
				self.status = self.statecli.caget()
			else:
				self.statecli.configure()
				self.status=self.statecli.caget()
				#self.statecli.clearup()
			return not int(self.status)
		except:	
			print "problem with isMoving string: "+self.status+": Returning busy status"
			return 1
	
	def stop(self):
		print "calling stop"
		if self.stopcli.isConfigured():
			self.stopcli.caput(1)
		else:
			self.stopcli.configure()
			self.stopcli.caput(1)
Example #26
0
class LaserMotorClass(ScannableMotionBase):
	'''Create PD for single EPICS positioner which respond only to set and get'''
	def __init__(self, name, pvinstring, pvoutstring, unitstring, formatstring,help=None):
		self.setName(name);
		if help is not None: self.__doc__+='\nHelp specific to '+self.name+':\n'+help
		self.setInputNames([name])
		self.Units=[unitstring]
		self.setOutputFormat([formatstring])
		self.setLevel(5)
		self.incli=CAClient(pvinstring)
		self.incli.configure()
		self.outcli=CAClient(pvoutstring)
		self.outcli.configure()
		
	def getPosition(self):
		self.incli.caput('TP')
		sleep(0.5)
		s=self.outcli.caget()
		#print "getPos: " + s
		c=299792548;
		a=250*pow(12.0/28.0,4);
		counts = float(s[s.find(':')+1:len(s)])
		time = -1000*counts*2*a/c
		return time

	def asynchronousMoveTo(self,time):
		c=299792548;
		a=250*pow(12.0/28.0,4);
		counts= -round(c*time/(2*a)*0.001);
		temp=str(int(counts));
		temp2="MA" + temp;
		#print temp2
		self.incli.caput(temp2)
		sleep(0.5)

	def isBusy(self):
		self.incli.caput('TE')
		sleep(0.5)
		s=self.outcli.caget()
		#print "isBusy: " + s
		sleep(0.5)
		return abs(float(s[s.find(':')+1:len(s)])) > 150

	def zero(self):
		self.incli.caput('DH') 
Example #27
0
class PositionerPVClass(ScannableMotionBase):
    def __init__(self, name, strPV):
        self.setName(name)
        self.setInputNames([])
        self.setExtraNames([name])
        #		self.Units=[strUnit];
        self.setLevel(7)
        self.setOutputFormat(["%20.12f"])
        self.ch = CAClient(strPV)

#		self.setTimePreset(time)

    def atScanStart(self):
        if not self.ch.isConfigured():
            self.ch.configure()

    #Scannable Implementations
    def getPosition(self):
        return self.getCount()

    def asynchronousMoveTo(self, newPos):
        self.setCollectionTime(newPos)
        self.collectData()

    def isBusy(self):
        return False

    def atScanEnd(self):
        if self.ch.isConfigured():
            self.chTP.clearup()

    def getCount(self):
        if self.chSn.isConfigured():
            output = self.chSn.caget()
        else:
            self.chSn.configure()
            output = self.chSn.caget()
            self.chSn.clearup()
        return float(output)

    def toString(self):
        ss = self.getName() + " :  " + str(self.getPosition())
        return ss
Example #28
0
class SingleEpicsPositionerClass(ScannableBase):
    '''Create PD for single EPICS positioner'''
    def __init__(self, name, pvinstring, pvoutstring, pvstatestring,
                 pvstopstring, unitstring, formatstring):
        self.setName(name)
        self.setInputNames([name])
        self.setExtraNames([name])
        self.Units = [unitstring]
        self.setOutputFormat([formatstring])
        self.setLevel(3)
        self.incli = CAClient(pvinstring)
        self.outcli = CAClient(pvoutstring)
        self.statecli = CAClient(pvstatestring)
        self.stopcli = CAClient(pvstopstring)

    def atStart(self):
        if not self.incli.isConfigured():
            self.incli.configure()
        if not self.outcli.isConfigured():
            self.outcli.configure()
        if not self.statecli.isConfigured():
            self.statecli.configure()
        if not self.stopcli.isConfigured():
            self.stopcli.configure()

    def getPosition(self):
        output = 99
        try:
            if self.outcli.isConfigured():
                #			if not isinstance(self.outcli.caget(),type(None)):
                #			print self.outcli.caget()
                return float(self.outcli.caget())
            else:
                self.outcli.configure()

                output = self.outcli.caget()
                if output == None:
                    raise Exception, "null pointer exception in getPosition"
                self.outcli.clearup()
                return float(output)
        except Exception, e:
            print "error in getPosition", e.getMessage(), e, output
            raise e
class SingleEpicsPositionerClass(ScannableBase):
    """Create PD for single EPICS positioner"""

    def __init__(self, name, pvinstring, pvoutstring, pvstatestring, pvstopstring, unitstring, formatstring):
        self.setName(name)
        self.setInputNames([name])
        self.setExtraNames([name])
        self.Units = [unitstring]
        self.setOutputFormat([formatstring])
        self.setLevel(3)
        self.incli = CAClient(pvinstring)
        self.outcli = CAClient(pvoutstring)
        self.statecli = CAClient(pvstatestring)
        self.stopcli = CAClient(pvstopstring)

    def atStart(self):
        if not self.incli.isConfigured():
            self.incli.configure()
        if not self.outcli.isConfigured():
            self.outcli.configure()
        if not self.statecli.isConfigured():
            self.statecli.configure()
        if not self.stopcli.isConfigured():
            self.stopcli.configure()

    def getPosition(self):
        output = 99
        try:
            if self.outcli.isConfigured():
                # 			if not isinstance(self.outcli.caget(),type(None)):
                # 			print self.outcli.caget()
                return float(self.outcli.caget())
            else:
                self.outcli.configure()

                output = self.outcli.caget()
                if output == None:
                    raise Exception, "null pointer exception in getPosition"
                self.outcli.clearup()
                return float(output)
        except Exception, e:
            print "error in getPosition", e.getMessage(), e, output
            raise e
Example #30
0
class ScannableMotorEpicsPVClass(ScannableMotionBase):
	def __init__(self, name, strPV, strUnit, strFormat):
		self.setName(name);
		self.setInputNames([name])
		self.setExtraNames([name]);
		self.Units=[strUnit]
		self.setOutputFormat([strFormat])
		self.setLevel(3)
		self.incli=CAClient(strPV+'.VAL')
		self.outcli=CAClient(strPV+'.RBV')
		self.statecli=CAClient(strPV+'.DMOV')
		self.stopcli=CAClient(strPV+'.STOP')
		self.delayTime = 0;

	def setDelay(self, newDelay):
		self.delayTime = newDelay;

	def atScanStart(self):
		if not self.incli.isConfigured():
			self.incli.configure()
		if not self.outcli.isConfigured():
			self.outcli.configure()
		if not self.statecli.isConfigured():
			self.statecli.configure()
		if not self.stopcli.isConfigured():
			self.stopcli.configure()

	def getPosition(self):
		output = 99
		try:
			if self.outcli.isConfigured():
				return float(self.outcli.caget())
			else:
				self.outcli.configure()
				
				output = self.outcli.caget()
				if output == None:
					raise Exception, "null pointer exception in getPosition"
				self.outcli.clearup()
				return float(output)
		except Exception,e :
			print "error in getPosition", e.getMessage(), e, e.class, output
Example #31
0
class EpicsMonitorClass(ScannableMotionBase):
    def __init__(self, name, strPV, strUnit, strFormat):
        self.setName(name)
        self.setInputNames([])
        self.setExtraNames([name])
        self.Units = [strUnit]
        self.setOutputFormat([strFormat])
        self.setLevel(7)
        self.cli = CAClient(strPV)
        self.cli.configure()

    def atScanStart(self):
        if not self.cli.isConfigured():
            self.cli.configure()

    def getPosition(self):
        try:
            if self.cli.isConfigured():
                return float(self.cli.caget())
            else:
                self.cli.configure()
                return float(self.cli.caget())
        except:
            print "Error getting position"

    def asynchronousMoveTo(self, new_position):
        pass

    def isBusy(self):
        return False
Example #32
0
class xmapcounter(ScannableMotionBase):
	def __init__(self, name, pv='ME13C-EA-DET-01:',formatstring='%6f'):
		self.setLevel(9)
		self.setOutputFormat([formatstring]*4)
		self.setName(name)	
		self.setInputNames([name])
		self.pvt=CAClient(pv+'EraseStart')
		self.rt=CAClient(pv+'PresetReal')
		self.rt.configure()
		self.pvt.configure()
		self.checkbusy=CAClient(pv+'ElapsedReal')
		self.checkbusy.configure()	
		self.setExtraNames(['xmroi1','xmroi2','xmroi3'])
		self.new_position=1


	def getPosition(self):
		w(.2)
		return [float(self.checkbusy.caget()),float(xmroi1.getPosition()),float(xmroi2.getPosition()),float(xmroi3.getPosition())]

	def asynchronousMoveTo(self,new_position):
		self.new_position=new_position
		self.rt.caput(self.new_position)
		self.pvt.caput(1)
		w(new_position+.5)

#
	def isBusy(self):
		while self.checkbusy.caget()<self.new_position:
			w(0.1)
			return 1
		else:
			return 0
Example #33
0
class HexapodAxisStatus(object):
    '''Hexapod axis status class implementing position-compare algorithm with tolerance input. isBusy() method should be used to query the motion status of this axis.'''
    def __init__(self, name, pvinstring, pvoutstring, tolerance=0.01):
        self.name = name
        self.incli = CAClient(pvinstring)
        self.outcli = CAClient(pvoutstring)
        self.currentpos = 0.0
        self.targetpos = 0.0
        self._tolerance = tolerance

    def getCurrentPosition(self):
        try:
            if self.outcli.isConfigured():
                self.currentpos = float(self.outcli.caget())
            else:
                self.outcli.configure()
                self.currentpos = float(self.outcli.caget())
                self.outcli.clearup()
            return self.currentpos
        except Exception, err:
            print "Error returning current position of " + self.name + err
            return 0
Example #34
0
class DisplayEpicsPVClass(ScannableMotionBase):
    '''Create PD to display single EPICS PV'''
    def __init__(self, name, pvstring, unitstring, formatstring):
        self.setName(name)
        self.setInputNames([name])
        self.Units = [unitstring]
        self.setOutputFormat([formatstring])
        self.setLevel(8)
        self.outcli = CAClient(pvstring)

    def getPosition(self):
        self.outcli.configure()
        output = float(self.outcli.caget())
        output = self.getOutputFormat()[0] % output
        self.outcli.clearup()
        return float(output)

    def asynchronousMoveTo(self, position):
        return

    def isBusy(self):
        return 0
class DoseControl(MonitorListener):
    
    def __init__(self, name,pv):
        self.name=name
        self.currentpressure=0.0
        self.outcli=CAClient(pv)
        self.outcli.configure()
        sleep(1)
        self.monitor=self.outcli.camonitor(self)
        
    def waitForGreaterThan(self, target):
        while (self.getCurrentPressure() <= target):
            sleep(0.1)
        
    def getCurrentPressure(self):
        return self.currentpressure
    
    def setSystemPressure(self, sysP,target,flow):
        #SET STARTING SAMPLE PRESSURE
        caput("BL11I-EA-GIR-01:DVPC:SETPOINT:WR", sysP)
        caput("BL11I-EA-GIR-01:MFC1:SETPOINT:WR", flow)
        caput("BL11I-EA-GIR-01:BPR:SETPOINT:WR", target)
        self.waitForGreaterThan(target)
        caput("BL11I-EA-GIR-01:MFC1:SETPOINT:WR", 0)
    
    def setSamplePressure(self,SampleP, target, increment):
        # SET FINAL SAMPLE PRESSURE AND INCREMENTS
        while SampleP <= target:                                #final sample pressure in bar
            SampleP += increment                      #increments in bar
            caput("BL11I-EA-GIR-01:DVPC:SETPOINT:WR", SampleP)
            sleep(5)                      #wait time in seconds

    def monitorChanged(self, mevent):
        try:
            self.currentpressure = float(mevent.getDBR().getDoubleValue()[0])
        except:
            #do nothing
            print
            
Example #36
0
	def initOtherMagnetPVs(self):
		# make a hashtable of key:CAClient pairs for other magnet-related detectors
		otherMagnetPvsData = [["Magnet temperature 1", "TMON.T1", "BL06J-EA-TMON-01:T1", "true"],
							  ["Magnet temperature 2", "TMON.T2", "BL06J-EA-TMON-01:T2", "true"],
							  ["Magnet temperature 3", "TMON.T3", "BL06J-EA-TMON-01:T3", "true"],
							  ["Nitrogen Level", "TMON.NL", "BL06J-EA-TMON-01:NL", "true"],
							  ["Cryostat temp", "TCTRL.T1", "BL06J-EA-TCTRL-01:STS:T1", "true"],
							  ["VTI setpoint demand", "VTI.SETPOINT-DMD", "BL06J-EA-TCTRL-01:DMD:LOOP1:SETPOINT", "false"],
							  ["VTI setpoint readback", "VTI.SETPOINT-RBV", "BL06J-EA-TCTRL-01:STS:LOOP1:SETPOINT", "true"],
							  ["Needle valve manual control demand", "NVALV.MANUAL-DMD", "BL06J-EA-TCTRL-01:DMD:LOOP2:MANUAL", "false"],
							  ["Needle valve manual control readback", "NVALV.MANUAL-RBV", "BL06J-EA-TCTRL-01:STS:LOOP2:MANUAL", "true"],
							  ["Helium Depth Indicator current level (mm)", "HDI.LEVEL", "BL06J-EA-HDI-01:LEVEL", "true"],
							  ["Helium Depth Indicator pump control", "HDI.PUMP", "BL06J-EA-HDI-01:PUMP", "false"],
							  ]
		self.otherPvs = {}
		for otherMagnetPv in otherMagnetPvsData:
			pvKey = otherMagnetPv[1]
			pvValue = otherMagnetPv[2];
			pv = CAClient(pvValue)
			pv.configure()
			self.otherPvs[pvKey] = pv		
		print "otherPvs: " + str(self.otherPvs)
Example #37
0
class HexapodAxisStatus(object):
	'''Hexapod axis status class implementing position-compare algorithm with tolerance input. isBusy() method should be used to query the motion status of this axis.'''
	def __init__(self, name, pvinstring, pvoutstring, tolerance=0.01):
		self.name=name
		self.incli=CAClient(pvinstring)
		self.outcli=CAClient(pvoutstring)
		self.currentpos=0.0
		self.targetpos=0.0
		self._tolerance=tolerance

	def getCurrentPosition(self):
		try:
			if self.outcli.isConfigured():
				self.currentpos=float(self.outcli.caget())
			else:
				self.outcli.configure()
				self.currentpos=float(self.outcli.caget())
				self.outcli.clearup()
			return  self.currentpos
		except Exception, err:
			print "Error returning current position of " + self.name + err
			return 0
class PVWithSeparateReadbackAndToleranceScannable(ScannableBase):

    def __init__(self, name, pv_set, pv_read, timeout, tolerance = 0.0005): #BL16B-EA-PSU-01
        self.name = name
        self.inputNames = [name]
        self.outputFormat = ['%6.4f']

        self.timeout = timeout
        self.tol = tolerance
        self._time_triggered = None
        self._last_target = None
        self._pv_set = CAClient(pv_set)
        self._pv_read = CAClient(pv_read)
        self._pv_set.configure()
        self._pv_read.configure()

    def asynchronousMoveTo(self, value):
        self._pv_set.caput(value)
        self._time_triggered = time.time()
        self._last_target =  value
    
    def isBusy(self):
        
        if self._last_target == None:
            return False
        
        i = (float(self._pv_read.caget()))
        
        if abs(i - self._last_target) <= self.tol:
            return False
        
        if (time.time() - self._time_triggered) > self.timeout:
            raise Exception('Timed out after %fs setting current to %f. The current has hung at %f, and the voltage is %f\n*Is the voltage set too low?*' % ((self.timeout, self.last_target) + self.getPosition()))
        
        return True

    def getPosition(self):
        return float(self._pv_read.caget())
class AdcControl(ScannableMotionBase):
    
    def __init__(self, name):
        self.setName(name)
        num = int(name[-1])
        #EPICS PVs
        mode="BL11I-EA-ADC-0%d:MODE" % num
        rate="BL11I-EA-ADC-0%d:CLOCKRATE" % num
        enable="BL11I-EA-ADC-0%d:ENABLE" % num
        samples="BL11I-EA-ADC-0%d:SAMPLES:OUT" % num
        clock="BL11I-EA-ADC-0%d:EXTCLOCK" % num
        reenable="BL11I-EA-ADC-0%d:REENABLE" % num
        offset="BL11I-EA-ADC-0%d:OFFSET:OUT" % num
        average="BL11I-EA-ADC-0%d:AVERAGE:OUT" % num
        softtrig="BL11I-EA-ADC-0%d:SOFTTRIGGER.VAL" % num

        self.setInputNames(["ADC Mode","Clock Rate","Enable","Samples"])
        self.setExtraNames([])
        self.setOutputFormat(["%s","%s","%s","%d"])
        self.mode=CAClient(mode)
        self.rate=CAClient(rate)
        self.enableField=CAClient(enable)
        self.samples=CAClient(samples)
        self.clock=CAClient(clock)
        self.reenable=CAClient(reenable)
        self.adcoffset=CAClient(offset)
        self.average=CAClient(average)
        self.softtrig=CAClient(softtrig)
        
    def continuousMode(self):
        try:
            if not self.mode.isConfigured():
                self.mode.configure()
            self.mode.caput(0)
        except FactoryException, e:
            print "create channel error (%s): %s" % (self.mode.getChannel().getName(),e)
        except CAException, e:
            print "caput Error (%s): %s" % (self.mode.getChannel().getName(),e)
Example #40
0
class SingleChannelBimorphClass(ScannableMotionBase):
    '''Create PD for single EPICS Bimorph channel'''
    def __init__(self, name, pvinstring, pvoutstring, pvstatestring,
                 unitstring, formatstring):
        self.setName(name)
        self.setInputNames([name])
        #               self.setExtraNames([name]);
        self.Units = [unitstring]
        self.setOutputFormat([formatstring])
        self.setLevel(3)
        self.incli = CAClient(pvinstring)
        self.outcli = CAClient(pvoutstring)
        self.statecli = CAClient(pvstatestring)

    def atStart(self):
        if not self.incli.isConfigured():
            self.incli.configured()
        if not self.outcli.isConfigured():
            self.outcli.configured()
        if not self.statecli.isConfigured():
            self.statecli.configured()

    def getPosition(self):
        try:
            if self.outcli.isConfigured():
                output = float(self.outcli.caget())
            else:
                self.outcli.configure()
                output = float(self.outcli.caget())
                self.outcli.clearup()
            return output
        except:
            print "Error returning position"
            return 0

    def asynchronousMoveTo(self, new_position):
        try:
            if self.incli.isConfigured():
                self.incli.caput(new_position)
            else:
                self.incli.configure()
                self.incli.caput(new_position)
                self.incli.clearup()
        except:
            print "error moving to position"

    def isBusy(self):
        try:
            if self.statecli.isConfigured():
                self.status = self.statecli.caget()
            else:
                self.statecli.configure()
                self.status = self.statecli.caget()
                self.statecli.clearup()
            return int(self.status)
        except:
            print "problem with isMoving string: " + self.status + ": Returning busy status"
            return 1
class EventReceiver(ScannableMotionBase):
    
    def __init__(self, name, delay=evrdelaypv, delayrbv=evrdelayrbv, width=evrwidthpv, widthrbv=evrwidthrbv, enable=evrenablepv, polarity=evrpolaritypv):
        self.setName(name)
        self.setInputNames(["delay", "width"])
        self.setExtraNames([])
        self.delay=CAClient(delay)
        self.delayrbv=CAClient(delayrbv)
        self.width=CAClient(width)
        self.widthrbv=CAClient(widthrbv)
        self._enable=CAClient(enable)
        self.polarity=CAClient(polarity)
    
    # function generator controls
    def enableField(self):
        try:
            if not self._enable.isConfigured():
                self._enable.configure()
            self._enable.caput(1)
        except FactoryException, e:
            print "create channel error (%s): %s" % (self._enable.getChannel().getName(),e)
        except CAException, e:
            print "caput Error (%s): %s" % (self._enable.getChannel().getName(),e)
Example #42
0
class GasRigClass(ScannableMotionBase):
    '''Create a scannable for a gas injection rig'''
    def __init__(self, name, rootPV):
        self.setName(name);
        self.setInputNames([name])
        self.setLevel(3)
        self.setsequencecli=CAClient(rootPV+SEQUENCE_CONTROL)
        self.statecli=CAClient(rootPV+SEQUENCE_STATUS)
        self.atpressurecli=CAClient(rootPV+AT_PRESSURE_PROC)
        
    def getState(self):
        try:
            if not self.statecli.isConfigured():
                self.statecli.configure()
                output=int(self.statecli.caget())
                self.statecli.clearup()
            else:
                output=int(self.statecli.caget())
            return sequence[output]
        except:
            print "Error returning current state"
            return 0

    def setSequence(self,new_position):
        try:
            if not self.setsequencecli.isConfigured():
                self.setsequencecli.configure()
                self.setsequencecli.caput(new_position)
                self.setsequencecli.clearup()
            else:
                self.setsequencecli.caput(new_position)
        except:
            print "error setting sequence"

    def atPressure(self):
        try:
            if not self.atpressurecli.isConfigured():
                self.atpressurecli.configure()
                self.atpressurecli.caput(1)
                self.atpressurecli.clearup()
            else:
                self.atpressurecli.caput(1)
        except:
            print "error setting at_pressure"
Example #43
0
class GasRigClass(ScannableMotionBase):
    '''Create a scannable for a gas injection rig'''
    def __init__(self, name, rootPV):
        self.setName(name);
        self.setInputNames([name])
        self.setLevel(5)
        self.setsequencecli=CAClient(rootPV+SEQUENCE_CONTROL)
        self.statecli=CAClient(rootPV+SEQUENCE_STATUS)
        self.systemincli=CAClient(SystemTargetPressure)
        self.sampleincli=CAClient(SampleTargetPressure)
        
    def vacSample(self, samplePressure=dvpc):
        print "Vacuum the sample ..."
        samplePressure.setMode(0)
        self.on()
        increment=0.005
        target=float(samplePressure.getPosition())-increment
        try:
            if not self.sampleincli.isConfigured():
                self.sampleincli.configure()
            while float(samplePressure.getPosition()) > target:  # final sample pressure in bar
#                 interruptable()
                self.sampleincli.caput(target)
                target = target-increment  # increments in bar
                sleep(5.0)  # wait time in seconds
                if target<=0.0:
                    break
            if self.sampleincli.isConfigured():
                self.sampleincli.clearup()
        except:
            print "error moving to position"
        samplePressure.moveTo(0.0)
        print "sample is under vacuum now."
        
    def vacSystem(self, systemPressure=bpr):
        print "Vacuum the system ..."
        systemPressure.setMode(0)
        self.on()
        increment=0.005
        target=float(systemPressure.getPosition())-increment
        try:
            if not self.systemincli.isConfigured():
                self.systemincli.configure()
            while target > 0:  
#                 interruptable()
                self.systemincli.caput(target)
                target = target-increment  # increments in bar
                sleep(5.0)  # wait time in seconds
            if self.systemincli.isConfigured():
                self.systemincli.clearup()
        except:
            print "error moving to position"
        systemPressure.moveTo(0.0)
        print "system is under vacuum now."

    def gasin(self, mfc=mfc1, flow=0.1, pressuretarget=1.0, systemPressure=bpr):
        '''select gas flow control and set system pressure'''
        print "inject gas %s into the system." % (mfc.getGasType())
        mfc.asynchronousMoveTo(flow)
        sleep(1)
        systemPressure.moveTo(pressuretarget)
        sleep(1)
        mfc.asynchronousMoveTo(0)
        print "The system reaches at target pressure %f" % (pressuretarget)
        
    def complete(self,valve=ventvalve,systemPressure=bpr, samplePressure=sampleP):
        print "complete this sample, vent the system"
        self.off()
        valve.on()
        systemPressure.asynchronousMoveTo(0)
        samplePressure.asynchronousMoveTo(0)
        mfc1.asynchronousMoveTo(0)
        mfc2.asynchronousMoveTo(0)
        mfc3.asynchronousMoveTo(0)
        
    def flushSystem(self,repeat, mfc=mfc1, flow=0.5, duration=60.0, isolation=isolationvalve, vent=ventvalve, systemPressure=bpr):
        print "flushing the system for "+str(duration)+" seconds for "+ str(repeat)+ " times ..."
        isolation.off()
        vent.on()
        for i in range(repeat):
            mfc.asynchronousMoveTo(flow)
            sleep(1)
            systemPressure.moveTo(4)
            sleep(1)
            mfc.asynchronousMoveTo(0)
            sleep(duration)
            systemPressure.asynchronousMoveTo(0)
            sleep(10.0)
        print "flush system completed."

    def getState(self):
        try:
            if not self.statecli.isConfigured():
                self.statecli.configure()
                output=int(self.statecli.caget())
                self.statecli.clearup()
            else:
                output=int(self.statecli.caget())
            return sequencestat[output]
        except:
            print "Error returning current state"
            return 0

    def setSequence(self,new_position):
        try:
            if not self.setsequencecli.isConfigured():
                self.setsequencecli.configure()
                self.setsequencecli.caput(new_position)
                self.setsequencecli.clearup()
            else:
                self.setsequencecli.caput(new_position)
        except:
            print "error setting sequence"
            
    def on(self):
        self.setSequence(0)
        
    def off(self):
        self.setSequence(1)
        
    def reset(self):
        self.setSequence(2)
        
#### methods for scannable 
    def getPosition(self):
        return self.getState()
    
    def asynchronousMoveTo(self, new_position):
        self.setSequence(float(new_position))

    def isBusy(self):
        return False

    def atScanStart(self):
        pass
    def atPointStart(self):
        pass
    def stop(self):
        pass
    def atPointEnd(self):
        pass
    def atScanEnd(self):
        pass
    
#gasrig=GasRigClass("gasrig", "BL11I-EA-GIR-01:")
    def xgasin(self, mfc=mfc1, flow=0.1, pressuretarget=1.0, systemPressure=bpr, sleepdelta=1, sleepmove=0.5):
        '''select gas flow control and set system pressure'''
        print "xgasin: inject gas %s into the system." % (mfc.getGasType())
        mfc.asynchronousMoveTo(flow)
        #systemPressure.moveTo(pressuretarget)
        sleep(sleepdelta)
        systemPressure.moveTo(pressuretarget, sleepmove)
        #mfc.asynchronousMoveTo(flow)
        sleep(sleepdelta)
        mfc.asynchronousMoveTo(0)
        print "The system reaches at target pressure %f" % (pressuretarget)
class AlicatPressureController(ScannableMotionBase):
    '''
    construct a scannable for pressure control. It also provides access to other properties.
    '''
    def __init__(self,name, rootPV, tolerance=0.01, formatstring="%.3f"):
        '''
        Constructor
        '''
        self.setName(name)
        self.setInputNames([name])
        self.setOutputFormat([formatstring])
        self.setLevel(3)
        self.readmodecli=CAClient(rootPV+READ_MODE)
        self.setmodecli=CAClient(rootPV+SET_MODE)
        self.readpressurecli=CAClient(rootPV+READ_PRESSURE)
        self.settargetcli=CAClient(rootPV+SET_TARGET)
        self.readtargetcli=CAClient(rootPV+READ_TARGET)
        self.setproportionalgaincli=CAClient(rootPV+SET_PROPORTIONAL_GAIN)
        self.readproportionalgaincli=CAClient(rootPV+READ_PROPORTIONAL_GAIN)
        self.setderivativegaincli=CAClient(rootPV+SET_DERIVATIVE_GAIN)
        self.readderivativegaincli=CAClient(rootPV+READ_DERIVATIVE_GAIN)
        self.mytolerance=tolerance
        self.isConfigured=False
        
    def configure(self):
        if not self.isConfigured:
            if not self.readmodecli.isConfigured():
                self.readmodecli.configure()
            if not self.setmodecli.isConfigured():
                self.setmodecli.configure()
            if not self.settargetcli.isConfigured():
                self.settargetcli.configure()
            if not self.readtargetcli.isConfigured():
                self.readtargetcli.configure()
            if not self.readpressurecli.isConfigured():
                self.readpressurecli.configure()
            self.isConfigured=True
            
    def deconfigure(self):
        if self.isConfigured:
            if self.readmodecli.isConfigured():
                self.readmodecli.clearup()
            if self.setmodecli.isConfigured():
                self.setmodecli.clearup()
            if self.settargetcli.isConfigured():
                self.settargetcli.clearup()
            if self.readtargetcli.isConfigured():
                self.readtargetcli.clearup()
            if self.readpressurecli.isConfigured():
                self.readpressurecli.clearup()
            self.isConfigured=False
            
    def getMode(self):
        try:
            if not self.readmodecli.isConfigured():
                self.readmodecli.configure()
                output=int(self.readmodecli.caget())
                self.readmodecli.clearup()
            else:
                output=int(self.readmodecli.caget())
            return modes[output]
        except:
            print "Error returning current mode"
            return 0

    def setMode(self, mode):
        try:
            if not self.setmodecli.isConfigured():
                self.setmodecli.configure()
                self.setmodecli.caput(mode)
                self.setmodecli.clearup()
            else:
                self.setmodecli.caput(mode)
        except:
            print "error set to mode"

    def setTarget(self, target):
        try:
            if not self.settargetcli.isConfigured():
                self.settargetcli.configure()
                self.settargetcli.caput(target)
                self.settargetcli.clearup()
            else:
                self.settargetcli.caput(target)
        except:
            print "error set to target flow value"

    def getTarget(self):
        try:
            if not self.settargetcli.isConfigured():
                self.settargetcli.configure()
                output=float(self.settargetcli.caget())
                self.settargetcli.clearup()
            else:
                output=float(self.settargetcli.caget())
            return output
        except:
            print "Error returning target value"
            return 0

    def getPressure(self):
        try:
            if not self.readpressurecli.isConfigured():
                self.readpressurecli.configure()
                output=float(self.readpressurecli.caget())
                self.readpressurecli.clearup()
            else:
                output=float(self.readpressurecli.caget())
            return output
        except:
            print "Error returning pressure"
            return 0
        
    def getProportionalGain(self):
        try:
            if not self.readproportionalgaincli.isConfigured():
                self.readproportionalgaincli.configure()
                output=float(self.readproportionalgaincli.caget())
                self.readproportionalgaincli.clearup()
            else:
                output=float(self.readproportionalgaincli.caget())
            return output
        except:
            print "Error returning Proportional Gain"
            return 0

    def setProportionalGain(self, gain):
        try:
            if not self.setproportionalgaincli.isConfigured():
                self.setproportionalgaincli.configure()
                self.setproportionalgaincli.caput(gain)
                self.setproportionalgaincli.clearup()
            else:
                self.setproportionalgaincli.caput(gain)
        except:
            print "error set to proportional gain"

    def getDerivativeGain(self):
        try:
            if not self.readderivativegaincli.isConfigured():
                self.readderivativegaincli.configure()
                output=float(self.readderivativegaincli.caget())
                self.readderivativegaincli.clearup()
            else:
                output=float(self.readderivativegaincli.caget())
            return output
        except:
            print "Error returning Derivative Gain"
            return 0

    def setDerivativeGain(self, gain):
        try:
            if not self.setderivativegaincli.isConfigured():
                self.setderivativegaincli.configure()
                self.setderivativegaincli.caput(gain)
                self.setderivativegaincli.clearup()
            else:
                self.setderivativegaincli.caput(gain)
        except:
            print "error set to derivative gain"
            
            
    def getTolerance(self):
        return self.mytolerance
    
    def setTolerance(self, value):
        self.mytolerance=value

#### methods for scannable 
    def getPosition(self):
        return self.getPressure()
    
    def asynchronousMoveTo(self, posi):
        self.setTarget(float(posi))

    def moveTo(self, posi, sleepdelta=0.5):
        self.asynchronousMoveTo(posi)
        while self.isBusy():
            sleep(sleepdelta)

    def isBusy(self):
        return (abs(float(self.getPosition())-float(self.getTarget()))>float(self.getTolerance()))

    def atScanStart(self):
        pass
    def atPointStart(self):
        pass
    def stop(self):
        pass
    def atPointEnd(self):
        pass
    def atScanEnd(self):
        pass
class GasRigValveClass(ScannableMotionBase):
    '''Create a scannable for a gas injection rig'''
    def __init__(self, name, rootPV):
        self.setName(name);
        self.setInputNames([name])
        self.setLevel(5)
        self.controlcli=CAClient(rootPV+VALVE_CONTROL)
        self.statecli=CAClient(rootPV+VALVE_STATUS)
        self.modecli=CAClient(rootPV+VALVE_MODE)
        self.interlockscli=CAClient(rootPV+VALVE_INTERLOCKS)
        self.operationscli=CAClient(rootPV+VALVE_OPERATIONS)
        
    def getStatus(self):
        try:
            if not self.statecli.isConfigured():
                self.statecli.configure()
                output=int(self.statecli.caget())
                self.statecli.clearup()
            else:
                output=int(self.statecli.caget())
            return STATUS_SEQUENCE[output]
        except:
            print "Error returning current state"
            return 0
        
    def getMode(self):
        try:
            if not self.modecli.isConfigured():
                self.modecli.configure()
                output=int(self.modecli.caget())
                self.modecli.clearup()
            else:
                output=int(self.modecli.caget())
            return MODE_SEQUENCE[output]
        except:
            print "Error returning current state"
            return 0
        
    def getInterlocks(self):
        try:
            if not self.interlockscli.isConfigured():
                self.interlockscli.configure()
                output=int(self.interlockscli.caget())
                self.interlockscli.clearup()
            else:
                output=int(self.interlockscli.caget())
            return INTERLOCKS_SEQUENCE[output]
        except:
            print "Error returning current state"
            return 0

    def getOperations(self):
        try:
            if not self.operationscli.isConfigured():
                self.operationscli.configure()
                output=int(self.operationscli.caget())
                self.operationscli.clearup()
            else:
                output=int(self.operationscli.caget())
            return output
        except:
            print "Error returning current state"
            return 0

    def setControl(self,new_position):
        try:
            if not self.controlcli.isConfigured():
                self.controlcli.configure()
                self.controlcli.caput(new_position)
                self.controlcli.clearup()
            else:
                self.controlcli.caput(new_position)
        except:
            print "error setting sequence"
            
    def on(self):
        self.setControl(0)
        
    def off(self):
        self.setControl(1)
        
    def reset(self):
        self.setControl(2)
        
#### methods for scannable 
    def getPosition(self):
        return self.getStatus()
    
    def asynchronousMoveTo(self, new_position):
        self.setControl(float(new_position))

    def isBusy(self):
        return False

    def atScanStart(self):
        pass
    def atPointStart(self):
        pass
    def stop(self):
        pass
    def atPointEnd(self):
        pass
    def atScanEnd(self):
        pass
class AlicatPressureController(ScannableMotionBase):
    '''
    classdocs
    '''
    def __init__(self,name, rootPV, formatstring):
        '''
        Constructor
        '''
        self.setName(name);
        self.setInputNames([name])
        self.setOutputFormat([formatstring])
        self.setLevel(3)
        self.readmodecli=CAClient(rootPV+READ_MODE)
        self.setmodecli=CAClient(rootPV+SET_MODE)
        self.readpressurecli=CAClient(rootPV+READ_PRESSURE)
        self.settargetcli=CAClient(rootPV+SET_TARGET)
        self.readtargetcli=CAClient(rootPV+READ_TARGET)
        self.setproportionalgaincli=CAClient(rootPV+SET_PROPORTIONAL_GAIN)
        self.readproportionalgaincli=CAClient(rootPV+READ_PROPORTIONAL_GAIN)
        self.setderivativegaincli=CAClient(rootPV+SET_DERIVATIVE_GAIN)
        self.readderivativegaincli=CAClient(rootPV+READ_DERIVATIVE_GAIN)
        
    def getMode(self):
        try:
            if not self.readmodecli.isConfigured():
                self.readmodecli.configure()
                output=int(self.readmodecli.caget())
                self.readmodecli.clearup()
            else:
                output=int(self.readmodecli.caget())
            return modes[output]
        except:
            print "Error returning current mode"
            return 0

    def setMode(self, mode):
        try:
            if not self.setmodecli.isConfigured():
                self.setmodecli.configure()
                self.setmodecli.caput(mode)
                self.setmodecli.clearup()
            else:
                self.setmodecli.caput(mode)
        except:
            print "error set to mode"

    def setTarget(self, target):
        try:
            if not self.settargetcli.isConfigured():
                self.settargetcli.configure()
                self.settargetcli.caput(target)
                self.settargetcli.clearup()
            else:
                self.settargetcli.caput(target)
        except:
            print "error set to target flow value"

    def getTarget(self):
        try:
            if not self.readtargetcli.isConfigured():
                self.readtargetcli.configure()
                output=float(self.readtargetcli.caget())
                self.readtargetcli.clearup()
            else:
                output=float(self.readtargetcli.caget())
            return output
        except:
            print "Error returning flow target value"
            return 0

    def getPressure(self):
        try:
            if not self.readpressurecli.isConfigured():
                self.readpressurecli.configure()
                output=float(self.readpressurecli.caget())
                self.readpressurecli.clearup()
            else:
                output=float(self.readpressurecli.caget())
            return output
        except:
            print "Error returning pressure"
            return 0
        
    def getProportionalGain(self):
        try:
            if not self.readproportionalgaincli.isConfigured():
                self.readproportionalgaincli.configure()
                output=float(self.readproportionalgaincli.caget())
                self.readproportionalgaincli.clearup()
            else:
                output=float(self.readproportionalgaincli.caget())
            return output
        except:
            print "Error returning Proportional Gain"
            return 0

    def setProportionalGain(self, gain):
        try:
            if not self.setproportionalgaincli.isConfigured():
                self.setproportionalgaincli.configure()
                self.setproportionalgaincli.caput(gain)
                self.setproportionalgaincli.clearup()
            else:
                self.setproportionalgaincli.caput(gain)
        except:
            print "error set to proportional gain"

    def getDerivativeGain(self):
        try:
            if not self.readderivativegaincli.isConfigured():
                self.readderivativegaincli.configure()
                output=float(self.readderivativegaincli.caget())
                self.readderivativegaincli.clearup()
            else:
                output=float(self.readderivativegaincli.caget())
            return output
        except:
            print "Error returning Derivative Gain"
            return 0

    def setDerivativeGain(self, gain):
        try:
            if not self.setderivativegaincli.isConfigured():
                self.setderivativegaincli.configure()
                self.setderivativegaincli.caput(gain)
                self.setderivativegaincli.clearup()
            else:
                self.setderivativegaincli.caput(gain)
        except:
            print "error set to derivative gain"
            
            
#### methods for scannable 
    def atScanStart(self):
        pass
    def atPointStart(self):
        pass
    def getPosition(self):
        pass
    def asynchronousMoveTo(self, posi):
        pass
    def isBusy(self):
        return False
    def stop(self):
        pass
    def atPointEnd(self):
        pass
    def atScanEnd(self):
        pass
class ScalerChannelEpicsPVClass(ScannableBase):
	def __init__(self, name, strChTP, strChCNT, strChSn):
		self.setName(name);
		self.setInputNames([]);
		self.setExtraNames([name]);
#		self.Units=[strUnit];
		#self.setLevel(5);
		self.setOutputFormat(["%20.12f"]);
		self.chTP=CAClient(strChTP);
		self.chCNT=CAClient(strChCNT);
		self.chSn=CAClient(strChSn);
		self.tp = -1;

#		self.setTimePreset(time)

	def atStart(self):
		if not self.chTP.isConfigured():
			self.chTP.configure()
		if not self.chCNT.isConfigured():
			self.chCNT.configure()
		if not self.chSn.isConfigured():
			self.chSn.configure()

	#Scannable Implementations
	def getPosition(self):
		return self.getCount();
	
	def asynchronousMoveTo(self,newPos):
		self.setCollectionTime(newPos);
		self.collectData();

	def isBusy(self):
		return self.getStatus()

	def atEnd(self):
		if self.chTP.isConfigured():
			self.chTP.clearup()
		if self.chCNT.isConfigured():
			self.chCNT.clearup()
		if self.chSn.isConfigured():
			self.chSn.clearup()


	#Scaler 8512 implementations		
	def getTimePreset(self):
		if self.chTP.isConfigured():
			newtp = self.chTP.caget()
		else:
			self.chTP.configure()
			newtp = float(self.chTP.caget())
			self.chTP.clearup()
		self.tp = newtp
		return self.tp

	#Set the Time Preset and start counting automatically
	def setTimePreset(self, newTime):
		self.tp = newTime
		newtp = newTime;
		if self.chTP.isConfigured():
			tp = self.chTP.caput(newtp)
		else:
			self.chTP.configure()
			tp = self.chTP.caput(newtp)
			self.chTP.clearup()
#		Thread.sleep(1000)	

	def getCount(self):
		if self.chSn.isConfigured():
			output = self.chSn.caget()
		else:
			self.chSn.configure()
			output = self.chSn.caget()
			self.chSn.clearup()
		return float(output)


	#Detector implementations
	
	#Tells the detector to begin to collect a set of data, then returns immediately.
	#public void collectData() throws DeviceException;
	#Set the Time Preset and start counting automatically
	def collectData(self):
		#self.setTimePreset(self.tp)
		if self.chCNT.isConfigured():
			tp = self.chCNT.caput(1)
		else:
			self.chCNT.configure()
			tp = self.chCNT.caput(1)
			self.chCNT.clearup()
#		Thread.sleep(1000)	

	#Tells the detector how long to collect for during a call of the collectData() method.
	#public void setCollectionTime(double time) throws DeviceException;
	def setCollectionTime(self, newTime):
		self.setTimePreset(newTime)
		
	#Returns the latest data collected.
	#public Object readout() throws DeviceException;
	def getCollectionTime(self):
		nc=self.getTimePreset()
		return nc

	#Returns the current collecting state of the device.
	# return ACTIVE (1) if the detector has not finished the requested operation(s), 
	#        IDLE(0) if in an completely idle state and 
	#        STANDBY(2) if temporarily suspended.
	#public int getStatus() throws DeviceException;
	def getStatus(self):
		if self.chCNT.isConfigured():
			self.stauts = self.chCNT.caget()
		else:
			self.chCNT.configure()
			self.stauts = self.chCNT.caget()
			self.chCNT.clearup()	
		if self.stauts == '0': #still counting, Busy
			return 0
		else:
			return 1
class AlicatMassFlowController(ScannableMotionBase):
    '''
    scannable for set and get mass flow in a scannable way. It also provides method to query other mass flow properties.
    '''
    def __init__(self,name, rootPV, tolerance=0.01, formatstring="%.3f"):
        '''
        Constructor
        '''
        self.setName(name)
        self.setInputNames([name])
        self.setOutputFormat([formatstring])
        self.setLevel(5)
        self.currentflowcli=CAClient(rootPV+READ_MASS_FLOW)
        self.setflowtargetcli=CAClient(rootPV+SET_MASS_FLOW_TARGET)
        self.readflowtargetcli=CAClient(rootPV+READ_MASS_FLOW_TARGET)
        self.currentgastypecli=CAClient(rootPV+READ_GAS_TYPE)
        self.setfgastype1cli=CAClient(rootPV+SELECT_GAS_TYPE_1)
        self.setfgastype2cli=CAClient(rootPV+SELECT_GAS_TYPE_2)
        self.setgastypenumbercli=CAClient(rootPV+SET_GAS_TYPE_BY_NUMBER)
        self.pressurecli=CAClient(rootPV+READ_PRESSURE_IN_BAR)
        self.temperaturecli=CAClient(rootPV+READ_TEMPERATURE)
        self.volumetricflowcli=CAClient(rootPV+READ_VOLUMETRIC_FLOW)
        self.setproportionalgaincli=CAClient(rootPV+SET_PROPORTIONAL_GAIN)
        self.readproportionalgaincli=CAClient(rootPV+READ_PROPORTIONAL_GAIN)
        self.setderivativegaincli=CAClient(rootPV+SET_DERIVATIVE_GAIN)
        self.readderivativegaincli=CAClient(rootPV+READ_DERIVATIVE_GAIN)
        self.mytolerance=tolerance
        
    def getTolerance(self):
        return self.mytolerance
    
    def setTolerance(self, value):
        self.mytolerance=value
    
    def getCurrentFlow(self):
        try:
            if not self.currentflowcli.isConfigured():
                self.currentflowcli.configure()
                output=float(self.currentflowcli.caget())
                self.currentflowcli.clearup()
            else:
                output=float(self.currentflowcli.caget())
            return output
        except:
            print "Error returning current flow value"
            return 0

    def setTarget(self, target):
        try:
            if not self.setflowtargetcli.isConfigured():
                self.setflowtargetcli.configure()
                self.setflowtargetcli.caput(target)
                self.setflowtargetcli.clearup()
            else:
                self.setflowtargetcli.caput(target)
        except:
            print "error set to target flow value"

    def getTarget(self):
        try:
            if not self.readflowtargetcli.isConfigured():
                self.readflowtargetcli.configure()
                output=float(self.currentflowcli.caget())
                self.readflowtargetcli.clearup()
            else:
                output=float(self.readflowtargetcli.caget())
            return output
        except:
            print "Error returning flow target value"
            return 0

    def getGasType(self):
        #self.currentgastypecli does not work in EPICS
        try:
            if not self.setgastypenumbercli.isConfigured():
                self.setgastypenumbercli.configure()
                output=int(self.setgastypenumbercli.caget())
                self.setgastypenumbercli.clearup()
            else:
                output=int(self.setgastypenumbercli.caget())
            return gasTypes[output]
        except:
            print "Error returning current gas type"
            return 0
        
    def setGasType(self,name):
        key=gasTypes.keys()[(gasTypes.values()).index(name)]
        if int(key)>=0 or int(key) <16:
            try:
                if not self.setfgastype1cli.isConfigured():
                    self.setfgastype1cli.configure()
                    self.setfgastype1cli.caput(name)
                    self.setfgastype1cli.clearup()
                else:
                    self.setfgastype1cli.caput(name)
            except:
                print "error set to gas type 1"
        else:
            try:
                if not self.setfgastype2cli.isConfigured():
                    self.setfgastype2cli.configure()
                    self.setfgastype2cli.caput(name)
                    self.setfgastype2cli.clearup()
                else:
                    self.setfgastype2cli.caput(name)
            except:
                print "error set to gas type 2"
            
    def getPressure(self):
        try:
            if not self.pressurecli.isConfigured():
                self.pressurecli.configure()
                output=float(self.pressurecli.caget())
                self.pressurecli.clearup()
            else:
                output=float(self.pressurecli.caget())
            return output
        except:
            print "Error returning pressure"
            return 0
        
    def getTemperature(self):
        try:
            if not self.temperaturecli.isConfigured():
                self.temperaturecli.configure()
                output=float(self.temperaturecli.caget())
                self.temperaturecli.clearup()
            else:
                output=float(self.temperaturecli.caget())
            return output
        except:
            print "Error returning temperature"
            return 0
   
    def getVolumetricFlow(self):
        try:
            if not self.volumetricflowcli.isConfigured():
                self.volumetricflowcli.configure()
                output=float(self.volumetricflowcli.caget())
                self.volumetricflowcli.clearup()
            else:
                output=float(self.volumetricflowcli.caget())
            return output
        except:
            print "Error returning volumetric flow"
            return 0

    def getProportionalGain(self):
        try:
            if not self.readproportionalgaincli.isConfigured():
                self.readproportionalgaincli.configure()
                output=float(self.readproportionalgaincli.caget())
                self.readproportionalgaincli.clearup()
            else:
                output=float(self.readproportionalgaincli.caget())
            return output
        except:
            print "Error returning Proportional Gain"
            return 0

    def setProportionalGain(self, gain):
        try:
            if not self.setproportionalgaincli.isConfigured():
                self.setproportionalgaincli.configure()
                self.setproportionalgaincli.caput(gain)
                self.setproportionalgaincli.clearup()
            else:
                self.setproportionalgaincli.caput(gain)
        except:
            print "error set to proportional gain"

    def getDerivativeGain(self):
        try:
            if not self.readderivativegaincli.isConfigured():
                self.readderivativegaincli.configure()
                output=float(self.readderivativegaincli.caget())
                self.readderivativegaincli.clearup()
            else:
                output=float(self.readderivativegaincli.caget())
            return output
        except:
            print "Error returning Derivative Gain"
            return 0

    def setDerivativeGain(self, gain):
        try:
            if not self.setderivativegaincli.isConfigured():
                self.setderivativegaincli.configure()
                self.setderivativegaincli.caput(gain)
                self.setderivativegaincli.clearup()
            else:
                self.setderivativegaincli.caput(gain)
        except:
            print "error set to derivative gain"
            
            
#### methods for scannable 
    def getPosition(self):
        return self.getCurrentFlow()
    
    def asynchronousMoveTo(self, posi):
        self.setTarget(float(posi))
        
    def isBusy(self):
        return (abs(self.getPosition()-self.getTarget())>self.getTolerance())
    
    def atScanStart(self):
        pass
    def atPointStart(self):
        pass
    def stop(self):
        pass
    def atPointEnd(self):
        pass
    def atScanEnd(self):
        pass
class PositionCompareMotorWithLimitsClass(ScannableMotionBase):
    '''Create a scannable for a single motor'''
    def __init__(self, name, pvinstring, pvoutstring, pvstopstring, tolerance, unitstring, formatstring, upperlimit, lowerlimit):
        self.setName(name);
        self.setInputNames([name])
        self.Units=[unitstring]
        self.setOutputFormat([formatstring])
        self.setLevel(5)
        self.incli=CAClient(pvinstring)
        self.outcli=CAClient(pvoutstring)
        self.stopcli=CAClient(pvstopstring)
        self._tolerance=tolerance
        self.setUpperGdaLimits(upperlimit)
        self.setLowerGdaLimits(lowerlimit)
        
    def setLowerGdaLimits(self, lowerlimit):
        ScannableMotionBase.setLowerGdaLimits(lowerlimit)
        
    def getLowerGdaLimits(self):
        return ScannableMotionBase.getLowerGdaLimits()
    
    def setUpperGdaLimits(self, upperlimit):
        ScannableMotionBase.setUpperGdaLimits(upperlimit)
    
    def getUpperGdaLimits(self):
        return ScannableMotionBase.getUpperGdaLimits()
    
    def setTolerance(self, tolerance):
        self._tolerance=tolerance
        
    def getTolerance(self):
        return self._tolerance
        
    def atScanStart(self):
        if not self.incli.isConfigured():
            self.incli.configure()
        if not self.outcli.isConfigured():
            self.outcli.configure()
        if not self.stopcli.isConfigured():
            self.stopcli.configure()
         
    def rawGetPosition(self):
        try:
            if not self.outcli.isConfigured():
                self.outcli.configure()
                output=float(self.outcli.caget())
                self.outcli.clearup()
            else:
                output=float(self.outcli.caget())
            return output
        except:
            print "Error returning current position"
            return 0

    def getTargetPosition(self):
        try:
            if not self.incli.isConfigured():
                self.incli.configure()
                target=float(self.incli.caget())
                self.incli.clearup()
            else:
                target=float(self.incli.caget())
            return target
        except:
            print "Error returning target position"
            return 0
       
    def rawAsynchronousMoveTo(self,new_position):
        try:
            if not self.incli.isConfigured():
                self.incli.configure()
                self.incli.caput(new_position)
                self.incli.clearup()
            else:
                self.incli.caput(new_position)
        except:
            print "error moving to position"

    def rawIsBusy(self):
        return ( not abs(self.rawGetPosition() - self.getTargetPosition()) < self._tolerance)

    def atScanEnd(self):
        if self.incli.isConfigured():
            self.incli.clearup()
        if self.outcli.isConfigured():
            self.outcli.clearup()
        if self.stopcli.isConfigured():
            self.stopcli.clearup()
            
    def stop(self):
        if not self.stopcli.isConfigured():
            self.stopcli.configure()
            self.stopcli.caput(1)
            self.stopcli.clearup()
        else:
            self.stopcli.caput(1)

    def toString(self):
        return self.name + " : " + str(self.getPosition())
Example #50
0
def cagetArray(pvstring):
	cli=CAClient(pvstring)
	cli.configure()
	out=cli.cagetArrayDouble()
	cli.clearup()
	return out
class EPICSODQBPMClass(ScannableBase):
	'''PD for OD QBPM device
	Inputs: None
	Outputs: Range, C1, C2, C3, C4, X, Y
	self.set_range(value) - set gain 0 = highest
	calibration sequence:
	self.dark_current()	save dark current at current gain (beam off)
	self.set_zero()	calibrate zero x,y (beam on)
	self.setxy(xval, yval)	calibrate gains to give position in mm (go to xval, yval; beam on) - NOT TESTED
	Additional methods: config() loads qbpm parameters'''

	#	a=A1*(current4-A2) etc
	#	X=GX*(a-b)/(a+b) etc
	#	a,b,c,d=chan 4,2,1,3

	def __init__(self, name, pvrootstring,help=None):
		self.setName(name);
		if help is not None: self.__doc__+='\nHelp specific to '+self.name+':\n'+help
		#[self.A1,self.A2,self.B1,self.B2,self.C1,self.C2,self.D1,self.D2,self.GX,	self.GY]=xyparamvec
		self.pvrootstring=pvrootstring
		self.setInputNames([])
		self.setExtraNames(['Range','C1','C2','C3','C4','X','Y']);
		#self.setReportingUnits([' ','uA','uA','uA','uA','mm','mm'])
		self.setOutputFormat(['%.0f','%.9f','%.9f','%.9f','%.9f','%.3f','%.3f'])
		self.setLevel(9)
		self.rangecli=CAClient(pvrootstring+':RANGE_MENU');self.rangecli.configure()
		self.c1cli=CAClient(pvrootstring+':PHD1:I');self.c1cli.configure()
		self.c2cli=CAClient(pvrootstring+':PHD2:I');self.c2cli.configure()
		self.c3cli=CAClient(pvrootstring+':PHD3:I');self.c3cli.configure()
		self.c4cli=CAClient(pvrootstring+':PHD4:I');self.c4cli.configure()
		self.xcli=CAClient(pvrootstring+':XPOS');self.xcli.configure()
		self.ycli=CAClient(pvrootstring+':YPOS');self.ycli.configure()
		self.IR1cli=CAClient(pvrootstring+':PHD1:I_R');self.IR1cli.configure()
		self.IR2cli=CAClient(pvrootstring+':PHD2:I_R');self.IR2cli.configure()
		self.IR3cli=CAClient(pvrootstring+':PHD3:I_R');self.IR3cli.configure()
		self.IR4cli=CAClient(pvrootstring+':PHD4:I_R');self.IR4cli.configure()


	def getPosition(self):
		self.rangestring=self.rangecli.caget()
		self.c1string=self.c1cli.caget()
		self.c2string=self.c2cli.caget()
		self.c3string=self.c3cli.caget()
		self.c4string=self.c4cli.caget()
		self.xstring=self.xcli.caget()
		self.ystring=self.ycli.caget()
		return [float(self.rangestring),float(self.c1string), float(self.c2string),float(self.c3string),float(self.c4string),float(self.xstring),float(self.ystring)]

#	def asynchronousMoveTo(self,new_position):
#		self.rangecli.caput(new_position)

	def isBusy(self):
		return 0

	def set_params(self,params):
		[A1,A2,B1,B2,C1,C2,D1,D2,GX,GY]=params
		self.configcli=CAClient(self.pvrootstring+':A1_SP');self.configcli.configure(); self.configcli.caput(A1); self.configcli.clearup();
		self.configcli=CAClient(self.pvrootstring+':A2_SP');self.configcli.configure(); self.configcli.caput(A2); self.configcli.clearup();
		self.configcli=CAClient(self.pvrootstring+':B1_SP');self.configcli.configure(); self.configcli.caput(B1); self.configcli.clearup();
		self.configcli=CAClient(self.pvrootstring+':B2_SP');self.configcli.configure(); self.configcli.caput(B2); self.configcli.clearup();
		self.configcli=CAClient(self.pvrootstring+':C1_SP');self.configcli.configure(); self.configcli.caput(C1); self.configcli.clearup();
		self.configcli=CAClient(self.pvrootstring+':C2_SP');self.configcli.configure(); self.configcli.caput(C2); self.configcli.clearup();
		self.configcli=CAClient(self.pvrootstring+':D1_SP');self.configcli.configure(); self.configcli.caput(D1); self.configcli.clearup();
		self.configcli=CAClient(self.pvrootstring+':D2_SP');self.configcli.configure(); self.configcli.caput(D2); self.configcli.clearup();
		self.configcli=CAClient(self.pvrootstring+':GX_SP');self.configcli.configure(); self.configcli.caput(GX); self.configcli.clearup();
		self.configcli=CAClient(self.pvrootstring+':GY_SP');self.configcli.configure(); self.configcli.caput(GY); self.configcli.clearup();

	def get_params(self):
		self.configcli=CAClient(self.pvrootstring+':A1_SP');self.configcli.configure(); A1=float(self.configcli.caget());self.configcli.clearup()
		self.configcli=CAClient(self.pvrootstring+':A2_SP');self.configcli.configure(); A2=float(self.configcli.caget()); self.configcli.clearup()
		self.configcli=CAClient(self.pvrootstring+':B1_SP');self.configcli.configure(); B1=float(self.configcli.caget()); self.configcli.clearup()
		self.configcli=CAClient(self.pvrootstring+':B2_SP');self.configcli.configure(); B2=float(self.configcli.caget()); self.configcli.clearup()
		self.configcli=CAClient(self.pvrootstring+':C1_SP');self.configcli.configure(); C1=float(self.configcli.caget()); self.configcli.clearup()
		self.configcli=CAClient(self.pvrootstring+':C2_SP');self.configcli.configure(); C2=float(self.configcli.caget()); self.configcli.clearup()
		self.configcli=CAClient(self.pvrootstring+':D1_SP');self.configcli.configure(); D1=float(self.configcli.caget()); self.configcli.clearup()
		self.configcli=CAClient(self.pvrootstring+':D2_SP');self.configcli.configure(); D2=float(self.configcli.caget()); self.configcli.clearup()
		self.configcli=CAClient(self.pvrootstring+':GX_SP');self.configcli.configure(); GX=float(self.configcli.caget()); self.configcli.clearup()
		self.configcli=CAClient(self.pvrootstring+':GY_SP');self.configcli.configure(); GY=float(self.configcli.caget()); self.configcli.clearup()
		return [A1,A2,B1,B2,C1,C2,D1,D2,GX,GY]

	def get_rawcounts(self):
		self.IR1=float(self.IR1cli.caget())
		self.IR2=float(self.IR2cli.caget())
		self.IR3=float(self.IR3cli.caget())
		self.IR4=float(self.IR4cli.caget())
		return [self.IR1, self.IR2, self.IR3, self.IR4]

	def set_range(self, newrange):
		self.rangecli.caput(newrange)

	def factory_reset(self):
		params=[A1,A2,B1,B2,C1,C2,D1,D2,GX,GY]=[1,0,1,0,1,0,1,0,1,1]
		self.set_params(params)
		
	def dark_current(self):
		#offsets not persistent - do dark current with beam off
		[A1,A2,B1,B2,C1,C2,D1,D2,GX,GY]=self.get_params()

		self.configcli=CAClient(self.pvrootstring+':PHD4:I_R');self.configcli.configure(); A2=float(self.configcli.caget()); self.configcli.clearup()
		self.configcli=CAClient(self.pvrootstring+':PHD2:I_R');self.configcli.configure(); B2=float(self.configcli.caget()); self.configcli.clearup()
		self.configcli=CAClient(self.pvrootstring+':PHD1:I_R');self.configcli.configure(); C2=float(self.configcli.caget()); self.configcli.clearup()
		self.configcli=CAClient(self.pvrootstring+':PHD3:I_R');self.configcli.configure(); D2=float(self.configcli.caget()); self.configcli.clearup()
		self.set_params([A1,A2,B1,B2,C1,C2,D1,D2,GX,GY])
		print 'new dark currents (i4,i2,i1,i3):', [A2, B2, C2, D2]

	def set_zero(self):
		#do with beam on
		[ic,ib,id,ia]=self.get_rawcounts()
		[A1,A2,B1,B2,C1,C2,D1,D2,GX,GY]=self.get_params()
		A1B1=A1*B1; C1D1=C1*D1;	#get products
		A1_B1=(ib-B2)/(ia-A2);		#calculate ratio X=0
		C1_D1=(id-D2)/(ic-C2);		#calculate ratio Y=0
		#re-calc A1, B1 etc for zero X,Y but keep ratio at current value
		[A1, B1, C1, D1]=[sqrt(A1B1*A1_B1), sqrt(A1B1/A1_B1), sqrt(C1D1*C1_D1), sqrt(C1D1/C1_D1)]
		self.set_params([A1,A2,B1,B2,C1,C2,D1,D2,GX,GY])

	def set_xy(self,x,y):
		#do with beam on
		[ic,ib,id,ia]=self.get_rawcounts()
		[A1,A2,B1,B2,C1,C2,D1,D2,GX,GY]=self.get_params()
		[a,b,c,d]=[A1*(ia-A2), B1*(ib-B2),C1*(ic-C2), D1*(id-D2)]
		[GX, GY]=[x*(a+b)/(a-b),y*(c+d)/(c-d)]
		#print [A1,A2,B1,B2,C1,C2,D1,D2,GX,GY]
		self.set_params([A1,A2,B1,B2,C1,C2,D1,D2,GX,GY])
Example #52
0
def caput_wait(pvstring, value, timeout=10):
	cli=CAClient(pvstring)
	cli.configure()
	cli.caput(timeout, value)
	cli.clearup()
class DetectorControlClass(ScannableMotionBase):
    """Create PD for single EPICS ETL detector"""

    def __init__(self, name, pvinstring, pvoutstring, unitstring, formatstring):
        self.setName(name)
        self.setInputNames([name])
        self.Units = [unitstring]
        self.setOutputFormat([formatstring])
        self.setLevel(3)
        self.incli = CAClient(pvinstring)
        self.outcli = CAClient(pvoutstring)

    def atStart(self):
        if not self.incli.isConfigured():
            self.incli.configure()
        if not self.outcli.isConfigured():
            self.outcli.configure()

    def getPosition(self):
        try:
            if not self.outcli.isConfigured():
                self.outcli.configure()
                output = float(self.outcli.caget())
                self.outcli.clearup()
            else:
                output = float(self.outcli.caget())
            return output
        except:
            print "Error returning current position"
            return 0

    def getTargetPosition(self):
        try:
            if not self.incli.isConfigured():
                self.incli.configure()
                target = float(self.incli.caget())
                self.incli.clearup()
            else:
                target = float(self.incli.caget())
            return target
        except:
            print "Error returning target position"
            return 0

    def asynchronousMoveTo(self, new_position):
        try:
            if not self.incli.isConfigured():
                self.incli.configure()
                self.incli.caput(new_position)
                self.incli.clearup()
            else:
                self.incli.caput(new_position)
        except:
            print "error moving to position"

    def isBusy(self):
        return self.getPosition() != self.getTargetPosition()

    def atEnd(self):
        if self.incli.isConfigured():
            self.incli.clearup()
        if self.outcli.isConfigured():
            self.outcli.clearup()

    def toString(self):
        return self.name + " : " + str(self.getPosition())
class SamplePressure(ScannableBase, MonitorListener):
    """
    create a sannable to provide control of gas pressure in the sample. 
    It will reports to users when the system pressure is less than the sample pressure requested. 
    """

    def __init__(self, name, systempressure):
        """
        Constructor
        """
        self.setName(name)
        self.setInputNames([name])
        self.increment = 0.01
        self.target = 0.0
        self.lastTarget = 0.0
        self.sampleP = 0.0
        self.currentpressure = 0.0
        self.pressureTolerance = 0.002
        self.outcli = CAClient(CurrentPressure)
        self.incli = CAClient(TargetPressure)
        self.sysp = systempressure
        self.initialiseTarget()

    def atScanStart(self):
        """intialise parameters before scan"""
        # TODOS check requested sample pressure can be reached
        if not self.outcli.isConfigured():
            self.outcli.configure()
        if not self.incli.isConfigured():
            self.incli.configure()
        self.target = self.getPosition()

    def atScanEnd(self):
        """clean up resources"""
        if self.outcli.isConfigured():
            self.outcli.clearup()
        if self.incli.isConfigured():
            self.incli.clearup()

    def atPointStart(self):
        pass

    def atPointEnd(self):
        pass

    def getPosition(self):
        """
        return the current gas pressure in sample
        """
        try:
            if not self.outcli.isConfigured():
                self.outcli.configure()
                output = float(self.outcli.caget())
                self.outcli.clearup()
            else:
                output = float(self.outcli.caget())
            return output
        except:
            print "Error returning current position"
            return 0

    def asynchronousMoveTo(self, new_position):
        """
        move the sample pressure to the specified value asynchronously.
        """
        try:
            self.lastTarget = round(self.getLastTarget(), 3)
            self.sampleP = round(self.getPosition(), 3)
            self.target = round(float(new_position), 3)
            thread.start_new_thread(self.setSamplePressure, (self.sampleP, self.target, self.increment))
        except:
            print "error moving sample pressure to (%s): %f" % (sys.exc_info()[0], float(new_position))
            raise

    def isBusy(self):
        return abs(self.getPosition() - self.getTarget()) > self.getTolerance()

    def stop(self):
        """
        stop or abort pressure move in the sample.
        """
        self.asynchronousMoveTo(self.getPosition())
        if self.outcli.isConfigured():
            self.outcli.clearup()
        if self.incli.isConfigured():
            self.incli.clearup()

    def setSamplePressure(self, SampleP, target, increment):
        # SET FINAL SAMPLE PRESSURE AND INCREMENTS
        if SampleP < target:
            SampleP = round(self.lastTarget + increment, 3)  # increments in bar
            if SampleP > target:
                return
            try:
                if not self.incli.isConfigured():
                    self.incli.configure()
                while SampleP <= target:  # final sample pressure in bar
                    #                   interruptable()
                    self.incli.caput(SampleP)
                    # print "set sample pressure to "+str(SampleP)+", target is "+str(target)
                    sleep(5)  # wait time in seconds
                    SampleP = round(SampleP + increment, 3)
                    # check if smaple pressure required greater the system pressure then exit
                    if self.sysp.getPosition() < target:
                        # TODOs recharge the system pressure here???
                        print "System pressure %f is less than the demanding sample pressure %f. Please abort this scan or re-charge the system pressure." % (
                            self.sysp.getPosition(),
                            target,
                        )
            #                 if self.incli.isConfigured():
            #                     self.incli.clearup()
            except:
                print "error moving to position"

        elif SampleP > target:
            SampleP = round(self.lastTarget - increment, 3)  # increments in bar
            if SampleP < target:
                return
            if SampleP < 0:
                SampleP = 0
            if target < 0:
                raise Exception("Pressure cannot be negative.")
            try:
                if not self.incli.isConfigured():
                    self.incli.configure()
                while SampleP >= target:  # final sample pressure in bar
                    #                   interruptable()
                    self.incli.caput(SampleP)
                    # print "set sample pressure to "+str(SampleP)+", target is "+str(target)
                    sleep(5)  # wait time in seconds
                    SampleP = round(SampleP - increment, 3)
                    if SampleP < 0:
                        self.incli.caput(0)
                        break
            #                 if self.incli.isConfigured():
            #                     self.incli.clearup()
            except:
                print "error moving to position"
        else:
            print "already at the sample pressure."
            return

    def setIncrement(self, value):
        self.increment = value

    def getIncrement(self):
        return self.increment

    def getTarget(self):
        return self.target

    def getLastTarget(self):
        try:
            if not self.incli.isConfigured():
                self.incli.configure()
                output = float(self.incli.caget())
                self.incli.clearup()
            else:
                output = float(self.incli.caget())
            return output
        except:
            print "Error returning target value"
            return 0

    def initialiseTarget(self):
        self.lastTarget = self.getLastTarget()

    def getTolerance(self):
        return self.pressureTolerance

    def setTolerance(self, value):
        self.pressureTolerance = value
Example #55
0
class ADC(ScannableMotionBase, MonitorListener):
    
    def __init__(self, name, hv=adcppv, el=adcepv, gate=adcgatepv):
        self.setName(name)
        self.setInputNames([])
        self.hv=hv
        self.el=el
        self.gate=gate
        self.voltagecli=CAClient(hv)
        self.electrometercli=CAClient(el)
        self.gatecli=CAClient(gate)
        self.voltagenordcli=CAClient(hv+".NORD")
        self.electrometernordcli=CAClient(el+".NORD")
        self.monitoradded=False
        self.filename=None
        self.voltagemonitor=None
        self.electrometermonitor=None
        self.gatemonitor=None
        self.firstMonitor = True
        self.data={hv:[],el:[],gate:[]}
        self.voltages = []      # for holding voltage data array
        self.electrometers=[]   # for holding electrometer data array
        self.gates=[]
        self.firstData = True
        self.fastmode = False
        self.numberofgate=0
        self.fastMode=True
        self.updatecounter=0
        self.collectionNumber=1
               
    def setNumberOfGates(self, ng):
        self.numberofgate=ng
        
    def getNumberOfGates(self):
        return self.numberofgate
    
    def getCollectionNumber(self):
        return self.collectionNumber
    
    def setCollectionNumber(self, num):
        self.collectionNumber=num
    
    def isFastMode(self):
        return self.fastMode
    
    def setFastMode(self, mode):
        self.fastMode=mode
        
    def reset(self):
        self.electrometers = []
        self.voltages = []
        self.updatecounter=0
        self.collectionNumber=1
        
    def setFilename(self, filename):
        self.filename=filename
        
    def getFilename(self):
        return self.filename
    
    def getElectrometer(self, num):
        try:
            if not self.electrometercli.isConfigured():
                self.electrometercli.configure()
            return self.electrometercli.cagetArrayDouble(num)
        except FactoryException, e:
            print "create channel error (%s): %s" % (self.electrometercli.getChannel().getName(),e)
        except CAException, e:
            print "caget Error (%s): %s" % (self.electrometercli.getChannel().getName(),e)