def getConfigpars(self): #str = estr("%s" % self.__desc,color="black",type="bold") str = " Trigger delay = %.4f, " % (Pv.get(self.__delayPV)) str += " Gain (0/4) = (%.4f %.4f% .4f %.4f), " % ( Pv.get(self.__gainPV + "0"), Pv.get(self.__gainPV + "1"), Pv.get(self.__gainPV + "2"), Pv.get(self.__gainPV + "3")) return str
def __setDelay(self, delay): if (delay > self.__maxDelay or delay < self.__minDelay): print ' the requested delay has to be between %s and %s' % ( self.__minDelay, self.__maxDelay) print ' leave delay at ', self.__getDelay return Pv.put(self.__delayPV, delay)
def updateConfig(PV, pmgr, objID, cfgID, objDict, cfgDict, allNames, verbose): """ Routine to update the configuration of an obj """ # # PMGR cfg values for comparisons objOld = pmgr.objs[objID] cfgOld = pmgr.cfgs[cfgID] # # Print live values for troubleshooting if verbose: print "\nLive cfg values for {0}".format(pv.get(PV+".DESC")) pprint(objDict) pprint(cfgDict) print "\nPMGR cfg valu es for {0} before update".format(pv.get(PV+".DESC")) pprint(objOld) pprint(cfgOld) print print cfgDict["name"], objDict["name"] cfgDict["FLD_TYPE"] = pmgr.cfgs[cfgID]["FLD_TYPE"] cfgDict["name"] = objDict["name"] if cfgOld["name"] in allNames: allNames.remove(cfgOld["name"]) cfgDict["name"] = incrementMatching(cfgDict["name"], allNames, maxLength=maxLenName) print "Saving configuration..." # # Actually do the update didWork = cfgChange(pmgr, cfgID, cfgDict) return didWork, objOld, cfgOld
def __move(self,pos): Pv.put(self.__pvbase+":GO",0) Pv.put(self.__pvbase+":STOP",1) Pv.put(self.__pvbase+":CTRL_POS",int(pos*1.0e6/self.__getstepsize())) Pv.put(self.__pvbase+":GO",1) Pv.put(self.__pvbase+":STOP",0) pass
def __setGainN(self, igain, num): """ Set ipimb gain as an integer index in the enum. Return True if args were ok, False otherwise. """ if (not isinstance(num, int)): print 'channel number should be an integer!' return False currgain = self.__getGainN(num) if currgain is None: return False if (igain == -1): igain = currgain - 1 elif (igain == 101): igain = currgain + 1 if igain < self.__minGain: igain = self.__minGain elif igain >= self.__maxGain: igain = self.__maxGain - 1 if 0 <= num <= 3: gain_str = self.__gainPV + str(num) else: print 'invalid channel # %f, wont set gain' % num return False Pv.put(gain_str, igain) return True
def __init__(self, parent, pvbase, name, dName=None, isInt=False): layout = QtGui.QHBoxLayout() label = QtGui.QLabel(name) label.setMinimumWidth(100) # label.setMinimumWidth(300) layout.addWidget(label) #layout.addStretch() self.__display = PvDisplay() self.__display.connect_signal() self.__display.setMinimumWidth(300) layout.addWidget(self.__display) parent.addLayout(layout) pvname = pvbase+name print pvname self.pv = Pv.Pv(pvname) self.pv.monitor_start() self.pv.add_monitor_callback(self.update) if dName is not None: dPvName = pvbase+dName self.dPv = Pv.Pv(dPvName) self.dPv.monitor_start() self.dPv.add_monitor_callback(self.update) else: self.dPv = None self.isInt = isInt
def __theta_movement(self, theta): x1, x2, z = ThetaToMotors(theta) z_now = self.z.wm() try: if z_now < z: print 'moving z to %+4.f' % z self.z.mv(z) self.z.wait() print 'moving x1 to %+4.f and x2 to %.4f\n' % (x1, x2) self.x1.mv(x1) self.x2.mv(x2) self.waitAll() else: print 'moving x1 to %+4.f and x2 to %.4f\n' % (x1, x2) self.x1.mv(x1) self.x2.mv(x2) self.x1.wait() self.x2.wait() print 'moving z to %+4.f' % z self.z.mv(z) self.waitAll() except KeyboardInterrupt: self.stop() finally: Pv.put(self._theta_pv, self.wmTheta())
def set_testburst_rate(self, rate): if not (rate in self.__dictRateToEnum): print "!! Rate should be one of:", print self.__dictRateToEnum.keys() else: Pv.put("PATT:SYS0:1:TESTBURST.N", 0) Pv.put("PATT:SYS0:1:TESTBURSTRATE", self.__dictRateToEnum[rate])
def __init__(self, parent, partition, module, name, dName=None, isInt=False): self.layout = QtGui.QHBoxLayout() self.label = QtGui.QLabel(name) self.layout.addWidget(self.label) self.layout.addStretch() # self.display = QtGui.QLabel("-") self.display = PvDisplay() self.display.connect_signal() self.layout.addWidget(self.display) parent.addLayout(self.layout) if module is None: pvbase = "DAQ:" + partition + ":" else: pvbase = "DAQ:" + partition + ":" + module + ":" pvname = pvbase + name print pvname self.pv = Pv.Pv(pvname) self.pv.monitor_start() self.pv.add_monitor_callback(self.update) if dName is not None: dPvName = pvbase + dName self.dPv = Pv.Pv(dPvName) self.dPv.monitor_start() self.dPv.add_monitor_callback(self.update) else: self.dPv = None self.isInt = isInt
def switch(self): """ switches illuminator """ onoff = Pv.get(self.pv_OnOff) if onoff == 1: Pv.put(self.pv_OnOff, 1) elif onoff == 0: Pv.put(self.pv_OnOff, 0)
def getDetROI(self): return [ int(Pv.get(self.pvBase + ":det_roi_x1")), int(Pv.get(self.pvBase + ":det_roi_y1")), int(Pv.get(self.pvBase + ":det_roi_x2")), int(Pv.get(self.pvBase + ":det_roi_y2")) ]
def __init__(self, pvname): self.pvname = pvname self.__pressure = Pv.Pv('%s:PMON' % pvname) self.__state = Pv.Pv('%s:STATE' % pvname) self.__state.set_string_enum(True) self.__pres_status = Pv.Pv('%s:PSTATMON' % pvname) self.__pres_status.set_string_enum(True)
def __init__(self, pvname='GDET:FEE1'): self.pvname = pvname self.__ch0 = Pv.Pv('%s:241:ENRC' % pvname) self.__ch0_egu = Pv.Pv('%s:241:ENRC.EGU' % pvname) self.__ch0_egu.set_string_enum(True) self.__ch1 = Pv.Pv('%s:242:ENRC' % pvname) self.__ch1_egu = Pv.Pv('%s:242:ENRC.EGU' % pvname) self.__ch1_egu.set_string_enum(True)
def set_fburst(self, f="Full"): f.replace(" ", "") # remove spaces if not (f in self.__freqs): print "!! Frequency should be one of:", print self.__freqs.keys() else: Pv.put("PATT:SYS0:1:MPSBURSTRATE", self.__freqs[f])
def close(self, fast=False): """ close the shutter; the option fast when enable skip the test that makes sure that the output is not triggered by any event code""" #if (not fast): #self.evr.disableAllEvents() #self.evr.polarity(not self.__polarity) self._cleanup() Pv.put(self._PVname('S_CLOSE'), 1)
def __init__(self,name,pv_base,pv_TTL,Vlow=0,Vhigh=5): self.name = name self.pv_base = pv_base self.pv_TTL = pv_TTL self.Vhigh = Vhigh self.Vlow = Vlow Pv.put(pv_base,5) Pv.put(pv_TTL,0)
def speed(self,value=None): if (value is not None): Pv.put(self.speed_pv,value) if (self.speed_rbv is None): s=Pv.get(self.speed_pv) else: s=Pv.get(self.speed_rbv) return s
def __init_states(self): """ background thread to set up inpos, etc. once possible """ self.__preset_inp.wait_ready() self.__preset, _, _ = self.__preset_inp.value.partition(" ") self.__inpos = Pv.Pv('%s:IN_SET'%self.__preset) self.__outpos = Pv.Pv('%s:OUT_SET'%self.__preset) self.__indelta = Pv.Pv('%s:IN_DELTA'%self.__preset) self.__outdelta = Pv.Pv('%s:OUT_DELTA'%self.__preset)
def __setBias(self, bias): #fix this, unprotexted now if (bias > self.__maxBias or bias < self.__minBias): print ' the requested bias has to be between %s and %s' % ( self.__minBias, self.__maxBias) print ' leave bias at ', self.__getBias() return Pv.put(self.__biasPV, bias)
def gain(self,value=None): ''' Reads or changes gain in the PD feedback loop usage: gain(): reads back current gain gain(value): sets gain to passed value ''' if (value is None): return Pv.get(self.__pv_gain) else: Pv.put(self.__pv_gain,value)
def return_position(self): ''' returns the target stage to the last saved position. the target position is save with .save() ''' print 'moves the xyzstage ' + self._name + 'to the last saved position' self.x.mv(Pv.get(self._savepvx)) self.y.mv(Pv.get(self._savepvy)) self.z.mv(Pv.get(self._savepvz))
def moveDSPhi(self, phi): """ Move physical motors in sample/detector stages to get Phi reflection geometry """ if not self.assertLimitsDSPhi(phi): return self.reflectdet.move_silent(phi) self.phi.move_silent(phi) if self.pvBase is not None: Pv.put(self.pvBase + ":GON:REF",phi) pass
def moveEwithVernier(self, E, vernierThresKeV=.003): """ E in keV """ if (E > 2000): E = E / 1e3 Ever0 = Pv.get(self.__vernierPV) / 1000. if n.abs(Ever0 - E) > vernierThresKeV: Pv.put(self.__vernierPV, E * 1000) alio = EToAlio(E) self.alio.move(alio)
def move(self, position): if position in self.__positionMap: curpos = self.__getPosition() if curpos == positoin: print "WARNING: Stopper is already %s\n" % (position) else: Pv.put(self.__getPV(self.__cmdPV), position) else: print "ERROR: '%s' is not a valid position, please use one of: %s\n" % ( position, __positionMap.keys())
def trip(self, value=None): """ Sets or Returns the gauge trip point for the vacuum PLC """ previous_trip = Pv.get(self.__pstatsprbck) if (value is not None): Pv.put(self.__pstatspdes, value) s = "Resetting PLC trip point of `%s` from %.4g to %.4g" % ( self.name, previous_trip, value) logprint(s, print_screen=True) else: print "%s trip point is %.4g" % (self.name, previous_trip)
def disableAllEventsForGivenTrigger(self, trigger): """ Disable all events code for a give trigger """ if (trigger > self.__ntriggers - 1): print "in disableAllEventsForGivenTrigger you asked for a trigger that is not defined ... exiting" return 0 for i in range(self.__nevent_numbers): names = self.__getpvnames(i + 1) # starts with 1 and not zero Pv.put(names[trigger], 0) return 1
def set(self, value): if (self._set is not None): self._set(value) elif (self.pvoff is not None): offset = value - self.direction * self.wm_dial() Pv.put(self.pvoff, offset) sleep(0.1) # gives epics time to update offset pv self.wm() else: print "user position not defined for this motor"
def speed(self,value=None): """returns the speed, or sets it. This is a temporary hack, particularly for the nanoc for the tychography """ if value==None: v=Pv.get(self.pvspeed) return v else: Pv.put(self.pvspeed,str(value))
def __init__(self, name, pvname): self.__name = name self.__pvbase = pvname self.__get_flow = Pv.Pv('%s:GetFlowSetpoint' % pvname, initialize=False) self.__egu = Pv.Pv('%s:GetFlowSetpoint.EGU' % pvname, initialize=False) self.__set_flow = Pv.Pv('%s:SetFlowSetpoint' % pvname, initialize=False) self.__close = Pv.Pv('%s:CloseValve.PROC' % pvname, initialize=False) self.__set_operating_mode = Pv.Pv('%s:SetOperatingMode' % pvname, initialize=False)
def __init__(self): self.howto() #self.elog = pypsElog.pypsElog() for pv, item in self._pvs.items(): print 'Adding ', pv, item item['Pv'] = Pv.Pv(item['pv']) setattr(self, pv, item['default']) Pv.put(item['pv'] + '.DESC', item['desc']) self.EXP = 'current' self.run()
def fixSN(pmgr, PV): pv.put(PV + ".RINI", 1) # Re-initialize motor to get accurate SN objID = objFromPV(pmgr, PV) pmgr.updateTables() d = pmgr.objs[objID] # Set up Pv object so we can specify a timeout and wait for init. SNPV = pv.Pv(PV + ".SN") SNPV.connect(timeout=5) SN = SNPV.get() # Pull the value we need SNPV.disconnect() d["FLD_SN"] = SN transaction(pmgr, "objectChange", objID, d)
def get_motor_PVs(partialPV): motorPVs = [] i = 1 while i != 40: basePV = "%s:%02d"%(partialPV, i) print basePV try: SN = pv.get(basePV + ".SN") if len(SN) >= 8: motor_PVs[sn] = basepv print "PV: {0} is active".format(basePV) motorPVs += basePV except: pass return motorPVs
def motorPrelimChecks(PV, hutches, objType, verbose=False): """ Runs prelimenary checks on the paramter manager inputs, and returns a valid hutch name, and serial number. Returns false for any of the variables if there are any issues when obtaining them. """ SN = False # Check for valid hutch entry if not hutches: hutches.append(PV[0][:3].lower()) for hutch in hutches: if hutch not in supportedHutches: print "Invalid hutch: {0}. Only supports sxr and amo.".format(hutch.upper()) print "Removing hutch: {0}".format(hutch.upper()) hutches.remove(hutch) # Replace sxd with amo and sxr if present if 'sxd' in hutches: if 'amo' not in hutches: hutches.append('amo') if 'sxr' not in hutches: hutches.append('sxr') hutches.remove('sxd') if not hutches: return hutches, objType, SN if verbose: print "Hutches: {0}".format(hutches) # Check for valid obj entry. Pmgr only supports ims motors as of 1/1/2016 if str(objType) in supportedObjTypes: pass elif ":MMS:" in PV[0]: objType = "ims_motor" else: print "Unknown device type for {0}".format(PV[0]) objType = False return hutches, objType, SN # Get the motor serial number via caget i = 0 SN = {} for motorPV in PV: while i < nTries: try: SN[motorPV] = pv.get(motorPV + ".SN") break except: i+=1 if not SN: print "Failed to get motor serial number for motor {0}".format(motorPV) continue return hutches, objType, SN
def dumbMotorCheck(PV): """ Takes in a PV attempts caget on the PN nTries times and then checks the PN to see if it is MFI. Returns True if MFI is in the PN string, false if not. """ PN = "" i = 0 while i < nTries: try: PN = pv.get(PV + ".PN") break except: i += 1 if "MFI" in PN: return True else: return False
def getCfgVals(pmgr, PV): """ Returns a dictionary of the live cfg fields associated with a PV """ PV = PV.upper() configFields = listCfgFields(pmgr) cfgDict = getFieldDict(pmgr, PV, configFields) name = None try: name = pv.get(PV +".DESC") except: name = "Unknown" cfgDict["name"] = name cfgDict["FLD_TYPE"] = "{0}_{1}".format(name, PV[:4]) return cfgDict
def getFieldDict(pmgr, PV, fields): fldDict = {} for field in fields: if field != "FLD_TYPE": pvExt = pmgr.fldmap[field]["pv"] val = pv.get(PV + pvExt) if val is None: return None fieldDict = pmgr.fldmap[field] if "enum" in fieldDict: choices = fieldDict["enum"] if val >= len(choices): print "WARNING: index mismatch in field {0}.".format(field) print "An ioc has been updated without updating the Parameter Manager!" val = len(choices) - 1 val = fieldDict["enum"][val] fldDict[field] = val return fldDict
def pvConfig(pmgr, PV): """ Returns live config dict associated with PV, or None """ configFields = listCfgFields(pmgr) cfgDict = {} for field in configFields: if field != "FLD_TYPE": pvExt = pmgr.fldmap[field]["pv"] val = pv.get(PV + pvExt) if val is None: return None fieldDict = pmgr.fldmap[field] if "enum" in fieldDict: choices = fieldDict["enum"] if val >= len(choices): print "WARNING: index mismatch in field {0}.".format(field) print "An ioc has been updated without updating the Parameter Manager!" val = len(choices) - 1 val = fieldDict["enum"][val] cfgDict[field] = val return cfgDict
def defaultName(pmgr, PV): """ Returns a default name for the config associated with PV """ name = pv.get(PV + ".DESC") return nextName(pmgr, name)
# Run some prelimenary checks if verbose: print "\nPerforming preliminary checks for pmgr paramters\n" if arguments["--hutch"]: hutches = [hutch.lower() for hutch in arguments["--hutch"].split(',')] else: hutches = [] hutches, objType, SNs = utlp.motorPrelimChecks(motorPVs, hutches, None, verbose) if not hutches or not objType or not SNs: if zenity: system("zenity --error --text='Failed prelimenary checks'") exit("\nFailed prelimenary checks\n") # Loop through each of the motorPVs for PV in motorPVs: # Print some motor info print "Motor PV: {0}".format(PV) m_DESC = pv.get(PV + ".DESC") print "Motor description: {0}".format(m_DESC) if not SNs[PV]: print "Could not get SN for motor: {0}.".format(m_DESC) print "Skipping motor.\n" continue SN = SNs[PV] if verbose: print "Motor SN: {0}\n".format(SN) # If inputted apply, run apply routine and sure it is a smart motor if arguments["apply"]: if not utlp.dumbMotorCheck(PV): applyConfig(PV, hutches, objType, SN, verbose, zenity) else: print "Motor connected to PV:{0} is a dumb motor, must use \
def applyConfig(PV, hutches, objType, SN, verbose, zenity, dumb=False, dumb_cfg=None, dumb_confirm=True): """ Searches the pmgr for the correct SN and then applies the configuration currently associated with that motor. If it fails to find either a SN or a configuration it will exit. """ # Find the most recently updated obj in the pmgrs of each hutch inputted if verbose: print "Getting most recently updated obj\n" objID, pmgr = utlp.getMostRecentObj(hutches, SN, objType, verbose) if not objID or not pmgr: return # # Work-around for applyConfig # # applyObject uses the rec_base field of the obj to apply the PV values # # so for it to work properly we have to set rec_base to the correct # # PV value associated with that motor at the moment # Change rec_base field to the base PV and the port field to the live port obj = pmgr.objs[objID] port = pv.get(PV + ".PORT") if obj["rec_base"] != PV or obj["FLD_PORT"] != port: obj["rec_base"] = PV obj["FLD_PORT"] = port utlp.transaction(pmgr, "objectChange", objID, obj) if dumb: # Get all the cfg names allNames = {} for hutch in hutches: pmgr = utlp.getPmgr(objType, hutch, verbose) names = utlp.allCfgNames(pmgr) for name in names: allNames[name] = hutch # Make sure the user inputs a correct configuration cfgName = dumb_cfg if dumb_confirm: confirm = "no" while(confirm[0].lower() != "y"): if cfgName is not None: print "Closest matches to your input:" closest_cfgs = get_close_matches(cfgName, allNames.keys(), 15, 0.1) pprint(closest_cfgs) cfgName = raw_input("Please input a configuration to apply or search:\n") if cfgName not in allNames: print "Invalid configuration inputted." continue confirm = raw_input("\nAre you sure you want to apply {0} to {1}?\n".format(cfgName, PV)) elif cfgName not in allNames: print "Invalid configuration {} chosen.".format(cfgName) return # Get the selected configuration's ID pmgr = utlp.getPmgr(objType, allNames[cfgName], verbose) cfgID = utlp.cfgFromName(pmgr, cfgName) if not cfgID: print "Error when getting config ID from name: {0}".format(cfgName) if zenity: system("zenity --error --text='Error: Failed to get cfgID'") return # Set configuration of dumb motor pmgr object if obj["config"] != cfgID: status = False status = utlp.setObjCfg(pmgr, objID, cfgID) if not status: print "Failed set cfg to object" if zenity: system("zenity --error --text='Error: Failed to set cfgID to object'") return # Set the obj name and desc to use the cfg name (only for dumb motors) obj["name"] = utlp.nextObjName(pmgr, pmgr.cfgs[cfgID]["name"]) obj["FLD_DESC"] = pmgr.cfgs[cfgID]["name"] utlp.transaction(pmgr, "objectChange", objID, obj) # For future diff comparison cfgOld = utlp.getCfgVals(pmgr, PV) objOld = utlp.getObjVals(pmgr, PV) # Apply the pmgr configuration to the motor print "Applying configuration, please wait..." status = False status = utlp.objApply(pmgr, objID) if not status: print "Failed to apply: pmgr transaction failure" if zenity: system("zenity --error --text='Error: pmgr transaction failure'") return print "Successfully completed apply" # Try to print the diffs cfgNew = utlp.getCfgVals(pmgr, PV) objNew = utlp.getObjVals(pmgr, PV) try: utlp.printDiff(pmgr, objOld, cfgOld, objNew, cfgNew, verbose) except: pass if zenity: system('zenity --info --text="Configuration successfully applied"')