示例#1
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()
示例#2
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
示例#3
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
示例#4
0
文件: utils.py 项目: kusamau/gda-core
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()
示例#6
0
文件: utils.py 项目: openGDA/gda-core
def caget(pvstring):
	'caget from Jython'
	cli=CAClient(pvstring)
	cli.configure()
	out=cli.caget()
	cli.clearup()
	return out
示例#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
示例#8
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()
示例#9
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()
示例#10
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')
示例#11
0
class BimorphVoltage(ScannableMotionBase):
    def __init__(self, name, pvVoltage, pvStatus, formatstring):
        self.setName(name)
        self.chVoltage = CAClient(pvVoltage)
        self.chStatus = CAClient(pvStatus)
        self.Units = ['V']
        self.setOutputFormat([formatstring])
        self.delay = 5
        self.timeout = 30

    def setDelay(self, newDelay):
        self.delay = newDelay

    def setTimeout(self, newTimeout):
        self.timeout = newTimeout

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

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

        sleep(self.delay)

    def getStatus(self):
        try:
            if self.chStatus.isConfigured():
                return int(float(self.chStatus.caget()))
            else:
                self.chStatus.configure()
                return int(float(self.chStatus.caget()))
        except:
            print "Error getting status"

    def isBusy(self):
        if self.getStatus() == 1:  #It's done
            return False
        else:
            return True
示例#12
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()
示例#13
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')
示例#14
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.configure()
		if not self.outcli.isConfigured():
			self.outcli.configure()
		if not self.movecli.isConfigured():
			self.movecli.configure()

	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
示例#15
0
class PositionCompareClass(ScannableMotionBase):
    '''Create a position compare scannable with separate PV names for demand, target and readback positions.'''
    def __init__(self, name, pvdemand, pvreadback, tolerance, unitstring,
                 formatstring):
        ''' constructor
        @param name: name of this scannable
        @param pvdemand: the PV name for the demand position
        @param pvreadback: the PV name for the current position or readback
        @param tolerance: the tolerance value within which the readback position is regarded as reached to the demand position
        @param unitstring: the String value of the unit
        @param formatstring: the format string for the returned value.        
        '''
        self.setName(name)
        self.setInputNames([name])
        self.unit = unitstring
        self.setOutputFormat([formatstring])
        self.setLevel(3)
        self.demand = CAClient(pvdemand)
        self.readback = CAClient(pvreadback)
        self._tolerance = tolerance

    def setTolerance(self, tolerance):
        self._tolerance = tolerance

    def getTolerance(self):
        return self._tolerance

    def atScanStart(self):
        if not self.demand.isConfigured():
            self.demand.configure()
        if not self.readback.isConfigured():
            self.readback.configure()

    def rawGetPosition(self):
        '''read the magnet value
        '''
        try:
            if not self.readback.isConfigured():
                self.readback.configure()
                output = float(self.readback.caget())
                self.readback.clearup()
            else:
                output = float(self.readback.caget())
            return output
        except Exception, e:
            print("Error returning Magnet value")
            raise e
示例#16
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
示例#18
0
class EpicsReadPvWritePvClass(ScannableMotionBase):
    def __init__(self, name, pvSet, pvGet, formatstring):
        self.setName(name)
        self.setInputNames([name])
        self.setOutputFormat([formatstring])
        self.setLevel(6)
        self.chIn = CAClient(pvSet)
        self.chOut = CAClient(pvGet)

    def atScanStart(self):
        if not self.chIn.isConfigured():
            self.chIn.configure()
        if not self.chOut.isConfigured():
            self.chOut.configure()

    def atScanEnd(self):
        if self.chIn.isConfigured():
            self.chIn.clearup()
        if self.chOut.isConfigured():
            self.chOut.clearup()

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

    def asynchronousMoveTo(self, newpos):
        try:
            if not self.chIn.isConfigured():
                self.outcli.configure()
            self.chIn.caput(newpos)
        except:
            print "error moving to position %f" % float(newpos)

    def isBusy(self):
        return False
示例#19
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
示例#20
0
class EpicsPvClass(object):
    def __init__(self, strPV):
        self.pv = CAClient(strPV)
        self.pv.configure()

    def caput(self, value):
        if self.pv.isConfigured():
            self.pv.caput(value)
        else:
            self.pv.configure()
            self.pv.caput(value)
            self.pv.clearup()

    def caget(self):
        if self.pv.isConfigured():
            result = self.pv.caget()
        else:
            self.pv.configure()
            result = self.pv.caget()
            self.pv.clearup()
        return result
示例#21
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
示例#22
0
class EpicsDeviceClass(object):
    def __init__(self, pv):
        self.pv = pv
        self.ch = CAClient(self.pv)
        self.ch.configure()

    def caput(self, value):
        if self.ch.isConfigured():
            self.ch.caput(value)
        else:
            self.ch.configure()
            self.ch.caput(value)
            self.ch.clearup()

    def caget(self):
        if self.ch.isConfigured():
            result = self.ch.caget()
        else:
            self.ch.configure()
            result = self.ch.caget()
            self.ch.clearup()
        return result
示例#23
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
示例#24
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
示例#25
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
示例#26
0
class DetectorExposureScannable(ScannableMotionBase):
    '''
    a scannable to change exposure time of a given detector PV at each scan data point during scan process
    '''
    def __init__(self, name, pv):
        '''
        create a scannable for specified PV
        '''
        self.setName(name)
        self.setInputNames(['exposure'])
        self.pv = pv
        self.cli = CAClient(pv)
        self._busy = False

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

    def atScanEnd(self):
        if self.cli.isConfigured():
            self.cli.clearup()

    def asynchronousMoveTo(self, new_pos):
        try:
            if not self.cli.isConfigured():
                self.cli.configure()
            self._busy = True
            self.cli.caput(float(new_pos))
        except:
            raise
        finally:
            self._busy = False

    def getPosition(self):
        return float(self.cli.caget())

    def isBusy(self):
        return self._busy
示例#27
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 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):
        try:
            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"
        self.stopcli.configure()
        self.stopcli.caput(1)
        self.stopcli.clearup()
示例#28
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"
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
示例#30
0
class TemperatureControllerClass(ScannableMotionBase):
    def __init__(self, name, strTempSetPV, strTempSetReadBackPV, strTemp1GetPV,
                 strTemp2GetPV):
        self.setName(name)
        self.setInputNames([name])
        self.setExtraNames(['T1', 'T2'])
        self.setOutputFormat(["%6.3f", "%6.3f", "%6.3f"])

        #		self.Units=[strUnit];
        self.setLevel(7)
        #		self.setOutputFormat(["%20.12f"]);

        self.currentTemp = [0, 0]
        self.demondTemp = 0

        #Default delay is 10 minutes = 600 seconds
        self.waitTime = 600
        self.waitEnough = True
        self.errorTolerance = 1

        self.chSetTemp = CAClient(strTempSetPV)
        self.chSetTemp.configure()
        self.chSetTempRB = CAClient(strTempSetReadBackPV)
        self.chSetTempRB.configure()

        self.chGetTemp1 = CAClient(strTemp1GetPV)
        self.chGetTemp1.configure()
        self.chGetTemp2 = CAClient(strTemp2GetPV)
        self.chGetTemp2.configure()

    def setDelay(self, newWait):
        self.waitTime = newWait

    def setError(self, newError):
        self.errorTolerance = newError

    def setTemp(self, x):
        self.demondTemp = x
        if self.chSetTemp.isConfigured():
            self.chSetTemp.caput(x)
        else:
            self.chSetTemp.configure()
            self.chSetTemp.caput(x)
            self.chSetTemp.clearup()
        self.waitEnough = False

    def getTemp(self):
        if self.chSetTempRB.isConfigured():
            p0 = self.chSetTempRB.caget()
        else:
            self.chSetTempRB.configure()
            p0 = self.chSetTempRB.caget()
            self.chSetTempRB.clearup()

        if self.chGetTemp1.isConfigured():
            p1 = self.chGetTemp1.caget()
        else:
            self.chGetTemp1.configure()
            p1 = self.chGetTemp1.caget()
            self.chGetTemp1.clearup()

        if self.chGetTemp2.isConfigured():
            p2 = self.chGetTemp2.caget()
        else:
            self.chGetTemp2.configure()
            p2 = self.chGetTemp2.caget()
            self.chGetTemp2.clearup()

        self.demondTemp = float(float(p0))
        self.currentTemp = [float(p1), float(p2)]
        return [self.demondTemp, self.currentTemp[0], self.currentTemp[1]]

    def waitTillReady(self):
        if self.waitEnough:
            return
        #wait until T1 is ready
        nToast = 3
        while nToast > 0:
            self.getTemp()
            if math.fabs(self.currentTemp[0] -
                         self.demondTemp) > self.errorTolerance:
                print 'T1 is not ready yet, wait...'
                sleep(10)
            else:
                print 'T1 is checked and seems OK.'
                sleep(10)
                nToast -= 1

        #Wait the waitTime for T2
        print 'Wait ' + str(self.waitTime) + ' seconds for T2'
        sleep(self.waitTime)
        self.waitEnough = True
        print 'T2 wake up'

    def checkReady(self):
        return self.waitEnough

    #Pseudo Device Implementations
    def atScanStart(self):
        if not self.chSetTemp.isConfigured():
            self.chSetTemp.configure()
        if not self.chSetTempRB.isConfigured():
            self.chSetTempRB.configure()

        if not self.chGetTemp1.isConfigured():
            self.chGetTemp1.configure()
        if not self.chGetTemp2.isConfigured():
            self.chGetTemp2.configure()

    def atScanEnd(self):
        if self.chSetTemp.isConfigured():
            self.chSetTemp.clearup()
        if self.chSetTempRB.isConfigured():
            self.chSetTempRB.clearup()

        if self.chGetTemp1.isConfigured():
            self.chGetTemp1.clearup()
        if self.chGetTemp2.isConfigured():
            self.chGetTemp2.clearup()

    def getPosition(self):
        return self.getTemp()

    def asynchronousMoveTo(self, newPos):
        self.setTemp(newPos)
        self.waitTillReady()

    def isBusy(self):
        if self.checkReady():
            result = False
        else:
            result = True
        return result

    def toString(self):
        ss = self.getName() + " [tem, tem1, tem2]: " + str(self.getPosition())
        return ss
示例#31
0
class PixisDetectorClass(DetectorBase):
	def __init__(self, name, panelName, detectorName, initPV="BL06I-EA-PIXIS-01:CAM:Initialize"):
		self.setName(name);
		self.setInputNames([name]);
		self.setExtraNames([]);
#		self.Units=[strUnit];
		self.setLevel(7);
		
		self.panel = panelName;
		self.detectorName=detectorName;
		self.initPV=initPV;
		
		self.detector=None;
		self.fileName=None;
		self.dataHolder = None;
		self.ch=None;

		self.exposureTime = 0

		self.logScale = False;
		self.alive=False;
		
		self.connect();
		
	def connect(self):
		try:
			self.ch=CAClient(self.initPV);
			self.ch.configure();
			self.detector =vars(gdamain)[self.detectorName];
			print "PIXIS Camera is connected successfully."
		except:
			exceptionType, exception, traceback=sys.exc_info();
			logger.dump("PIXIS Camera can not be connected ", exceptionType, exception, traceback)
		
		
	#DetectorBase Implementation
	def getCollectionTime(self):
		self.exposureTime=self.detector.getCollectionTime();
		return self.exposureTime;

	def setCollectionTime(self, newExpos):
		self.exposureTime = newExpos;
		self.detector.setCollectionTime(self.exposureTime);

	def prepareForCollection(self):
		self.detector.prepareForCollection();


	def endCollection(self):
		self.detector.endCollection();


	def collectData(self):
		self.initialiseDetector(1);#To press the Initialize Detector button
		
		self.detector.collectData();
		return;
		
	def readout(self):
#		self.getMetadata();
		
		nxDetectorReturn=self.detector.readout();
		
		if isinstance(nxDetectorReturn, NXDetectorDataWithFilepathForSrs):
			self.fileName=nxDetectorReturn.getFilepath();
		else:
			self.fileName=str(nxDetectorReturn);
		
		# Trying to re-enable this results in the  
		errorWhenEnabled=""" 		See /uk.ac.gda.devices.peem/src/gda/device/detector/areadetector/AreaDetectorController.java:339
                                                                                             /dls/i06-1/data/2014/si9122-1/104163_PixisImage/pixis_000001.tif
2014-03-06 12:43:28,340 INFO  [ScriptLogger]  - PilatusDetectorPseudoDevice.readout(): File '/dls/i06-1/data/2014/si9122-1/104159_PixisImagepixis_000000.tif' does not exist! 
2014-03-06 12:43:28,342 INFO  [gda.jython.logger.RedirectableFileLogger]  -  | PilatusDetectorPseudoDevice.readout(): File '/dls/i06-1/data/2014/si9122-1/104159_PixisImagepixis_000000.tif' does not exist!
2014-03-06 12:43:28,353 INFO  [gda.jython.logger.RedirectableFileLogger]  -  | ====================================================================================================
2014-03-06 12:43:28,355 ERROR [gda.scan.ScanBase] java.lang.Exception: during scan collection: DeviceException: Traceback (most recent call last):
  File "/dls_sw/i06-1/software/gda_versions/gda_8.34b/workspace_git/gda-mt.git/configurations/mt-config/scripts/Diamond/Pixis/PixisDetector.py", line 93, in readout
    raise Exception("No File Found Error");
"""
#		if not self.fileExists(self.fileName, 100):
#			logger.simpleLog( "PilatusDetectorPseudoDevice.readout(): File '" + self.fileName + "' does not exist!" );
#			raise Exception("No File Found Error");
#		
#		self.createMetadataFiles( str(self.fileName) );
			
		if self.alive:
			self.display();
		
		return self.fileName;

	def getStatus(self):
		return self.detector.getStatus();

	def createsOwnFiles(self):
		return True;

## Extra Implementation
	def initialiseDetector(self, value=1):
#		self.pv=GDAEpicsInterfaceReader.getPVFromSimplePVType(deviceName);
		if self.ch.isConfigured():
			self.ch.caput(value);
		else:
			self.ch.configure();
			self.ch.caput(value);
			self.ch.clearup();
		

	def fileExists(self, fileName, numberOfTry):
		result = False;
	
		for i in range(numberOfTry):
			if (not os.path.exists(fileName)) or (not os.path.isfile(fileName)):
				print "File '%s' does not exist on try " % fileName + str(i+1);
				logger.simpleLog( "PixisDetectorClass: File does not exist on try " + str(i+1) );
				#check again:
				sleep(1);
				os.system("ls -la " + fileName);
			else:
				#To touch the file will change the timestamps on the directory, which in turn causes the client to refetch the file's attributes. 
				os.system("touch -c " + fileName);
				
				#To check the file size non zero
				fsize = os.stat(fileName)[stat.ST_SIZE];
				print "File exists on try " + str(i+1) + " with size " + str(fsize);
				logger.simpleLog( "Pixis Camera: File '" + fileName + "' exists on try " + str(i+1) + " with size " + str(fsize) );
				sizePixis = 8388782L;
				if fsize!=sizePixis:
					print "Wrong file size: " + str(fsize);
					logger.simpleLog( "PixisDetector: File '" + fileName + "' has wrong file size: " + str(fsize) );
					sleep(1);
					continue;
				#The file seems exist with some content inside. Double check to make sure it's available
				try:
					#To touch the file will change the timestamps on the directory, which in turn causes the client to refetch the file's attributes. 
					os.system("touch -c " + fileName);
					tf = open(fileName,"rb");
					tf.close();
					result = True;
					break;
				except:
					print "There are something wrong on the file system !!!"
					logger.simpleLog( "PixisDetectorClass: There are something wrong on the file system !!!");
		return result;
		
	def setAlive(self, newAlive=True):
		self.alive = newAlive;
		
	def setLogScale(self, newLogScale=True):
		self.logScale = newLogScale;

	def setPanel(self, newPanelName):
		self.panel = newPanelName;
		
	def singleShot(self, newExpos):
		"""Shot single image with given exposure time""";
		if self.getStatus() != Detector.IDLE:
			print 'PIXIS detector not available, please try later';
			return;
		
		self.setCollectionTime(newExpos);
		self.collectData();
		while self.getStatus() != Detector.IDLE:
			sleep(self.exposureTime/2);
		return self.readout();

	def display(self, fileName=None):
		if fileName is None:
			fileName = self.fileName;
			
		self.dataHolder=dnp.io.load(fileName);
		dataset = self.dataHolder[0];

		if self.panel:
			if self.logScale:
				SDAPlotter.imagePlot(self.panel, DatasetUtils.lognorm(dataset)); #For RCP GUI
			else:
				SDAPlotter.imagePlot(self.panel, dataset); #For RCP GUI
		else:
			print "No panel set to display"
			raise Exception("No panel_name set in %s. Set this or set %s.setAlive(False)" % (self.name,self.name));
示例#32
0
class StripChart(MonitorListener):
    '''
    plot y dataset against x dataset for a fixed length, new data added push oldest data out in the datasets.
    '''

    def __init__(self, xpv, ypv, controlpv, numberofpointstoplot=1000,save=False):
        '''
        Constructor
        '''
        self.xpv=xpv
        self.ypv=ypv
        self.xcli=CAClient(xpv)
        self.ycli=CAClient(ypv)
        self.control=CAClient(controlpv)
        self.x=array.array('d')
        self.y=array.array('d')
        self.plotsize=numberofpointstoplot
        self.isSave=save
        
    def start(self):
        if not self.xcli.isConfigured():
            self.xcli.configure()
        if not self.ycli.isConfigured():
            self.ycli.configure()
        if not self.control.isConfigured():
            self.control.configure()
        self._first=True
        self.xmonitor=self.xcli.camonitor(self)
        self.ymonitor=self.ycli.camonitor(self)
        self.control.caput(1)

    def stop(self):
        self.control.caput(0)
        self.xcli.removeMonitor(self.xmonitor)
        self.ycli.removeMonitor(self.ymonitor)
        if self.xcli.isConfigured():
            self.xcli.clearup()
        if self.ycli.isConfigured():
            self.ycli.clearup()
        if self.control.isConfigured():
            self.control.clearup()
        
    def monitorChanged(self, mevent):
        if self._first:
            self._first=False
            return
        if str(mevent.getSource().getName()).trim()==self.xpv:
            self.x.append(float(mevent.getDBR().getDoubleValue()[0]))
        if str(mevent.getSource().getName()).trim()==self.ypv:
            self.y.append(float(mevent.getDBR().getDoubleValue()[0]))
        if self.x.count() == self.y.count():
            if self.x.count() <= self.plotsize:
                dnp.plot.line(self.x, self.y, "Plot")
            else:
                dnp.plot.plot(self.x[-self.plotsize:], self.y[-self.plotsize:], "Plot")
        
    def writeData(self):
        self.stop()
        self.stattimestamp.removeMonitor(self.timemonitor)
        self.stattotal.removeMonitor(self.countmonitor)
        filename=nextDataFile()
        print "saving data to %s, please wait..." % filename
        #length=min(self.timedata.getData().size, self.countdata.getData().size)
        timedataset=self.timedata.getData()
        countdataset=self.countdata.getData()
        dnp.plot.plot(timedataset, countdataset, "Plot")
        outfile=open(filename,"w")
        for time, count in zip(timedataset.getData().tolist(), countdataset.getData().tolist()):
            outfile.write("%f\t%d\n"% (time, count))
        outfile.close()
        #dnp.io.save(filename, [timedataset, countdataset], format="text") # write 2 text fileseach with one dataset
        print "collection completed."
示例#33
0
class ScalerChannelMonitorEpicsPVClass(ScannableMotionBase):
	def __init__(self, name, strPV, strCh, time):
		self.setName(name);
		self.setInputNames([])
		self.setExtraNames([name]);
#		self.Units=[strUnit]
#		self.setOutputFormat(['%d'])
		self.setLevel(3)
		self.chTP=CAClient(strPV+'.TP')
		self.chCNT=CAClient(strPV+'.CNT')
		self.chFREQ=CAClient(strPV+'.FREQ')
		self.chPRn=CAClient(strPV+'.PR' + strCh)
		self.chSn=CAClient(strPV+'.S' + strCh)

	def atScanStart(self):
		if not self.chTP.isConfigured():
			self.chTP.configure()
		if not self.chCNT.isConfigured():
			self.chCNT.configure()
		if not self.chFREQ.isConfigured():
			self.chFREQ.configure()
		if not self.chPRn.isConfigured():
			self.chPRn.configure()
		if not self.chSn.isConfigured():
			self.chSn.configure()

	def getPresetTime(self):
		#get time preset
		if self.chTP.isConfigured():
			self.tp = self.chTP.caget()
		else:
			self.chTP.configure()
			self.tp = self.chTP.caget()
			self.chTP.clearup()
			
		return self.tp

	def setPresetTime(self, float):
		#get time preset
		if self.chTP.isConfigured():
			tp = self.chTP.caget()
		else:
			self.chTP.configure()
			tp = self.chTP.caget()
			self.chTP.clearup()
			
		self.tp = self.getTP()
		
	def getPosition(self):
		self.tp = self.getPresetTime()
		
		self.startCounting();

		while self.isBusy():
			Thread.sleep(tp);
			
		self.startCounting();
		
		while self.isBusy():
			Thread.sleep(tp);
			
		output = self.getCount();
		return output;
	

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

	def startCounting(self):
		self.status = '1'
		if self.chCNT.isConfigured():
			self.chCNT.caput(self.stauts) ##start counting
		else:
			self.chCNT.configure()
			self.chCNT.caput(self.stauts) ##start counting
			self.chCNT.clearup()	

	def isBusy(self):
		try:
			if self.chCNT.isConfigured():
				self.stauts = self.chCNT.caget()
			else:
				self.chCNT.configure()
				self.stauts = self.chCNT.caget()
				self.chCNT.clearup()	
			
			if self.stauts == '1': #still counting, busy
				return 1
			elif self.stauts == '0': # count finished. not busy
				return 0 
			else: #strange condition, caget some wrong status
				raise ScalerException("Wrong Scaler CNT")	
				return 1
		except ScalerException, e:
			print "error in ScalerChannelMonitorEpicsPVClass.isBusy()."
			print e
			print self.status
		except Exception, e:
			print "What ever exception raised in ScalerChannelMonitorEpicsPVClass.isBusy()."
			print e
			print self.status
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
示例#35
0
文件: utils.py 项目: openGDA/gda-core
def caput(pvstring,value):
	'caput from Jython'
	cli=CAClient(pvstring)
	cli.configure()
	cli.caput(value)
	cli.clearup()
示例#36
0
文件: utils.py 项目: openGDA/gda-core
def cagetArray(pvstring):
	cli=CAClient(pvstring)
	cli.configure()
	out=cli.cagetArrayDouble()
	cli.clearup()
	return out
示例#37
0
文件: utils.py 项目: openGDA/gda-core
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 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())
示例#40
0
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
示例#41
0
class FastEnergyScanClass:
    def __init__(self):
        self.startEnergy = CAClient(pvStartEnergy)
        self.endEnergy = CAClient(pvEndEnergy)
        self.scanTime = CAClient(pvScanTime)
        self.numberOfPoints = CAClient(pvNumberOfPoints)
        self.startButton = CAClient(pvStartButton)
        self.status = CAClient(pvReadyState)

        self.buildButton = CAClient(pvBuildButton)

        self.elementCounter = CAClient(pvElementCounter)

        self.channel01 = CAClient(pvDataChannel01)
        self.channel02 = CAClient(pvDataChannel02)
        self.channel03 = CAClient(pvDataChannel03)
        self.channel04 = CAClient(pvDataChannel04)
        self.energyPGM = CAClient(pvEnergyPGM)
        self.energyIDGAP = CAClient(pvEnergyIDGAP)

        self.scanReady01 = CAClient(pvScanReady01)
        self.scanReady02 = CAClient(pvScanReady02)
        self.scanReady03 = CAClient(pvScanReady03)
        self.scanReady04 = CAClient(pvScanReady04)

        self.scanStatus = 'Idle'
        self.arrayHead = 0

        self.se = 400
        self.ee = 700

    def atScanStart(self):
        self.scanStatus = 'Idle'
        self.arrayHead = 0
        if not self.startEnergy.isConfigured():
            self.startEnergy.configure()
        if not self.endEnergy.isConfigured():
            self.endEnergy.configure()
        if not self.scanTime.isConfigured():
            self.scanTime.configure()
        if not self.numberOfPoints.isConfigured():
            self.numberOfPoints.configure()
        if not self.startButton.isConfigured():
            self.startButton.configure()
        if not self.buildButton.isConfigured():
            self.buildButton.configure()
        if not self.status.isConfigured():
            self.status.configure()

        if not self.elementCounter.isConfigured():
            self.elementCounter.configure()

        if not self.channel01.isConfigured():
            self.channel01.configure()
        if not self.channel02.isConfigured():
            self.channel02.configure()
        if not self.channel03.isConfigured():
            self.channel03.configure()
        if not self.channel04.isConfigured():
            self.channel04.configure()
        if not self.energyPGM.isConfigured():
            self.energyPGM.configure()
        if not self.energyIDGAP.isConfigured():
            self.energyIDGAP.configure()

        if not self.scanReady01.isConfigured():
            self.scanReady01.configure()
        if not self.scanReady02.isConfigured():
            self.scanReady02.configure()
        if not self.scanReady03.isConfigured():
            self.scanReady03.configure()
        if not self.scanReady04.isConfigured():
            self.scanReady04.configure()

    def atScanEnd(self):
        self.scanStatus = 'Idle'
        self.arrayHead = 0
        if self.startEnergy.isConfigured():
            self.startEnergy.clearup()
        if self.endEnergy.isConfigured():
            self.endEnergy.clearup()
        if self.scanTime.isConfigured():
            self.scanTime.clearup()
        if self.numberOfPoints.isConfigured():
            self.numberOfPoints.clearup()
        if self.startButton.isConfigured():
            self.startButton.clearup()
        if self.buildButton.isConfigured():
            self.buildButton.clearup()
        if self.status.isConfigured():
            self.status.clearup()

        if self.elementCounter.isConfigured():
            self.elementCounter.clearup()

        if self.channel01.isConfigured():
            self.channel01.clearup()
        if self.channel02.isConfigured():
            self.channel02.clearup()
        if self.channel03.isConfigured():
            self.channel03.clearup()
        if self.channel04.isConfigured():
            self.channel04.clearup()
        if self.energyPGM.isConfigured():
            self.energyPGM.clearup()
        if self.energyIDGAP.isConfigured():
            self.energyIDGAP.clearup()

        if self.scanReady01.isConfigured():
            self.scanReady01.clearup()
        if self.scanReady02.isConfigured():
            self.scanReady02.clearup()
        if self.scanReady03.isConfigured():
            self.scanReady03.clearup()
        if self.scanReady04.isConfigured():
            self.scanReady04.clearup()

    #To check the PGM and ID motors are ready for the fast scan
    def checkMotorReady(self):
        c1 = int(float(self.scanReady01.caget()))
        c2 = int(float(self.scanReady02.caget()))
        c3 = int(float(self.scanReady03.caget()))
        c4 = int(float(self.scanReady04.caget()))
        return (c1 == 0 and c2 == 0 and c3 == 0 and c4 == 0)

    def setEnergyRange(self, startEnergy, endEnergy):
        self.se = startEnergy
        self.ee = endEnergy
        self.startEnergy.caput(startEnergy - 3)
        self.endEnergy.caput(endEnergy + 3)

    def setTime(self, scanTime, pointTime):
        numberOfPoints = scanTime / pointTime
        self.scanTime.caput(scanTime)
        self.numberOfPoints.caput(numberOfPoints)

    #trigger the fast scan
    def start(self):
        self.startButton.caput(1)

    #trigger the fast scan
    def build(self):
        self.buildButton.caput('Busy')  # click the build button

    def isBuilt(self):
        strStatus = self.getStatus()
        if strStatus == 'Scan ready':  #Finished building
            return True
        else:
            return False

    #Total 6 status from Epics, plus internal Idle status
    ##	"Scan complete"
    ##	"Scan aborted"
    #	"Moving PGM to midpoint"
    #	"Calculating parameters"
    ##	"Moving IDD and PGM to start position"
    ## "Scan ready"
    ##	"Starting scan move"
    #	"Scanning"
    ##	"Scan complete"
    #	"Idle"
    def getStatus(self):
        newScanStatus = self.status.caget()
        if newScanStatus != self.scanStatus:  # scan status changed
            self.scanStatus = newScanStatus
            print self.scanStatus
        return self.scanStatus

    def isBusy(self):
        strStatus = self.getStatus()
        if strStatus == 'Scan complete':
            print 'fast energy scan finished.'
            return False
        else:
            return True

    def isScanning(self):
        strStatus = self.getStatus()
        if strStatus == 'Scanning' or strStatus == 'Starting scan move':
            return True
        else:
            return False

    #To get the number of valid data from the waveform
    def getDataNumbers(self):
        strLength = self.elementCounter.caget()
        return int(float(strLength))

    def saveData(self):
        numberOfPoints = self.getDataNumbers()
        #self.printData(numberOfPoints);
        self.saveSRSData(numberOfPoints)

    def saveSRSData(self, numberOfPoints):
        srsHeader = [
            " &SRS\n", " SRSRUN=null,SRSDAT=null,SRSTIM=null,\n",
            " SRSSTN='null',SRSPRJ='null    ',SRSEXP='null    ',\n",
            " SRSTLE='                                                            ',\n",
            " SRSCN1='        ',SRSCN2='        ',SRSCN3='        ',\n",
            " &END\n"
        ]

        try:
            runs = NumTracker("tmp")
            nextNum = runs.getCurrentFileNumber()
            #nextNum = runs.incrementNumber()
            path = InterfaceProvider.getPathConstructor().createFromProperty(
                "gda.data.scan.datawriter.datadir")
            fileName = path + "/" + str(nextNum + 1) + ".dat"
            print fileName
            fh = open(fileName, 'w')

            #SRS Header
            for i in range(len(srsHeader)):
                fh.write(srsHeader[i])

            titleLine = '%(v1)s \t %(v2)s \t %(v3)s \t %(v4)s \t %(v5)s \t %(v6)s \n' % {
                'v1': 'PGM Energy',
                'v2': 'ID GAP Energy',
                'v3': 'Channel 1',
                'v4': 'Channel 2',
                'v5': 'Channel 3',
                'v6': 'Channel 4'
            }
            fh.write(titleLine)

            arrayEnergyPGM = self.energyPGM.cagetArrayDouble()
            arrayEnergyIDGAP = self.energyIDGAP.cagetArrayDouble()
            arrayChannel01 = self.channel01.cagetArrayDouble()
            arrayChannel02 = self.channel02.cagetArrayDouble()
            arrayChannel03 = self.channel03.cagetArrayDouble()
            arrayChannel04 = self.channel04.cagetArrayDouble()

            for i in range(numberOfPoints):
                if arrayEnergyPGM[i] < self.se:
                    continue
                if arrayEnergyPGM[i] > self.ee:
                    continue
                #print i, arrayEnergyPGM[i], arrayEnergyIDGAP[i], arrayChannel01[i], arrayChannel02[i], arrayChannel03[i], arrayChannel04[i];
                newLine = '%(v1).8f \t %(v2).8f \t %(v3).8f \t %(v4).8f \t %(v5).8f \t %(v6).8f \n' % {
                    'v1': arrayEnergyPGM[i],
                    'v2': arrayEnergyIDGAP[i],
                    'v3': arrayChannel01[i],
                    'v4': arrayChannel02[i],
                    'v5': arrayChannel03[i],
                    'v6': arrayChannel04[i]
                }
                fh.write(newLine)
            fh.close()
            runs.incrementNumber()
        except:
            print "ERROR: Could not save data into file."

    def printData(self, numberOfPoints):
        arrayEnergyPGM = self.energyPGM.cagetArrayDouble()
        arrayEnergyIDGAP = self.energyIDGAP.cagetArrayDouble()
        arrayChannel01 = self.channel01.cagetArrayDouble()
        arrayChannel02 = self.channel02.cagetArrayDouble()
        arrayChannel03 = self.channel03.cagetArrayDouble()
        arrayChannel04 = self.channel04.cagetArrayDouble()

        for i in range(numberOfPoints):
            print i, arrayEnergyPGM[i], arrayEnergyIDGAP[i], arrayChannel01[
                i], arrayChannel02[i], arrayChannel03[i], arrayChannel04[i]

    def plotWholeData(self, numberOfPoints):
        arrayEnergyPGM = self.energyPGM.cagetArrayDouble()
        arrayEnergyIDGAP = self.energyIDGAP.cagetArrayDouble()
        arrayChannel01 = self.channel01.cagetArrayDouble()
        arrayChannel02 = self.channel02.cagetArrayDouble()
        arrayChannel03 = self.channel03.cagetArrayDouble()
        arrayChannel04 = self.channel04.cagetArrayDouble()

        dataSetPGM = dnp.array([numberOfPoints])

        for i in range(numberOfPoints):
            dataSetPGM.set(arrayEnergyPGM[i], i)

        # Removed as won't work with RCP client. Talk to Mark Basham if need be.
        # dvp=Plotter();
        # dvp.plotOver("Fast Scan Panel", dataSetPGM.getIndexDataSet(), dataSetPGM);

    def plotData(self):
        newHead = self.getDataNumbers()
        if self.arrayHead >= newHead:
            print "No new data added for plotting"
            return
        self.arrayHead = newHead

        #to get new data
        arrayEnergyPGM = self.energyPGM.cagetArrayDouble()
        arrayEnergyIDGAP = self.energyIDGAP.cagetArrayDouble()
        arrayChannel01 = self.channel01.cagetArrayDouble()
        arrayChannel02 = self.channel02.cagetArrayDouble()
        arrayChannel03 = self.channel03.cagetArrayDouble()
        arrayChannel04 = self.channel04.cagetArrayDouble()

        dataSetEnergyPGM = dnp.zeros([newHead])
        dataSetEnergyPGM.setName("PGM Energy")

        dataSetEnergyIDGAP = dnp.zeros([newHead])
        dataSetEnergyIDGAP.setName("ID Gap Energy")

        dataSetChannel01 = dnp.zeros([newHead])
        dataSetChannel01.setName("Channel 1")

        dataSetChannel02 = dnp.zeros([newHead])
        dataSetChannel02.setName("Channel 2")

        dataSetChannel03 = dnp.zeros([newHead])
        dataSetChannel03.setName("Channel 3")

        dataSetChannel04 = dnp.zeros([newHead])
        dataSetChannel04.setName("Channel 4")

        for i in range(0, newHead):
            #print i, arrayEnergyPGM[i], arrayEnergyIDGAP[i], arrayChannel01[i], arrayChannel02[i], arrayChannel03[i], arrayChannel04[i];
            dataSetEnergyPGM[i] = arrayEnergyPGM[i]
            dataSetEnergyIDGAP[i] = arrayEnergyIDGAP[i]
            dataSetChannel01[i] = arrayChannel01[i]
            dataSetChannel02[i] = arrayChannel02[i]
            dataSetChannel03[i] = arrayChannel03[i]
            dataSetChannel04[i] = arrayChannel04[i]
            #print i, arrayEnergyPGM[i], arrayEnergyIDGAP[i], arrayChannel01[i], arrayChannel02[i], arrayChannel03[i], arrayChannel04[i];

        dvp = Plotter()
        indexDataSet = dataSetEnergyPGM.getIndexDataSet()
        #dvp.plot("Data Vector", indexDataSet, [dataSetChannel01, dataSetChannel02, dataSetChannel03, dataSetChannel04]);
        dvp.plot("Fast Scan Panel", dataSetEnergyPGM, [
            dataSetChannel01, dataSetChannel02, dataSetChannel03,
            dataSetChannel04
        ])
示例#42
0
class EpicsPVWithMonitorListener(PseudoDevice, MonitorListener, Runnable):
	'''create a scannable that monitors the EPICS PV value changes and update its value passively. 
	This value is used by a running thread to control the scan processing this object participates in.
	'''
	def __init__(self, name, pvstring, unitstring, formatstring):
		self.setName(name)
		self.setInputNames([name])
		self.Units=[unitstring]
		self.setOutputFormat([formatstring])
		self.setLevel(5)
		self.outcli=CAClient(pvstring)
		self.currenttemp=float(self.rawGetPosition())
		self.monitor=None
		self.thread=None
		self.runThread=False

	def atScanStart(self):
		'''prepare to start scan: creating channel, monitor, and start control thread'''
		if not self.outcli.isConfigured():
			self.outcli.configure()
			self.monitor=self.outcli.camonitor(self)
			self.thread=Thread(self,"Thread: "+self.getName())
			self.runThread=True
			self.thread.start()
	def atScanEnd(self):
		'''clean up after scan finished successfully: remove monitor, destroy channel, and stop control thread'''
		if self.outcli.isConfigured():
			self.outcli.removeMonitor(self.monitor)
			self.monitor=None
			self.outcli.clearup()
			self.runThread=False
			self.thread=None
			
	def rawGetPosition(self):
		''' return current position.'''
		output=0.0
		if not self.outcli.isConfigured():
			self.outcli.configure()
			output=float(self.outcli.caget())
			self.outcli.clearup()
		else:
			output=float(self.outcli.caget())
		return float(output)

	def rawAsynchronousMoveTo(self,position):
		'''Not implemented, this is only a monitoring object'''
		print "object " + self.getName()+" cannot be moved."
		return

	def rawIsBusy(self):
		'''monitoring object never busy'''
		return 0

	def monitorChanged(self, mevent):
		self.currenttemp = float(mevent.getDBR().getDoubleValue()[0])

	def run(self):
	#	print "Thread: " + self.getName() + " started"
		while (self.runThread):
			if (JythonServerFacade.getInstance().getScanStatus() == JythonStatus.RUNNING and self.currenttemp >= float(MAXTEMP)):
				JythonServerFacade.getInstance().pauseCurrentScan()	
				print "Scan paused as temperature " + self.getName() +" returns: "+str(self.currenttemp)
			elif (JythonServerFacade.getInstance().getScanStatus() == JythonStatus.PAUSED and self.currenttemp <= float(MINTEMP)):
				print "Scan resumed as temperature " + self.getName() +" returns: "+str(self.currenttemp)
				JythonServerFacade.getInstance().resumeCurrentScan()
			sleep(10)


	def stop(self):
		'''clean up after scan finished successfully: remove monitor, destroy channel, 
		and stop control thread on emergence stop or unexpected crash. If required, can be used to manually clean up the object.'''
		if not self.monitor == None:
			self.outcli.removeMonitor(self.monitor)
			self.monitor=None
		if self.outcli.isConfigured():	
			self.outcli.clearup()
		if not self.thread == None:
			self.runThread=False
			self.thread=None
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 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
示例#45
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)
示例#46
0
del nt


#=====================Using EPICS caget() and caput to access PVs =========================================
from gda.epics import CAClient

#Create the Client
epicsClient = CAClient()

#Create the PV channels and use the caput and caget method directly
print epicsClient.caget("BL06I-AL-SLITS-01:X:CENTER.RBV")
epicsClient.caput("BL06I-AL-SLITS-01:X:CENTER", -0.55)

#Clear up the channels
epicsClient.clearup();

#==============================================================

#==============================================================

#==============================================================

#==============================================================

#==============================================================

#==============================================================

#==============================================================
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])
示例#48
0
class EpicsReadWriteEnum(ScannableMotionBase):
    '''
    class that creates an instance for a EPICS PV of Enum type.
    '''
    def __init__(self,
                 name,
                 inpvstring,
                 rbvpvstring,
                 formatstring,
                 positions={}):
        '''
        Constructor
        '''
        self.setName(name)
        self.setInputNames([name])
        self.setExtraNames([])
        self.setOutputFormat([formatstring])
        self.setLevel(5)
        self.incli = CAClient(inpvstring)
        self.rbvcli = CAClient(rbvpvstring)
        self.positions = positions

    def atScanStart(self):
        if not self.incli.isConfigured():
            self.incli.configure()
        if not self.rbvcli.isConfigured():
            self.rbvcli.configure()

    def atPointStart(self):
        pass

    def rawGetPosition(self):
        try:
            if not self.rbvcli.isConfigured():
                self.rbvcli.configure()
            sleep(0.5)  # there is no caput callback yet in EPIC
            output = int(self.rbvcli.caget())
            return self.positions[output]
        except:
            raise Exception("%s: Error get current position" % self.getName())

    def rawAsynchronousMoveTo(self, new_position):
        lKey = None
        try:
            if not self.incli.isConfigured():
                self.incli.configure()
            if isinstance(new_position, str):
                lKey = [
                    key for key, value in self.positions.iteritems()
                    if value == new_position
                ][0]
            elif isinstance(new_position, int):
                lKey = int(new_position)
            else:
                raise Exception("Input must be String or Integer.")
            if lKey is None or (lKey < 0 or lKey >= len(self.positions)):
                raise Exception("Request position is not supported.")
            self.incli.caput(lKey)
        except:
            raise Exception("%s: Error set position to '%s'" %
                            (self.getName(), self.positions[lKey]))

    def isBusy(self):
        return False

    def atPointEnd(self):
        pass

    def atScanEnd(self):
        if self.incli.isConfigured():
            self.incli.clearup()
        if self.rbvcli.isConfigured():
            self.rbvcli.clearup()

    def stop(self):
        pass

    def toFormattedString(self):
        return self.name + " : " + self.getInputNames()[0] + " : " + str(
            self.getPosition())
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