def test_force_connect(): pv = PV(pvnames.double_arrays[0], auto_monitor=True) print("Connecting") assert pv.wait_for_connection(5.0) print("SUM", pv.get().sum()) time.sleep(3) print("Disconnecting") pv.disconnect() print("Reconnecting") pv.force_connect() assert pv.wait_for_connection(5.0) called = {'called': False} def callback(value=None, **kwargs): called['called'] = True print("update", value.sum()) pv.add_callback(callback) time.sleep(1) assert pv.get() is not None assert called['called']
def addPV(self, name): if name is not None and name not in self.pvlist: pv = PV(str(name), callback=self.onPVChange) pv.get() conn = False if pv is not None: if not pv.connected: pv.wait_for_connection() conn = pv.connected msg = 'PV not found: %s' % name if conn: msg = 'PV found: %s' % name self.pvmsg.SetLabel(msg) if not conn: return self.pvlist.append(name) self.pvdata[name] = [(time.time(), pv.get())] i_new = len(self.pvdata) new_shown = False for choice in self.pvchoices: if choice is None: continue cur = choice.GetSelection() choice.Clear() choice.SetItems(self.pvlist) choice.SetSelection(cur) if cur == 0 and not new_shown: choice.SetSelection(i_new) new_shown = True self.needs_refresh = True
def test(self): pv_w = PV(iocname + pv_write) pv_r = PV(iocname + pv_read) if type == "PUTGET": pv_w.put(value) time.sleep(DELAY) got = pv_r.get(as_string=True) fail_string = 'The PV values do not match, sent %s got %s but expected %s' % (value, got, expected) self.assertEqual(expected, got, fail_string) elif type == "PUTERROR": self.assertRaises(ValueError, pv_w.put, value) elif type == "GET": as_str=False dbl = 0 try: dbl = float(expected) except: as_str=True dbl = expected got = pv_r.get(as_string=as_str) fail_string = 'The value read was not as expected, got %s but expected %s' % (got, dbl) self.assertEqual(dbl, got, fail_string) elif type == "EQUAL": got1 = pv_r.get(as_string=True) got2 = pv_w.get(as_string=True) fail_string = 'The PV values do not match, got %s and %s' % (got1, got2) self.assertEqual(got1, got2, fail_string)
def test_waveform_get_with_count_arg(self): with no_simulator_updates(): wf = PV(pvnames.char_arr_pv, count=32) val=wf.get() self.assertEquals(len(val), 32) val=wf.get(count=wf.nelm) self.assertEquals(len(val), wf.nelm)
def test_get1(self): write('Simple Test: test value and char_value on an integer\n') with no_simulator_updates(): pv = PV(pvnames.int_pv) val = pv.get() cval = pv.get(as_string=True) self.failUnless(int(cval)== val)
def test_get1(self): write('Simple Test: test value and char_value on an integer\n') pause_updating() pv = PV(pvnames.int_pv) val = pv.get() cval = pv.get(as_string=True) self.failUnless(int(cval)== val) resume_updating()
def test_putwait(self): write('Put with wait (using real motor!) \n') pv = PV(pvnames.motor1) # this works with a real motor, fail if it doesn't connect quickly if not pv.wait_for_connection(timeout=0.2): self.skipTest('Unable to connect to real motor record') val = pv.get() t0 = time.time() if val < 5: pv.put(val + 1.0, wait=True) else: pv.put(val - 1.0, wait=True) dt = time.time()-t0 write(' put took %s sec\n' % dt) self.failUnless( dt > 0.1) # now with a callback! global put_callback_called put_callback_called = False def onPutdone(pvname=None, **kws): print( 'put done ', pvname, kws) global put_callback_called put_callback_called = True val = pv.get() if val < 5: pv.put(val + 1.0, callback=onPutdone) else: pv.put(val - 1.0, callback=onPutdone) t0 = time.time() while time.time()-t0 < dt*1.50: time.sleep(0.02) write(' put should be done by now? %s \n' % put_callback_called) self.failUnless(put_callback_called) # now using pv.put_complete val = pv.get() if val < 5: pv.put(val + 1.0, use_complete=True) else: pv.put(val - 1.0, use_complete=True) t0 = time.time() count = 0 while time.time()-t0 < dt*1.50: if pv.put_complete: break count = count + 1 time.sleep(0.02) write(' put_complete=%s (should be True), and count=%i (should be>3)\n' % (pv.put_complete, count)) self.failUnless(pv.put_complete) self.failUnless(count > 3)
class Shutter(StandardDevice): #CALLBACK FUNCTION FOR THE SHUTTER STATUS PV #def onStatusChange(self, **kw): #self._open = not self._open #CONSTRUCTOR OF SHUTTER CLASS def __init__(self, pvStatusName="", pvControlName="", pvHutchName="", mnemonic="", invert=False): StandardDevice.__init__(self, mnemonic) self.delay = 0.01 self.invert = invert self.pvStatus = PV(pvStatusName) self.pvControl = PV(pvControlName) self.pvHutch = PV(pvHutchName) #IF POSSIBLE, OPEN THE SHUTTER AND WAIT UNTIL THE SHUTTER IS REALLY OPEN def open(self): if not self.isHutchReady(): raise Exception('Error: ','Hutch Not Ready') try: if not self.isOpen(): self.pvControl.put(1, wait=True) while not self.isOpen(): sleep(self.delay) else: print('Warning: ','Shutter already open') except Exception as e: print(e.args[0],e.args[1]) #IF POSSIBLE, CLOSE THE SHUTTER AND WAIT UNTIL THE SHUTTER IS REALLY CLOSE def close(self): try: if self.isOpen(): self.pvControl.put(1, wait=True) while self.isOpen(): sleep(self.delay) else: print('Warning: ','Shutter already closed') except Exception as e: print(e.args[0],e.args[1]) def isHutchReady(self): if(self.invert): return 1 - self.pvHutch.get() else: return self.pvHutch.get() def isOpen(self): if(self.invert): return 1 - self.pvStatus.get() else: return self.pvStatus.get()
def test_DoubleVal(self): pvn = pvnames.double_pv pv = PV(pvn) pv.get() cdict = pv.get_ctrlvars() write( 'Testing CTRL Values for a Double (%s)\n' % (pvn)) self.failUnless('severity' in cdict) self.failUnless(len(pv.host) > 1) self.assertEqual(pv.count,1) self.assertEqual(pv.precision, pvnames.double_pv_prec) units= ca.BYTES2STR(pv.units) self.assertEqual(units, pvnames.double_pv_units) self.failUnless(pv.access.startswith('read'))
def test_subarray_zerolen(self): subarr1 = PV(pvnames.zero_len_subarr1) subarr1.wait_for_connection() val = subarr1.get(use_monitor=True, as_numpy=True) self.assertIsInstance(val, numpy.ndarray, msg='using monitor') self.assertEquals(len(val), 0, msg='using monitor') self.assertEquals(val.dtype, numpy.float64, msg='using monitor') val = subarr1.get(use_monitor=False, as_numpy=True) self.assertIsInstance(val, numpy.ndarray, msg='no monitor') self.assertEquals(len(val), 0, msg='no monitor') self.assertEquals(val.dtype, numpy.float64, msg='no monitor')
def test_emptyish_char_waveform_no_monitor(self): '''a test of a char waveform of length 1 (NORD=1): value "\0" without using auto_monitor ''' with no_simulator_updates(): zerostr = PV(pvnames.char_arr_pv, auto_monitor=False) zerostr.wait_for_connection() # elem_count = 128, requested count = None, libca returns count = 1 zerostr.put([0], wait=True) time.sleep(0.2) self.assertEquals(zerostr.get(as_string=True), '') numpy.testing.assert_array_equal(zerostr.get(as_string=False), [0]) self.assertEquals(zerostr.get(as_string=True, as_numpy=False), '') numpy.testing.assert_array_equal(zerostr.get(as_string=False, as_numpy=False), [0]) # elem_count = 128, requested count = None, libca returns count = 2 zerostr.put([0, 0], wait=True) time.sleep(0.2) self.assertEquals(zerostr.get(as_string=True), '') numpy.testing.assert_array_equal(zerostr.get(as_string=False), [0, 0]) self.assertEquals(zerostr.get(as_string=True, as_numpy=False), '') numpy.testing.assert_array_equal(zerostr.get(as_string=False, as_numpy=False), [0, 0])
def __init__(self,prefix=basename,med='13SDD1:',nelem=4,env_pvfile=env_pvfile): class pvs: pass self.state = state.OFFLINE self.med_name = med self.nelem = nelem connect_to_mca_pvs(med,nelem) self.pv = pvs() self.med = pvs() self.med.start = PV("%sEraseStart" % med) self.med.ctime = PV("%sPresetReal" % med) self.med.status = PV("%sAcquiring" % med) self.med.presetmode = PV("%sPresetMode" % med) self.pv.status = PV("%sStatus" % prefix) self.pv.mode = PV("%sMode" % prefix) self.pv.ctime = PV("%sCountTime"% prefix) self.pv.req = PV("%sRequest" % prefix) self.pv.host = PV("%shost" % prefix) self.pv.dir = PV("%sdir" % prefix) self.pv.subdir = PV("%ssubdir" % prefix) self.pv.base = PV("%sfilebase" % prefix) self.pv.format = PV("%sformat" % prefix) self.pv.ext = PV("%sfileext" % prefix) self.pv.msg = PV("%sMSG" % prefix) self.pv.tstamp = PV("%sTSTAMP" % prefix) self.pv.unixts = PV("%sUNIXTS" % prefix) time.sleep(0.1) self.pv.req.add_callback(self.onRequest) self.pv.mode.add_callback(self.onModeChange) self.med.status.add_callback(self.onDetectorState) self.automode = self.pv.mode.get() self.manual_collection = False self.datafile = 'Temp File' self.env_pvs = None self.read_envfile(env_pvfile) self.mcas = [] for i in range(nelem): m = PV( "%smca%i.VAL" % (self.med_name,i+1)) m.get() self.mcas.append(m) self.state = state.IDLE
def test_subarray_1elem(self): with no_simulator_updates(): # pv = PV(pvnames.zero_len_subarr1) pv = PV(pvnames.double_arr_pv) pv.wait_for_connection() val = pv.get(count=1, use_monitor=False) print('val is', val, type(val)) self.assertIsInstance(val, numpy.ndarray) self.assertEqual(len(val), 1) val = pv.get(count=1, as_numpy=False, use_monitor=False) print('val is', val, type(val)) self.assertIsInstance(val, list) self.assertEqual(len(val), 1)
def init(self): initial_check = util.expect(self.proc, ["A1"]) init = PV('initiate') a_in_1 = PV('analogIn1') poll(evt=1.e-5, iot=0.01) before_init = a_in_1.get() init.put(1) poll(evt=1, iot=1) after_init = a_in_1.get() return before_init, after_init
def buffering_low(self): status = PV('status') if not util.check_device('C1', self.proc) and status.get() in range(0,3): print "device not connected" return False count3 = PV('in_counts_3') low_3 = PV('low_limit_3') low_4 = PV('low_limit_4') trig_buffer = PV('trig_buffer') init = PV('initiate') poll(evt=1.e-5, iot=0.01) data3 = [] def getCount3(pvname, value, **kw): data3.append(value) if util.put_check(low_3, 0.0) and util.put_check(low_4, 0.0) and util.put_check(trig_buffer, 1000) and util.put_fuzzy('analog_out_period', 10e-5, 0.05): pass else: print "setting not taking place" return False, False count3.add_callback(getCount3) init.put(1) t0 = time.time() while time.time() - t0 < 3: poll(evt=1.e-5, iot=0.01) time.sleep(2) return len(data3)
def fault_codes(self): connect = self.proc.expect( [pexpect.TIMEOUT, pexpect.EOF, 'success'], timeout=5) if connect != 2: return -1 cmux_0, cmux_1, cmux_2, cmux_3 = PV('c_mux_0'), PV('c_mux_1'), PV('c_mux_2'), PV('c_mux_3') fault_message = PV('r_psu_fault_message') faults = [] perms = itertools.product([0,1], repeat=4) for i,j,k,c in list(perms): #print i,j,k,c cmux_0.put(i) poll(evt=0.1, iot=0.1) cmux_1.put(j) poll(evt=0.1, iot=0.1) cmux_2.put(k) poll(evt=0.1, iot=0.1) cmux_3.put(c) poll(evt=0.1, iot=0.1) faults.append(fault_message.get()) #print cmux_1.get(), cmux_2.get(), cmux_3.get(), cmux_4.get() return faults
class PvString: def __init__(self, pvname, name=None, elog=None): self.name = name self.pvname = pvname self._pv = PV(pvname) self._elog = elog self.alias = Alias(name, channel=self.pvname, channeltype="CA") def get_current_value(self): return self._pv.get() def set_target_value(self, value, hold=False): changer = lambda value: self._pv.put(bytes(value, "utf8"), wait=True) return Changer(target=value, parent=self, changer=changer, hold=hold, stopper=None) def __repr__(self): return self.get_current_value() def __call__(self, string=None): if not string is None: self.set_target_value(string) else: return self.get_current_value()
def stress_test(self): if not self.connected: print "Device not connected" return False trig_stop = PV('stop_trigger_source') for i in range(0, 10): trig_stop.put(i % 2) trig_stop.get() poll(evt=0.01, iot=0.01) expect = self.proc.expect([pexpect.TIMEOUT, pexpect.EOF, 'Announce\(\) success', 'fail', 'memory'], timeout=0.1) print self.proc.after print i%2 if expect in (3,4): return self.proc.after, self.proc.before return "passed all"
def buffering(self, value): check = util.expect(self.proc, ["C1"]) count3 = PV('in_counts_3') low3 = PV('low_limit_3') trig_buffer = PV('trig_buffer', auto_monitor=False) int_time = PV('analog_out_period') init = PV('initiate') poll(evt=1.e-5, iot=0.01) data = [] #camonitor('trig_buffer') def getCount1(pvname, value, **kw): data.append(value) util.put_check(low3, 0.0) util.put_check(trig_buffer, value) util.put_fuzzy('analog_out_period', 10e-5, 0.05) print "set value " + str(value) print "buffer value " + str(trig_buffer.get()) #time.sleep(5) #print "buffer value " + str(trig_buffer.get()) count3.add_callback(getCount1) init.put(1) poll(evt=1.e-5, iot=0.01) t0 = time.time() while time.time() - t0 < 5: poll(evt=1.e-5, iot=0.01) run1 = len(data) return run1
class MDAConvert(): """ An object that watches for a new MDA file and converts it to columnar ascii and saves to users directory """ def __init__(self): self.save_record = 'SR13ID01HU02IOC02:saveData_' self.scan_record = 'SR13ID01HU02IOC02:scan1.' self.mda_path = '/data/ioc2/' self.dataMount = '/data/pilatus1M/' self.dataSubDirectory = 'scan' self.dataFullPath = '' self.experimentPathPV = PV('13PIL1:cam1:FilePath_RBV',callback=self.onExpFilePath) self.scanDataStatePV = PV('%sDSTATE' % (self.scan_record,), callback=self.onScanDSTATE) self.scanFileNamePV = PV('%sfileName' % (self.save_record,)) self.redis = redis.StrictRedis(host='localhost', port=6379, db=0) def onExpFilePath(self, pvname, value, char_value, **kwargs): self.dataFullPath = '%s%s/%s/' % (self.dataMount,'/'.join(char_value.split('/')[-5:-2]),self.dataSubDirectory) def onScanDSTATE(self, pvname, value, **kwargs): if value == 7: thread=Thread(target=self.convertMDA) thread.daemon = True thread.start() def convertMDA(self): mdaFile = '%s%s' % (self.mda_path,self.scanFileNamePV.get(as_string=True)) print mdaFile try: mda = readMDA(mdaFile, verbose=False) except Exception: return data = mda[-1] results = [p.data for p in data.p] results.extend([d.data for d in data.d]) results = zip(*results) names = [p.name for p in data.p] names.extend([d.name for d in data.d]) datFileName = '%s%s.csv' % (self.dataFullPath, os.path.splitext(os.path.basename(mdaFile))[0]) print datFileName with open(datFileName,'w') as f: print >> f, ', '.join('%s' % name for name in names) for line in results: print >> f, ', '.join('%s' % data for data in line) epn = self.dataFullPath.split('/')[-3] try: self.redis.rpush('MDA:%s' % (epn,),datFileName) self.redis.publish('MDA:NewFile',datFileName) except redis.ConnectionError: print 'Error connecting to redis database'
class pv_buffer(): def __init__(self, pv, buffer_size): self.pvname=pv self.pv = PV(pv,auto_monitor=True) self.data = np.array([self.pv.get()]) self.tstart = time.time() self.time = np.array([self.tstart]) self.buffer_size=buffer_size def poll(self): t=time.time() v=caget(self.pvname)#self.pv.get() #print(t,v) if(len(self.data)<self.buffer_size): self.time = np.append(self.time,t) self.data = np.append(self.data,v) else: self.time[:-1]=self.time[1:] self.time[-1]=t self.data[:-1]=self.data[1:] self.data[-1]=v return self.time-self.tstart, self.data
class EpicsEntry: def __init__(self, EntryName, EpicsRecord, Unit = "", Scale = 1.0, Digits = 2): self.name = EntryName self.record = PV(EpicsRecord) self.value = self.updatefn() self.unit = Unit self.scale = Scale self.digits = Digits def getAlarm(self): if self.record.connected: return self.record.severity return 3 def updatefn(self): if self.record.connected: return self.record.get() return float('nan') def GetValue(self): return self.value def GetStr(self,width): halfw = int(width/2) fmtstr = "{:<"+str(halfw - 1)+"} {:>"+str(halfw -5)+"."+str(self.digits)+"f} {:<5}" if self.getAlarm() == 3: return self.name+": not connected" return fmtstr.format(self.name+":",self.value * self.scale,self.unit)
def __init__(self, pvname, pvnumber=None, rbv=None, pvtype=None): if pvnumber and not pvname: pvname = PV(pvPrefix + ':SCANPV' + str(pvnumber) + ':PVNAME').get() self.pvname = pvname if self.pvname: self.pvnumber = pvnumber self.rbv = rbv # Get PV type from 'PV type' menu pvtypePv = PV(pvPrefix + ':SCANPV' + str(self.pvnumber) + ':PVTYPE') if not pvtype: pvtype = pvtypePv.get() # Create PV instance if pvtype == 1: scanpv = Motor(self.pvname, self.pvnumber) elif pvtype == 2: scanpv = PolluxMotor(self.pvname, self.pvnumber) elif pvtype == 3: scanpv = BeckhoffMotor(self.pvname, self.pvnumber) elif pvtype == 4: scanpv = Magnet(self.pvname, self.pvnumber) elif pvtype == 5: scanpv = Lakeshore(self.pvname, self.pvnumber) else: scanpv = BasePv(self.pvname, self.pvnumber, self.rbv) self.scanpv = scanpv self.pvtype = pvtype self.pvtypePv = pvtypePv else: self.scanpv = ''
def __init__(self, expname=None, filepath=None, scanname=None): if not expname: expname = PV(pvPrefix + ':IOC.DESC').get() if ' ' in expname: expname = expname.replace(' ', '_') scanname = PV(pvPrefix + ':SCAN:NAME').get() if ' ' in scanname: scanname = scanname.replace(' ', '_') if scanname: scanname = '_' + scanname #targetname=PV(pvPrefix + ':SCAN:TARGETNAME').get() #if ' ' in targetname: targetname=targetname.replace(' ','_') filepathAutoset = PV(pvPrefix + ':DATA:FILEPATH:AUTOSET').get() if not filepath: if filepathAutoset: if os.environ['NFSHOME']: filepath = (os.environ['NFSHOME'] + '/pvScan/' + expname + '/' + now + scanname + '/') else: filepath = '~/pvScan/' + expname + '/' + now + scanname + '/' PV(pvPrefix + ':DATA:FILEPATH').put(filepath) # Write filepath to PV for display else: filepath = PV(pvPrefix + ':DATA:FILEPATH').get(as_string=True) if not filepath.endswith('/'): filepath = filepath + '/' if ' ' in filepath: filepath = filepath.replace(' ', '_') scanmodePv = PV(pvPrefix + ':SCAN:MODE') scanmode = scanmodePv.get() self.expname = expname self.scanname = scanname #self.targetname = targetname self.targetname = '' self.filepath = filepath self.filepathAutoset = filepathAutoset self.scanflag = PV(pvPrefix + ':SCAN:ENABLE').get() self.preScanflag = PV(pvPrefix + ':SCAN:PRESCAN').get() self.scanmodePv = scanmodePv self.scanmode = scanmode
def pulse(self): data = [] if not self.connected: print "Device not connected" return False pulse_period, pulse_width, p_enable1, p_enable2, p_enable3, p_enable4 = PV( 'pulse_period' ), PV('pulse_width'), PV('digital_out_pulse_enable_1'), PV( 'digital_out_pulse_enable_2'), PV( 'digital_out_pulse_enable_3'), PV('digital_out_pulse_enable_4') util.put_check(pulse_period, 10000) util.put_check(pulse_width, 100) util.put_check(p_enable1, 1) util.put_check(p_enable2, 1) util.put_check(p_enable3, 1) util.put_check(p_enable4, 1) period = pulse_period.get() width = pulse_width.get() p1 = p_enable1.get() p2 = p_enable2.get() p3 = p_enable3.get() p4 = p_enable4.get() # teardown util.put_check(pulse_period, 100) util.put_check(pulse_width, 1) util.put_check(p_enable1, 0) util.put_check(p_enable2, 0) util.put_check(p_enable3, 0) util.put_check(p_enable4, 0) return [period, width, p1, p2, p3, p4]
def testEnumPut(self): pv = PV(pvnames.enum_pv) self.assertIsNot(pv, None) pv.put('Stop') time.sleep(0.1) val = pv.get() self.assertEqual(val, 0)
def set_analog_outs(self): a1 = PV('analog_out_1') a2 = PV('analog_out_2') d = [] j = [] #print a1.get(), a2.get() a2.connect() #poll(evt=1.0, iot=0.01) a1.connect() poll(evt=1.0, iot=0.01) print a2.info for i in range(10): if i % 2 == 1: util.put_check(a2, 0.45) #util.put_check(a1, float(i)) else: util.put_check(a2, 0.5) #util.put_check(a1, float(i)) #j.append(a1.get()) d.append(a2.get()) print a1.status #util.put_check(a2, value2) print d print j return d
def connect_to_mca_pvs(med_name, nelem=4): mcas = ["%smca%i" % (med_name, i + 1) for i in range(nelem)] for key, suff in (('REAL_TIME', 'ERTM'), ('LIVE_TIME', 'ELTM'), ('CAL_OFFSET', 'CALO'), ('CAL_SLOPE', 'CALS'), ('CAL_QUAD', 'CALQ'), ('TWO_THETA', 'TTH')): for mca in mcas: x = PV("%s.%s" % (mca, suff)) i = 0 look_for_rois = True while look_for_rois: i = i + 1 look_for_rois = (i < 32) for mca in mcas: try: x = PV('%s.R%iNM' % (mca, i)) val = x.get() if val == '' or val is None: look_for_rois = False break except: look_for_rois = False break lo = PV('%s.R%iLO' % (mca, i)) hi = PV('%s.R%iHI' % (mca, i)) return i
def burst_size(self, value): print self.connected data = [] if not self.connected: print "Device not connected" return False acquisition_mode = PV('acquisition_mode') buffered_mode = PV('buffered_acquisition') burst_count = PV('burst_count') acquisition_mode.put(1) poll(evt=1.e-5, iot=0.01) buffered_mode.put(1) poll(evt=1.e-5, iot=0.01) t0 = time.time() burst_count.put(value) poll(evt=0.01, iot=0.01) connect = self.proc.expect( [pexpect.TIMEOUT, pexpect.EOF, 'Announce\(\) success'], timeout=1) output = burst_count.get() burst_count.put(0, wait=True) poll(evt=1.0, iot=1.01) return output
class EnumWrapper: def __init__(self, pvname, elog=None): self._elog = elog self._pv = PV(pvname) self.names = self._pv.enum_strs # print(self.names) # if self.names: self.setters = Positioner([(nam, lambda: self.set(nam)) for nam in self.names]) def set(self, target): if type(target) is str: assert target in self.names, ("set value need to be one of \n %s" % self.names) self._pv.put(self.names.index(target)) elif type(target) is int: assert target >= 0, "set integer needs to be positive" assert target < len(self.names) self._pv.put(target) def get(self): return self._pv.get() def get_name(self): return self.names[self.get()] def __repr__(self): return self.get_name()
def buffer_mode(self, value): data = [] if not self.connected: print "Device not connected" return False time.sleep(1) acquisition_mode = PV('acquisition_mode') buffered_mode = PV('buffered_acquisition') stopcount = PV('stop_count') current1 = PV('current_in_1') init = PV('initiate') acquisition_mode.put(1) poll(evt=1.0, iot=1.0) buffered_mode.put(1) poll(evt=1.0, iot=1.0) stopcount.put(value) poll(evt=1.0, iot=1.0) buff1 = buffered_mode.get() def getCount(pvname, value, **kw): data.append(value) current1.add_callback(getCount) init.put(1) poll(evt=1.e-5, iot=0.01) t0 = time.time() while time.time() - t0 < 4: poll(evt=1.e-5, iot=0.01) return len(data)
def connect_to_mca_pvs(med_name,nelem=4): mcas = ["%smca%i" % (med_name,i+1) for i in range(nelem)] for key,suff in (('REAL_TIME','ERTM'),('LIVE_TIME','ELTM'), ('CAL_OFFSET','CALO'),('CAL_SLOPE','CALS'), ('CAL_QUAD','CALQ'), ('TWO_THETA','TTH')): for mca in mcas: x = PV("%s.%s" % (mca,suff)) i = 0 look_for_rois = True while look_for_rois: i = i + 1 look_for_rois = (i < 32) for mca in mcas: try: x = PV('%s.R%iNM' % (mca,i)) val = x.get() if val == '' or val is None: look_for_rois = False break except: look_for_rois = False break lo = PV('%s.R%iLO' % (mca,i)) hi = PV('%s.R%iHI' % (mca,i)) return i
def io(self, value1, value2): check = util.expect(self.proc, ["C1"]) init = PV('initiate') low1, low2, low3, low4 = PV('low_limit_1'), PV('low_limit_2'), PV( 'low_limit_3'), PV('low_limit_4') poll(evt=1.e-5, iot=0.01) util.put_check(low1, 0.0) util.put_check(low2, 0.0) util.put_check(low3, 0.0) util.put_check(low4, 0.0) count1, count2, count3, count4 = PV('in_counts_1'), PV( 'in_counts_2'), PV('in_counts_3'), PV('in_counts_4') rate1, rate2, rate3, rate4 = PV('analog_in_rate_1'), PV( 'analog_in_rate_2'), PV('analog_in_rate_3'), PV('analog_in_rate_4') bias1_in, bias2_in, bias3_in, bias4_in = PV('analog_in_bias_1'), PV( 'analog_in_bias_2'), PV('analog_in_bias_3'), PV('analog_in_bias_4') bias1_out, bias2_out, bias3_out, bias4_out = PV( 'analog_out_bias_1'), PV('analog_out_bias_2'), PV( 'analog_out_bias_3'), PV('analog_out_bias_4') init.put(1) poll(evt=1.0, iot=0.01) util.put_check(bias1_out, value1) util.put_check(bias2_out, value2) counts = [count1.get(), count2.get(), count3.get(), count4.get()] rates = [rate1.get(), rate2.get(), rate3.get(), rate4.get()] bias_ins = [ bias1_in.get(), bias2_in.get(), bias3_in.get(), bias4_in.get() ] bias_outs = [ bias1_out.get(), bias2_out.get(), bias3_out.get(), bias4_out.get() ] return [counts, rates, bias_ins, bias_outs]
class DDGrabber(Experiment): """UED Direct Detector grabber.""" def __init__(self, cameraPvPrefix): Experiment.__init__(self) self.cameraPvPrefix = cameraPvPrefix self.grabFlag = PV(pvPrefix + ':GRABIMAGES:ENABLE').get() self.grabSeq2Flag = PV(pvPrefix + ':GRABIMAGES:SEQ2ENABLE').get() # Grab second image sequence after first self.grabSeq2Delay = PV(pvPrefix + ':GRABIMAGES:SEQ2DELAY').get() # Delay between 1st and 2nd sequence self.stepFlag = PV(pvPrefix + ':GRABIMAGES:STEPNUMBER').get() # Write step number into filename self.dataTime = PV(pvPrefix + ':GRABIMAGES:DATATIME').get() # Data capture time for DirectD self.dataStartStopPv = PV('UED:TST:FILEWRITER:CMD') # DataWriter start/stop PV self.dataStatusPv = PV('UED:TST:FILEWRITER:STATUS') # DataWriter status PV self.dataFilenamePv = PV('UED:TST:FILEWRITER:PATH') # DataWriter filename template PV self.nImages2 = None self.filenameExtras = '' self.timestampRBVPv = None self.captureRBVPv = None def dataWriterStatus(self): """Return status of dataWriter.""" status = self.dataStatusPv.get() if status: printMsg('DataWriter status is: ON') else: printMsg('DataWriter status is: OFF') return status def grabImages(self, nImages=0): """Set filepath PV, turn on/off dataWriter.""" #filenameTemplate='%s/%s%s_%s' %(timestamp('today'), self.expname, self.filenameExtras, timestamp(1)) if self.filenameExtras.startswith('_'): self.filenameExtras = self.filenameExtras.replace('_', '') filenameTemplate = ('%s/%s/%s_%s' %(timestamp('today'), self.expname, self.filenameExtras, timestamp(1))) self.dataFilenamePv.put(filenameTemplate + '\0') printMsg('Writing %s data for %d seconds...' % (self.cameraPvPrefix, self.dataTime)) print 'DirectD filepath: ', filenameTemplate #print self.dataStatusPv.get() #print caget('UED:TST:FILEWRITER:STATUS') self.dataStartStopPv.put(1) #caput('UED:TST:FILEWRITER:CMD',1) sleep(0.25) self.dataStartStopPv.put(1) #caput('UED:TST:FILEWRITER:CMD',1) sleep(0.25) self.dataWriterStatus() #print self.dataStatusPv.get() #print caget('UED:TST:FILEWRITER:STATUS') sleep(self.dataTime) self.dataStartStopPv.put(0) #caput('UED:TST:FILEWRITER:CMD',0) sleep(0.25) self.dataStartStopPv.put(0) #caput('UED:TST:FILEWRITER:CMD',0) sleep(0.25) self.dataWriterStatus() #print caget('UED:TST:FILEWRITER:STATUS') #print self.dataStatusPv.get() printMsg('Done Writing %s data.' % (self.cameraPvPrefix))
class ioc(): #_____________________________________________________________________________ def __init__(self, config): host = config["host"].strip() self.nam = config["ioc"].strip() pvnam = "iocmon:" + host + ":" + self.nam #print pvnam, self.description #color map self.col = {"ok": "00ff00", "alarm": "ff0000", "nocon": "ffffff"} self.pv_stat = PV(pvnam + ":status", connection_callback=self.on_stat_conn) self.status = self.pv_stat.get(as_string=True) self.severity = self.pv_stat.severity if self.status == None: self.status = " " self.severity = -1 self.description = " " print "Error: no connection to", pvnam + ":status" return self.pv_stat.add_callback(self.on_stat_update) self.description = caget(pvnam + ":description") #_____________________________________________________________________________ def make_html(self, tab_lines): #html content for the ioc bgcol = self.col["alarm"] if self.severity == 0: bgcol = self.col["ok"] if self.severity == -1: bgcol = self.col["nocon"] tab = '<td style="background-color: #' + bgcol + '">' + self.nam + '</td>' tab += '<td style="background-color: #' + bgcol + '">' + self.status + '</td>' tab += '<td>' + self.description + '</td>' tab_lines.append(tab) #_____________________________________________________________________________ def on_stat_update(self, char_value, severity, **kws): self.status = char_value self.severity = severity #print severity, char_value #_____________________________________________________________________________ def on_stat_conn(self, conn, **kws): if conn == True: return self.status = " " self.severity = -1
def init(self): if not self.connected: print "Device not conncted" return False init = PV('initiate') a_in_1 = PV('analogIn1') poll(evt=1.e-5, iot=0.01) before_init = a_in_1.get() init.put(1) poll(evt=1, iot=1) after_init = a_in_1.get() return before_init, after_init
def test_db(softioc, caclient): pv_in1 = PV("ET_dummyHost:LI1") pv_in2 = PV("ET_dummyHost:LI2") pv_calc = PV("ET_dummyHost:CALC") pv_in1.wait_for_connection(timeout=30) pv_in2.wait_for_connection(timeout=30) pv_calc.wait_for_connection(timeout=30) pv_in1.put(1, timeout=1) pv_in2.put(2, timeout=1) time.sleep(0.1) pv_calc.get() assert pv_calc.value == 3
class BeckhoffMotor(PV): """Beckhoff Motor class which inherits from pvScan Motor class.""" def __init__(self, pvname): if 'ESB' in pvname: rbv = pvname.split(':')[0] + ':CALC:' + ':'.join( pvname.split(':')[3:5]) + ':POS:MM' go = pvname.split(':')[0] + ':BO:' + ':'.join( pvname.split(':')[3:5]) + ':GO:POS' abort = pvname.split(':')[0] + ':BO:' + ':'.join( pvname.split(':')[3:5]) + ':STOP' pot_rbv = rbv_pv else: rbv = pvname.split(':')[0] + ':CALC:' + ':'.join( pvname.split(':')[2:3]) + ':POS:MM' go = pvname.split(':')[0] + ':BO:' + ':'.join( pvname.split(':')[2:3]) + ':GO:POS:ABS' abort = pvname.split(':')[0] + ':BO:' + ':'.join( pvname.split(':')[2:3]) + ':STOP' pot_rbv = rbv_pv PV.__init__(self, pvname) self.rbv = PV(rbv) self.go = PV(go) self.abort = PV(abort) self.pot_rbv = PV(pot_rbv) def pvWait(self, val, delta=0.005, timeout=180.0): """Wait until PV is near readback (or times out) to proceed.""" try: count = 0 pause = 0.2 while self.rbv.get() != val and count < timeout / pause: if math.fabs(self.rbv.get() - val) <= delta: break sleep(pause) count += 1 except TypeError: print "RBV is invalid for %s, pausing for %f seconds." % ( self.pvname, timeout) sleep(timeout) def move(self, val, wait=True, delta=0.005, timeout=360.0): """Put value and press Go button.""" PV.put(self, val) sleep(1) self.go.put(1) if wait: self.pvWait(val, delta, timeout)
def test_put_string_waveform_single_element(self): write('String Array: put single element\n') with no_simulator_updates(): pv = PV(pvnames.string_arr_pv) put_value = ['a'] pv.put(put_value, wait=True) get_value = pv.get(use_monitor=False) self.failUnless(put_value[0] == get_value)
def test_put_string_waveform_empty_list(self): write('String Array: put empty list\n') with no_simulator_updates(): pv = PV(pvnames.string_arr_pv) put_value = [] pv.put(put_value, wait=True) get_value = pv.get(use_monitor=False, as_numpy=False) self.failUnless('' == ''.join(get_value))
def test_put_string_waveform_zero_length_strings(self): write('String Array: put zero length strings\n') with no_simulator_updates(): pv = PV(pvnames.string_arr_pv) put_value = ['', '', ''] pv.put(put_value, wait=True) get_value = pv.get(use_monitor=False) numpy.testing.assert_array_equal(get_value, put_value)
def memory_test(self, value): util.expect(self.proc) # if not self.connected: # print "Device not connected" # return False #proc2 = pexpect.spawn(self.path) aout1 = PV('analogOut1') ain1 = PV('analogIn1') poll(evt=1.0, iot=1.01) #aout2 = PV('analogOut2') print ain1.get() # aout2.put(value) poll(evt=1.0, iot=1.01) # proc2.close(force=True) return value
def _set_params(self): """Set run params...""" functionName = '_set_params' pvdata = {} for name in self._pvnamelist: pv = PV(name) pvdata[pv.pvname] = pv.get(as_string=True) return pvdata
def test_remaining_time(self, reset_time): pv = PV('13SIM1:cam1:TimeRemaining_RBV') self.detector.doSetPreset(t=self.time_preset) start = time.time() self.detector.start() time.sleep(.1 * self.time_preset) elapsed = start - time.time() assert abs(pv.get() - (self.time_preset - elapsed)) < .1
def testA_CreatedWithConn(self): write('Simple Test: create pv with conn callback\n') pv = PV(pvnames.int_pv, connection_callback=onConnect) val = pv.get() global CONN_DAT conn = CONN_DAT.get(pvnames.int_pv, None) self.assertEqual(conn, True)
def turn_on(self): command = PV('c_p0_command') state = PV('r_p0_state') c_on_off = PV('c_p0_on_off') r_on_off = PV('r_p0_on_off') c_normal = PV('c_p0_normal') c_faulted = PV('c_p0_faulted') c_freq = PV('c_p0_freq') if state.get() != 0.0: util.put_check(c_on_off, 0) util.put_check(c_on_off, 1) util.put_check(c_normal, 1) util.put_check(c_faulted, 0) util.put_check(c_freq, 490) return state.get()
def test_put_string_waveform(self): write('String Array: put\n') with no_simulator_updates(): pv = PV(pvnames.string_arr_pv) put_value = ['a', 'b', 'c'] pv.put(put_value, wait=True) get_value = pv.get(use_monitor=False, as_numpy=False) numpy.testing.assert_array_equal(get_value, put_value)
def test_put_string_waveform(self): write('String Array: \n') with no_simulator_updates(): pv = PV(pvnames.string_arr_pv) put_value = ['a', 'b', 'c'] pv.put(put_value) get_value = pv.get(use_monitor=False, count=len(put_value)) numpy.testing.assert_array_equal(get_value, put_value)
def __init__(self, mnemonic, pv=None, responseTimeout=15, output="./out", numPoints=1044, mcas=False): """Constructor responseTimeout : how much time to wait qe65000 answer numPoints : how many points are collected each time """ super().__init__(mnemonic, numPoints, output, 'ocean') self.acquireChanged = Event() self.acquiring = False try: # determines the start of counting self.pvStart = PV(pv + ":Acquire") # determines mode of Acquisition (Single,Continous, Dark Spectrum) self.pvAcquireMode = PV(pv + ":AcquisitionMode") # use darkcorrection self.pvDarkCorrection = PV(pv + ":ElectricalDark") # spectrum self.pvSpectrum = PV(pv + ":Spectra") self.pvSpectrumCorrected = PV(pv + ":DarkCorrectedSpectra") # set Acquire Time self.pvAcquireTime = PV(pv + ":SetIntegration") # integration Time self.pvTime = PV(pv + ":IntegrationTime:Value") # control the end of acquire process self.pvAcquire = PV(pv + ":Acquiring") self.pvAcquire.add_callback(self.statusChange) # acquisition mode self.pvAcMode = PV(pv + ":AcquisitionMode") # set to single mode self.pvAcMode.put("Single") # axis Spectra pvAxis = PV(pv + ":SpectraAxis") self.axis = pvAxis.get(as_numpy=True)[:self.numPoints] # regions of interest self.ROIS = [] self.mcas = mcas self.responseTimeout = responseTimeout self.timer = Timer(self.responseTimeout) except TypeError: raise RuntimeError('PV not found') except ValueError: raise RuntimeError('Device is offline')
def data(pv=None, timevar=None, date1=None, date2=None, extra=None): session_init(session) admin = session['is_admin'] if date1 is not None and date1.endswith('.dat'): date1 = None if date2 is not None and date2.endswith('.dat'): date2 = None tmin, tmax, date1, date2, time_ago = parse_times(timevar, date1, date2) ts, dat = arch.get_data(pv, tmin=tmin, tmax=tmax, with_current=True) stmin = strftime("%Y-%m-%d %H:%M:%S", localtime(tmin)) stmax = strftime("%Y-%m-%d %H:%M:%S", localtime(tmax)) pvinfo = arch.get_pvinfo(pv) buff = ['# Data for %s [%s] ' % (pv, pvinfo['desc']), '# Time Range: %s , %s' % (stmin, stmax), '# Timestamps: [%.1f : %.1f]' % (tmin, tmax), '# Data Type: %s' % pvinfo['type']] fmt = '%13.7g' if pvinfo['type'] == 'enum': thispv = PV(pv) thispv.get() fmt = '%13i' buff.append('# Value Meanings:') for _i, _enum in enumerate(thispv.enum_strs): buff.append('# %i: %s' % (_i, _enum)) if dat.dtype.type == np.string_: dat = convert_string_data(dat) fmt = '%s' buff.append('#---------------------------------------------------') buff.append('# TimeStamp Value Date Time') for _t, _v in zip(ts, dat): try: val = fmt % _v except: val = repr(_v) ddate = strftime("%Y%m%d", localtime(_t)) dtime = strftime("%H%M%S", localtime(_t)) buff.append(' %.1f %s %s %s' % (_t, val, ddate, dtime)) return Response("\n".join(buff), mimetype='text/plain')
def test_put_string_waveform_single_element(self): write('String Array: put single element\n') with no_simulator_updates(): pv = PV(pvnames.string_arr_pv) put_value = ['a'] pv.put(put_value, wait=True) time.sleep(0.05) get_value = pv.get(use_monitor=False, as_numpy=False) self.failUnless(put_value[0] == get_value)
def get(d, pv_name, size, start, pid): pv = PV(pv_name) if pv.wait_for_connection(timeout=1.0): d[pv_name] = pv.get(use_monitor=False) else: d[pv_name] = 'not connected' if len(d) == size: print int(round((time.time() - start) * 1000)) os.kill(pid, signal.SIGTERM)
class RunEntry: def __init__(self): self.run = PV("GEN:MON:Runfilename") def GetStr(self,width): if self.run.connected: start = subprocess.check_output("ssh daq-master /netroots/common_root/opt/acqu/build-analysis/bin/AcquHead ~/acqu/scratch/"+self.run.get()+" | grep Time | awk '{print $5}' | sed 's/.\{3\}$//'", shell=True) return "Run: "+self.run.get()+" - Start: "+start.strip()+" - End: XX:XX" return "Run: XXX - Start: XX:XX End: XX:XX"
def test_put_string_waveform_mixed_types(self): write('String Array: put mixed types\n') with no_simulator_updates(): pv = PV(pvnames.string_arr_pv) put_value = ['a', 2, 'b'] pv.put(put_value, wait=True) time.sleep(0.05) get_value = pv.get(use_monitor=False, as_numpy=False) numpy.testing.assert_array_equal(get_value, ['a', '2', 'b'])
def test_put_string_waveform_empty_list(self): write('String Array: put empty list\n') with no_simulator_updates(): pv = PV(pvnames.string_arr_pv) put_value = [] pv.put(put_value, wait=True) time.sleep(0.05) get_value = pv.get(use_monitor=False, as_numpy=False) self.failUnless('' == ''.join(get_value))
def test_put_string_waveform_zero_length_strings(self): write('String Array: put zero length strings\n') with no_simulator_updates(): pv = PV(pvnames.string_arr_pv) put_value = ['', '', ''] pv.put(put_value, wait=True) time.sleep(0.05) get_value = pv.get(use_monitor=False, as_numpy=False) numpy.testing.assert_array_equal(get_value, put_value)
def test_get_string_waveform(self): write('String Array: \n') with no_simulator_updates(): pv = PV(pvnames.string_arr_pv) val = pv.get() self.failUnless(len(val) > 10) self.assertIsInstance(val[0], str) self.failUnless(len(val[0]) > 1) self.assertIsInstance(val[1], str) self.failUnless(len(val[1]) > 1)