def start(self, wait=False): """start collection, with slightly different behavior for SCALER and NDARRAY mode. Arguments: wait (bool): whether to wait for counting to complete [False] Notes: In SCALER mode, for simple counting: this simply collects one set of Current readings, by setting Acquire to 1 and optionally waiting for it to complete. In NDARRAY mode: this will first start the Time Series, then set Acquire to 1. If an SIS is used, this will then set the SIS EraseStart to 1 and optionally waiting for it to complete. """ if self._mode in (NDARRAY_MODE, ROI_MODE): for i in self._chans: self.put('Current%i:TSControl' % i, 0) # 'Erase/Start' if self._sis is not None: self.put('Acquire', 1, wait=False) poll(0.025, 1.0) out = self._sis.Start(wait=wait) else: out = self.put('Acquire', 1, wait=wait) else: out = self.put('Acquire', 1, wait=wait) poll() return out
def SetPV(self, pv=None): "set pv, either an epics.PV object or a pvname" if pv is None: return if isinstance(pv, epics.PV): self.pv = pv elif isinstance(pv, (str, unicode)): self.pv = epics.PV(pv) self.pv.connect() epics.poll() self.pv.connection_callbacks.append(self.OnEpicsConnect) self.pv.get_ctrlvars() self.OnPVChange(self.pv.get(as_string=True)) self.pv.add_callback(self._pvEvent, wid=self.GetId() ) pv_value = pv.get(as_string=True) enum_strings = pv.enum_strs sizer = wx.BoxSizer(self.orientation) self.buttons = [] if enum_strings is not None: for i, label in enumerate(enum_strings): b = buttons.GenToggleButton(self, -1, label) self.buttons.append(b) b.Bind(wx.EVT_BUTTON, Closure(self._onButton, index=i) ) sizer.Add(b, flag = wx.ALL) b.SetToggle(label==pv_value) self.SetAutoLayout(True) self.SetSizer(sizer) sizer.Fit(self)
def RunTest(pvlist, use_preempt=True, maxlen=16384, use_numpy=True, use_time=False, use_ctrl=False): msg= ">>>Run Test: %i pvs, numpy=%s, time=%s, ctrl=%s, preempt=%s" print( msg % (len(pvlist), use_numpy, use_time, use_ctrl, use_preempt)) epics.ca.HAS_NUMPY = use_numpy and HAS_NUMPY epics.ca.PREEMPTIVE_CALLBACK = use_preempt epics.ca.AUTOMONITOR_MAXLENGTH = maxlen mypvs= [] for pvname in pvlist: pv = epics.PV(pvname, connection_callback=onConnect, callback=onChanges) mypvs.append(pv) epics.poll(evt=0.10, iot=10.0) for pv in mypvs: print('== ', pv.pvname, pv) # time.sleep(0.1) # epics.poll(evt=0.01, iot=1.0) val = pv.get() cval = pv.get(as_string=True) if pv.count > 1: val = val[:12] print(pv.type, val, cval) for pv in mypvs: pv.disconnect() time.sleep(0.01)
def probe(self, handle, ports): self.logger.debug('probe ports: %r', ports) self.set_probe_requests(ports) poll(DELAY_TO_PROCESS) message = self.robot.run_task('ProbeCassettes') self.logger.info('probe message: %r', message) return message
def getCount(pvname, value, **kw): if len(data) >= stop - 1: init.put(0) poll(evt=0.1, iot=0.1) #poll(evt=0.001, iot=0.001) data.append(value)
def SetPV(self, pv=None): "set pv, either an epics.PV object or a pvname" if pv is None: return if isinstance(pv, epics.PV): self.pv = pv elif isinstance(pv, (str, unicode)): self.pv = epics.get_pv(pv) self.pv.connect() epics.poll() self.pv.connection_callbacks.append(self.OnEpicsConnect) self.pv.get_ctrlvars() self.OnPVChange(self.pv.get(as_string=True)) ncback = len(self.pv.callbacks) + 1 self.pv.add_callback(self._pvEvent, wid=self.GetId(), cb_info=ncback) self.Bind(wx.EVT_CHOICE, self._onChoice) pv_value = pv.get(as_string=True) enum_strings = pv.enum_strs self.Clear() self.AppendItems(enum_strings) self.SetStringSelection(pv_value)
def connect_pvs(self, verbose=True): # print "Connect PVS" if self.prefix is None or len(self.prefix) < 2: return time.sleep(0.010) if not self.ad_img.PV('UniqueId_RBV').connected: poll() if not self.ad_img.PV('UniqueId_RBV').connected: self.messag('Warning: Camera seems to not be connected!') return self.wids['color'].SetPV(self.ad_cam.PV('ColorMode')) self.wids['exptime'].SetPV(self.ad_cam.PV('AcquireTime')) self.wids['gain'].SetPV(self.ad_cam.PV('Gain')) self.wids['imagemode'].SetPV(self.ad_cam.PV('ImageMode')) # self.wids['period'].SetPV(self.ad_cam.PV('AcquirePeriod')) # self.wids['numimages'].SetPV(self.ad_cam.PV('NumImages')) self.wids['triggermode'].SetPV(self.ad_cam.PV('TriggerMode')) sizex = self.ad_cam.MaxSizeX_RBV sizey = self.ad_cam.MaxSizeY_RBV sizelabel = 'Image Size: %i x %i pixels' try: sizelabel = sizelabel % (sizex, sizey) except: sizelabel = sizelabel % (0, 0) self.wids['fullsize'].SetLabel(sizelabel) poll()
def get_current_readback(self): connect = self.proc.expect( [pexpect.TIMEOUT, pexpect.EOF, 'success'], timeout=5) if connect == 2: #enable = PV('c_psu_enable') resistance = PV('c_psu_resistance') readback_current = PV('r_psu_current') readback_voltage = PV('r_psu_voltage') # setpoint_current = PV('analog_in_current_setpoint') # setpoint_voltage = PV('analog_in_voltage_setpoint') command_v = PV('c_psu_control_voltage') poll(evt=1.0, iot=1.0) command_v.put(400) poll(evt=1.0, iot=1.0) change = self.proc.expect([pexpect.TIMEOUT, pexpect.EOF, 'success'], timeout=5) r_curr = readback_current.get() r_volt = readback_voltage.get() target = 400/resistance.get() # set_curr = setpoint_current.get() # set_volt = setpoint_voltage.get() return r_curr, target else: return -1
def set_command_voltage(self): connect = self.proc.expect( [pexpect.TIMEOUT, pexpect.EOF, 'success'], timeout=5) print self.proc.after print self.proc.before if connect == 2: command_v = PV('c_psu_control_voltage') value = random.random()*1000 command_v.put(value) poll(evt=1.0, iot=1.0) command = command_v.get() print command_v.info print command print command_v.get() #teardown #command_v.disconnect() #util.blowout_pvs() # epics.ca.clear_channel(command_v.chid) # ctx = epics.ca.current_context() # pvs = [] # for x in epics.ca._cache[ctx]: # pvs.append(x) # for pv in pvs: # import itertools # for element in itertools.product(*somelists): # print(element) epics.ca._cache[ctx].pop(pv) #print epics.ca._cache[ctx] #epics.ca._cache[ctx].pop('c_psu_control_voltage') return command, value else: return -1
def restore_rois(self, roifile): """restore ROI setting from ROI.dat file""" cp = ConfigParser() cp.read(roifile) rois = [] self.mcas[0].clear_rois() prefix = self.mcas[0]._prefix if prefix.endswith('.'): prefix = prefix[:-1] iroi = 0 for a in cp.options('rois'): if a.lower().startswith('roi'): name, dat = cp.get('rois', a).split('|') lims = [int(i) for i in dat.split()] lo, hi = lims[0], lims[1] # print('ROI ', name, lo, hi) roi = ROI(prefix=prefix, roi=iroi) roi.LO = lo roi.HI = hi roi.NM = name.strip() rois.append(roi) iroi += 1 poll(0.050, 1.0) self.mcas[0].set_rois(rois) cal0 = self.mcas[0].get_calib() for mca in self.mcas[1:]: mca.set_rois(rois, calib=cal0)
def channel_limits(self, value): self.proc.expect([pexpect.TIMEOUT, pexpect.EOF], timeout=3) test = [PV('test1'), PV('test2'), PV('test3')] rules = {test[0]: (1, 300), test[1]: (-300, -1), test[2]: (None, None)} poll(evt=1.e-5, iot=0.01) time.sleep(0.1) test[0].put(value) #c1 = self.proc.expect(['Limit violation', pexpect.TIMEOUT, pexpect.EOF], timeout=1) test[1].put(value) #c2 = self.proc.expect(['Limit violation', pexpect.TIMEOUT, pexpect.EOF], timeout=1) test[2].put(value) #c3 = self.proc.expect(['Limit violation', pexpect.TIMEOUT, pexpect.EOF], timeout=1) poll(evt=1.0, iot=0.01) results = [] for i in test: if rules[i] == (None, None): results.append(util.isclose(i.get(), value)) elif value >= rules[i][0] and value <= rules[i][1]: results.append(util.isclose(i.get(), value)) else: results.append( util.isclose(i.get(), rules[i][0]) or util.isclose(i.get(), rules[i][1])) return results
def restore_rois(self, roifile): """restore ROI setting from ROI.dat file""" cp = ConfigParser() cp.read(roifile) rois = [] self.mcas[0].clear_rois() prefix = self.mcas[0]._prefix if prefix.endswith("."): prefix = prefix[:-1] iroi = 0 for a in cp.options("rois"): if a.lower().startswith("roi"): name, dat = cp.get("rois", a).split("|") lims = [int(i) for i in dat.split()] lo, hi = lims[0], lims[1] # print('ROI ', name, lo, hi) roi = ROI(prefix=prefix, roi=iroi) roi.LO = lo roi.HI = hi roi.NM = name.strip() rois.append(roi) iroi += 1 poll(0.050, 1.0) self.mcas[0].set_rois(rois) cal0 = self.mcas[0].get_calib() for mca in self.mcas[1:]: mca.set_rois(rois, calib=cal0)
def burst_size(self): if not self.connected: print "Device not connected" return False data = [] count = PV('in_counts_3') trig_mode = PV('trig_mode') low3 = PV('low_limit_3') int_time = PV('analog_out_period') trig_burst = PV('trig_burst') trig_buffer = PV('trig_buffer') init = PV('initiate') poll(evt=1.e-5, iot=0.01) util.put_check(trig_mode, 0) low3.put(0.0) int_time.put(10e-4) util.put_check(trig_buffer, 0) util.put_check(trig_burst, 1000) poll(evt=1.e-5, iot=0.01) def getCount(pvname, value, **kw): data.append(value) count.add_callback(getCount) t0 = time.time() init.put(1) t1 = time.time() # while caget('paused_state') != 1: # if time.time() - t1 > 30: # return "pause state never reached" # else: # pass pass1 = len(data) util.put_check(trig_burst, 10000) time.sleep(0.1) t2 = time.time() init.put(1) t3 = time.time() # while caget('paused_state') != 1: # if time.time() - t3 > 30: # return "pause state never reached 2nd time" # else: # pass pass2 = len(data) - pass1 # teardown util.put_check(trig_burst, 0) return pass1, pass2
def get_rois(self, nrois=None): "get all rois" self.rois = [] data_pv = self._pvs['VAL'] poll() data_pv.connect() prefix = self._roi_prefix if prefix is None: return self.rois if nrois is None: nrois = self._nrois for i in range(nrois): roi = ADMCAROI(prefix=self._roi_prefix, roi=i + 1, data_pv=data_pv) if roi.Name is None: roi = ADMCAROI(prefix=self._roi_prefix, roi=i + 1, data_pv=data_pv, with_poll=True) if roi.Name is None: continue if len(roi.Name.strip()) > 0 and roi.MinX > 0 and roi.SizeX > 0: self.rois.append(roi) else: break poll(0.001, 1.0) return self.rois
def sort_rois(self): """ make sure rois are sorted, and Epics PVs are cleared """ if self.rois is None: self.get_rois() poll(0.05, 1.0) unsorted = [] empties = 0 for roi in self.rois: if len(roi.Name) > 0 and roi.right > 0: unsorted.append(roi) else: empties = +1 if empties > 3: break self.rois = sorted(unsorted) rpref = self._roi_prefix roidat = [(r.Name, r.MinX, r.SizeX) for r in self.rois] for iroi, roi in enumerate(roidat): caput("%s:%i:Name" % (rpref, iroi + 1), roi[0]) caput("%s:%i:MinX" % (rpref, iroi + 1), roi[1]) caput("%s:%i:SizeX" % (rpref, iroi + 1), roi[2]) iroi = len(roidat) caput("%s:%i:Name" % (rpref, iroi + 1), '') caput("%s:%i:MinX" % (rpref, iroi + 1), 0) caput("%s:%i:SizeX" % (rpref, iroi + 1), 0) self.get_rois()
def onClose(self, event): self.db.set_hostpid(clear=True) self.db.commit() self.config.write() epics.poll() time.sleep(0.1) self.Destroy()
def __init__(self, prefix=None, nmca=4, version=2, **kws): self.nmca = nmca self.prefix = prefix self.version = version self.mca_array_name = 'MCASUM%i:ArrayData' if version < 2: self.mca_array_name = 'ARRSUM%i:ArrayData' self.environ = [] self.mcas = [] self.npts = 4096 self.energies = [] self.connected = False self.elapsed_real = None self.elapsed_textwidget = None self.needs_refresh = False self._xsp3 = None if self.prefix is not None: self.connect() self.nframes = 1 self.frametime = 1.0 # determine max frames self.frametime = self.MIN_FRAMETIME self._xsp3.NumImages = self.MAX_FRAMES epics.poll(0.010, 1.0) rbv = self._xsp3.NumImages_RBV while rbv != self.MAX_FRAMES: self.MAX_FRAMES = int(0.96*self.MAX_FRAMES) self._xsp3.NumImages = self.MAX_FRAMES rbv = self._xsp3.NumImages_RBV if self.MAX_FRAMES < 100: break
def caget(pvname, connection_timeout=5.0, verbose=True, **kwargs): # For future pyepics reference: # * The reason behind wrapping epics.caget is that there's no nice way to # differentiate between connection_timeout and caget timeout with epics.caget. # * The default of 5 seconds in epics.__create_pv can be excruciatingly slow. # * A verbosity setting if pvname not in _pv_cache: _pv_cache[pvname] = epics.PV(pvname, connection_timeout=connection_timeout) pv = _pv_cache[pvname] if pv.wait_for_connection(timeout=connection_timeout): if kwargs.get('as_string', False): pv.get_ctrlvars() epics.poll() try: value = pv.get(**kwargs) return value except Exception as ex: if verbose: print('caget.get failed for %s: (%s) %s' % (pvname, ex.__class__.__name__, ex)) return None else: if verbose: print('%s: failed to connect to PV' % pvname) return None
def SelectMotor(self, motor): " set motor to a named motor PV" if motor is None: return dt = debugtime() epics.poll() try: if self.motor is not None: for i in self.__motor_fields: self.motor.clear_callback(attr=i) except PyDeadObjectError: return dt.add('clear callbacks') if isinstance(motor, six.string_types): self.motor = epics.Motor(motor) dt.add('create motor (name)') elif isinstance(motor, epics.Motor): self.motor = motor dt.add('create motor (motor)') self.motor.get_info() dt.add('get motor info') if self.format is None: self.format = "%%.%if" % self.motor.PREC self.FillPanel() dt.add('fill panel') for attr in self.__motor_fields: self.motor.get_pv(attr).add_callback(self.OnMotorEvent, wid=self.GetId(), field=attr) dt.add('add callbacks %i attrs ' % (len(self.__motor_fields))) if self._size == 'full': self.SetTweak(self.format % self.motor.TWV)
def channel_scaling(self): status = PV('status') if not util.check_device('A1', self.proc) and status.get() in range(0,3): print "device not connected" print status.get() print util.check_device('A1', self.proc) return False normal = PV('cleanIn1') linear = PV('linearIn1') log = PV('logIn1') both_scaled = PV('bothScaled') init = PV('initiate') poll(evt=1.e-5, iot=0.01) init.put(1) poll(evt=1.e-5, iot=0.01) time.sleep(2) base = normal.get() lin = linear.get() logged = log.get() both = both_scaled.get() print base, lin, logged, both return (self.check( lin, base*2 + 10, 0.01) and self.check( logged, 10**base, 0.01) and self.check(both, 10 ** (base*2 +10), 0.01))
def RunTest(pvlist, use_preempt=True, maxlen=16384, use_numpy=True, form='native'): msg = ">>>Run Test: %i pvs, numpy=%s, form=%s, preempt=%s" print(msg % (len(pvlist), use_numpy, form, use_preempt)) epics.ca.HAS_NUMPY = use_numpy and HAS_NUMPY epics.ca.PREEMPTIVE_CALLBACK = use_preempt epics.ca.AUTOMONITOR_MAXLENGTH = maxlen mypvs = [] for pvname in pvlist: pv = epics.PV( pvname, form=form, # connection_callback=onConnect, # callback=onChanges ) mypvs.append(pv) epics.poll(evt=0.10, iot=10.0) for pv in mypvs: # time.sleep(0.1) # epics.poll(evt=0.01, iot=1.0) val = pv.get() cval = pv.get(as_string=True) if pv.count > 1: val = val[:12] print('-> ', pv, cval) print(' ', type(val), val) for pv in mypvs: pv.disconnect() time.sleep(0.01)
def run_task(self, name, args='', timeout=.5): """Execute a foreground task on the robot. Checks to see that the robot controller foreground thread is free and then executes a task. Blocks until the task is complete. Args: name (str): Robot controller task to run args (str): Argument string to supply to the controller timeout (float): Seconds to wait for the task to being """ if not self.foreground_done.get(): raise RobotError('busy') self.task_args.put(args or '\0') poll(DELAY_TO_PROCESS) self.generic_command.put(name) self._wait_for_foreground_busy(timeout) self._wait_for_foreground_free() poll(DELAY_TO_PROCESS) if self.foreground_error.get() != 0: message = self.foreground_error_message.get(as_string=True) raise RobotError(message) result = self.task_result.get(as_string=True) status, _, message = result.partition(' ') if status.lower() not in {'ok', 'normal'}: raise RobotError(message) return message
def FillPanelComponents(self): epics.poll() try: if self.motor is None: return except PyDeadObjectError: return self.drive.SetPV(self.motor.PV('VAL')) self.rbv.SetPV(self.motor.PV('RBV')) self.desc.SetPV(self.motor.PV('DESC')) descpv = self.motor.PV('DESC').get() self.desc.Wrap(45) if self._size == 'full': self.twf.SetPV(self.motor.PV('TWF')) self.twr.SetPV(self.motor.PV('TWR')) elif len(descpv) > 20: font = self.desc.GetFont() font.PointSize -= 1 self.desc.SetFont(font) self.info.SetLabel('') for f in ('SET', 'LVIO', 'SPMG', 'LLS', 'HLS', 'disabled'): uname = self.motor.PV(f).pvname wx.CallAfter(self.OnMotorEvent, pvname=uname, field=f)
def run_task(self, name, args=''): """Execute a foreground task on the robot. Checks to see that the robot controller foreground thread is free and then executes a task. Blocks until the task is complete. Args: name (str): Robot controller task to run args (str): Argument string to supply to the controller timeout (float): Seconds to wait for the task to being """ if not self.foreground_done.get(): raise RobotError('busy') self.task_args.put(args or '\0') poll(self.DELAY_TO_PROCESS) self.generic_command.put(name) self._wait_for_foreground_busy(self.TASK_TIMEOUT) self._wait_for_foreground_free() poll(self.DELAY_TO_PROCESS) if self.foreground_error.get() != 0: message = self.foreground_error_message.get(as_string=True) raise RobotError(message) result = self.task_result.get(as_string=True) status, _, message = result.partition(' ') if status.lower() not in {'ok', 'normal'}: raise RobotError(message) return message
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 mainloop(self): if self.larch is None: raise ValueError("Scan server not connected!") self.set_status('idle') msgtime = time.time() self.set_scan_message('Server Ready') is_paused = False while True: epics.poll(0.001, 1.0) self.look_for_interrupts() if self.epicsdb.Shutdown == 1 or self.req_shutdown: break if time.time() > msgtime + 1: msgtime = time.time() self.scandb.set_info('heartbeat', time.ctime()) self.epicsdb.setTime() if self.req_pause: continue reqs = self.scandb.get_commands(status='requested', reverse=False) if self.epicsdb.Abort == 1 or self.req_abort: if len(reqs) > 0: req = reqs[0] self.scandb.set_command_status(req.id, 'aborted') abort_slewscan() time.sleep(1.0) self.epicsdb.Abort = 0 self.clear_interrupts() time.sleep(1.0) elif len(reqs) > 0: self.do_command(reqs[0]) # mainloop end self.finish() return None
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 SelectMotor(self, motor): " set motor to a named motor PV" if motor is None: return epics.poll() try: if self.motor is not None: for i in self.__motor_fields: self.motor.clear_callback(attr=i) except PyDeadObjectError: return if isinstance(motor, (str, unicode)): self.motor = epics.Motor(motor) elif isinstance(motor, epics.Motor): self.motor = motor self.motor.get_info() if self.format is None: self.format = "%%.%if" % self.motor.PREC self.FillPanel() for attr in self.__motor_fields: self.motor.get_pv(attr).add_callback(self.OnMotorEvent, wid=self.GetId(), field=attr) if self._size == 'full': self.SetTweak(self.format % self.motor.TWV)
def __init__(self, prefix, nmcas=4, filesaver='HDF1:', fileroot='/home/xspress3'): dt = debugtime() self.nmcas = nmcas attrs = [] attrs.extend(['%s%s' % (filesaver, p) for p in self.pathattrs]) self.filesaver = filesaver self.fileroot = fileroot self._prefix = prefix self.mcas = [] for i in range(nmcas): imca = i + 1 dprefix = "%sdet1:" % prefix rprefix = "%sMCA%iROI" % (prefix, imca) data_pv = "%sMCA%i:ArrayData" % (prefix, imca) mca = ADMCA(dprefix, data_pv=data_pv, roi_prefix=rprefix) self.mcas.append(mca) attrs.append("MCA%iROI:TSControl" % (imca)) attrs.append("MCA%iROI:TSNumPoints" % (imca)) attrs.append("C%iSCA:TSControl" % (imca)) attrs.append("C%iSCA:TSNumPoints" % (imca)) Device.__init__(self, prefix, attrs=attrs, delim='') for attr in self.det_attrs: self.add_pv("%sdet1:%s" % (prefix, attr), attr) for i in range(nmcas): imca = i + 1 for j in range(8): isca = j + 1 attr = "C%iSCA%i" % (imca, isca) self.add_pv("%s%s:Value_RBV" % (prefix, attr), attr) poll(0.003, 0.25)
def SetPV(self, pv=None): "set pv, either an epics.PV object or a pvname" if pv is None: return if isinstance(pv, epics.PV): self.pv = pv elif isinstance(pv, (str, unicode)): self.pv = epics.PV(pv) self.pv.connect() epics.poll() self.pv.connection_callbacks.append(self.OnEpicsConnect) self.pv.get_ctrlvars() self.OnPVChange(self.pv.get(as_string=True)) self.pv.add_callback(self._pvEvent, wid=self.GetId()) self.Bind(wx.EVT_CHOICE, self._onChoice) pv_value = pv.get(as_string=True) enum_strings = pv.enum_strs self.Clear() self.AppendItems(enum_strings) self.SetStringSelection(pv_value)
def datalog(npts,interval): "Logs PV data to a file; PVs must be in pvlist" #print 'Logging PV data to', filepath, 'as a detached process...PID is', os.getpid() msg1=('Dumping data to', filepath, '...PID is', str(os.getpid())) s=' ' print s.join(msg1) #msgPV.put('Dumping data.........') msgPV.put(s.join(msg1)) #os.system("echo '' | mailx -s 'Starting pvLog' -r nlctaAutobot [email protected]") filename=filepath + 'pvlog-' + str(timestamp()) + '.dat' with open(filename, 'w') as datafile: datafile.write('Timestamp ') for pv in pvlist: datafile.write(pv.pvname) datafile.write(' ') datafile.write('\n') for i in range(npts): datafile.write(str(timestamp(1))) datafile.write(' ') for pv in pvlist: datafile.write(str(pv.value)) datafile.write(' ') datafile.write('\n') #sleep(interval) poll(evt=7.e-3, iot=0.1) msgPV.put('Data dumped') filenamePV.put(filename)
def __init__(self, cntName='HFXAFS:scaler1_', i0=QLCDNumber, it=QLCDNumber, iF=QLCDNumber, ir=QLCDNumber): QObject.__init__(self) threading.Thread.__init__(self) self.cntName =cntName self.i0 = i0 self.it = it self.iF = iF self.ir = ir self.countPV = epics.PV(self.cntName+'_calc2') scalerAttrs = ('calc1','calc2','calc3','calc4','calc5','calc6','calc7','calc8') self.scalerDev = epics.Device(prefix=self.cntName+'_', delim='', attrs=scalerAttrs, mutable=False) epics.poll() try: epics.poll(0.001, 1.0) val = self.scalerDev.get_all() self.i0.display(val['calc2']) self.it.display(val['calc3']) self.iF.display(val['calc4']) self.ir.display(val['calc5']) except: pass self.countPV.add_callback(self.countersCallbackFunc,run_now=True)
def get_rois(self, nrois=None): "get all rois" self.rois = [] data_pv = self._pvs['VAL'] poll() data_pv.connect() prefix = self._roi_prefix if prefix is None: return self.rois if nrois is None: nrois = self._nrois for i in range(nrois): roi = ADMCAROI(prefix=self._roi_prefix, roi=i+1, data_pv=data_pv) if roi.Name is None: roi = ADMCAROI(prefix=self._roi_prefix, roi=i+1, data_pv=data_pv, with_poll=True) if roi.Name is None: continue if len(roi.Name.strip()) > 0 and roi.MinX > 0 and roi.SizeX > 0: self.rois.append(roi) else: break poll(0.001, 1.0) return self.rois
def sort_rois(self): """ make sure rois are sorted, and Epics PVs are cleared """ if self.rois is None: self.get_rois() poll(0.05, 1.0) unsorted = [] empties = 0 for roi in self.rois: if len(roi.Name) > 0 and roi.right > 0: unsorted.append(roi) else: empties =+ 1 if empties > 3: break self.rois = sorted(unsorted) rpref = self._roi_prefix roidat = [(r.Name, r.MinX, r.SizeX) for r in self.rois] for iroi, roi in enumerate(roidat): caput("%s:%i:Name" % (rpref, iroi+1), roi[0]) caput("%s:%i:MinX" % (rpref, iroi+1), roi[1]) caput("%s:%i:SizeX" % (rpref, iroi+1), roi[2]) iroi = len(roidat) caput("%s:%i:Name" % (rpref, iroi+1), '') caput("%s:%i:MinX" % (rpref, iroi+1), 0) caput("%s:%i:SizeX" % (rpref, iroi+1), 0) self.get_rois()
def start(self, value=1): """Start Xspress3""" self.done = False runtime = -1 self._t0 = time.time() self._start.put(value, callback=self.__onComplete) poll(0.01, 0.5)
def FillPanelComponents(self): epics.poll() try: if self.motor is None: return except PyDeadObjectError: return self.drive.SetPV(self.motor.PV("VAL")) self.rbv.SetPV(self.motor.PV("RBV")) self.desc.SetPV(self.motor.PV("DESC")) descpv = self.motor.PV("DESC").get() self.desc.Wrap(45) if self._size == "full": self.twf.SetPV(self.motor.PV("TWF")) self.twr.SetPV(self.motor.PV("TWR")) elif len(descpv) > 20: font = self.desc.GetFont() font.PointSize -= 1 self.desc.SetFont(font) self.info.SetLabel("") for f in ("SET", "LVIO", "SPMG", "LLS", "HLS", "disabled"): uname = self.motor.PV(f).pvname wx.CallAfter(self.OnMotorEvent, pvname=uname, field=f)
def __init__(self, prefix=None, nmca=4, version=2, **kws): self.nmca = nmca self.prefix = prefix self.version = version self.mca_array_name = 'MCASUM%i:ArrayData' if version < 2: self.mca_array_name = 'ARRSUM%i:ArrayData' self.environ = [] self.mcas = [] self.npts = 4096 self.energies = [] self.connected = False self.elapsed_real = None self.elapsed_textwidget = None self.needs_refresh = False self._xsp3 = None if self.prefix is not None: self.connect() self.nframes = 1 self.frametime = 1.0 # determine max frames self.frametime = self.MIN_FRAMETIME self._xsp3.NumImages = self.MAX_FRAMES epics.poll(0.010, 1.0) rbv = self._xsp3.NumImages_RBV while rbv != self.MAX_FRAMES: self.MAX_FRAMES = int(0.96 * self.MAX_FRAMES) self._xsp3.NumImages = self.MAX_FRAMES rbv = self._xsp3.NumImages_RBV if self.MAX_FRAMES < 100: break
def __init__(self, prefix, nmcas=4, filesaver='HDF1:', fileroot='/T/xas_user'): dt = debugtime() if not prefix.endswith(':'): prefix = "%s:" % prefix self.nmcas = nmcas attrs = [] attrs.extend(['%s%s' % (filesaver, p) for p in self.pathattrs]) self.filesaver = filesaver self.fileroot = fileroot self._prefix = prefix self.mcas = [] for i in range(nmcas): imca = i+1 dprefix = "%sdet1:" % prefix rprefix = "%sMCA%iROI" % (prefix, imca) data_pv = "%sMCA%i:ArrayData" % (prefix, imca) mca = ADMCA(dprefix, data_pv=data_pv, roi_prefix=rprefix) self.mcas.append(mca) attrs.append("%s:MCA%iROI:TSControl" % (prefix, imca)) attrs.append("%s:MCA%iROI:TSNumPoints" % (prefix, imca)) attrs.append("%s:C%iSCA:TSControl" % (prefix, imca)) attrs.append("%s:C%iSCA:TSNumPoints" % (prefix, imca)) Device.__init__(self, prefix, attrs=attrs, delim='') for attr in self.det_attrs: self.add_pv("%sdet1:%s" % (prefix, attr), attr) for i in range(nmcas): imca = i+1 for j in range(8): isca = j+1 attr = "C%iSCA%i"% (imca, isca) self.add_pv("%s%s:Value_RBV" % (prefix, attr), attr) poll(0.003, 0.25)
def restore_rois(self, roifile): """restore ROI setting from ROI.dat file""" cp = ConfigParser() cp.read(roifile) rois = [] self.mcas[0].clear_rois() prefix = self.mcas[0]._prefix if prefix.endswith('.'): prefix = prefix[:-1] iroi = 0 for a in cp.options('rois'): if a.lower().startswith('roi'): name, dat = cp.get('rois', a).split('|') lims = [int(i) for i in dat.split()] lo, hi = lims[0], lims[1] roi = ROI(prefix=prefix, roi=iroi) roi.left = lo roi.right = hi roi.name = name.strip() rois.append(roi) iroi += 1 epics.poll(0.050, 1.0) self.mcas[0].set_rois(rois) cal0 = self.mcas[0].get_calib() for mca in self.mcas[1:]: mca.set_rois(rois, calib=cal0)
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 RunTest(pvlist, use_preempt=True, maxlen=16384, use_numpy=True, form='native'): msg= ">>>Run Test: %i pvs, numpy=%s, form=%s, preempt=%s" print( msg % (len(pvlist), use_numpy, form, use_preempt)) epics.ca.HAS_NUMPY = use_numpy and HAS_NUMPY epics.ca.PREEMPTIVE_CALLBACK = use_preempt epics.ca.AUTOMONITOR_MAXLENGTH = maxlen mypvs= [] for pvname in pvlist: pv = epics.PV(pvname, form=form, # connection_callback=onConnect, # callback=onChanges ) mypvs.append(pv) epics.poll(evt=0.10, iot=10.0) for pv in mypvs: # time.sleep(0.1) # epics.poll(evt=0.01, iot=1.0) val = pv.get() cval = pv.get(as_string=True) if pv.count > 1: val = val[:12] print( '-> ', pv, cval) print( ' ', type(val), val) for pv in mypvs: pv.disconnect() time.sleep(0.01)
def del_roi(self, roiname): self.get_rois() for roi in self.rois: if roi.name.strip().lower() == roiname.strip().lower(): roi.clear() epics.poll(0.010, 1.0) self.set_rois(self.rois)
def SetPV(self, pv=None): "set pv, either an epics.PV object or a pvname" if pv is None: return if isinstance(pv, epics.PV): self.pv = pv elif isinstance(pv, (str, unicode)): self.pv = epics.PV(pv) self.pv.connect() epics.poll() self.pv.connection_callbacks.append(self.OnEpicsConnect) self.pv.get_ctrlvars() self.OnPVChange(self.pv.get(as_string=True)) self.pv.add_callback(self._pvEvent, wid=self.GetId()) pv_value = pv.get(as_string=True) enum_strings = pv.enum_strs sizer = wx.BoxSizer(self.orientation) self.buttons = [] if enum_strings is not None: for i, label in enumerate(enum_strings): b = buttons.GenToggleButton(self, -1, label) self.buttons.append(b) b.Bind(wx.EVT_BUTTON, Closure(self._onButton, index=i)) b.Bind(wx.EVT_RIGHT_DOWN, self._onRightDown) sizer.Add(b, flag=wx.ALL) b.SetToggle(label == pv_value) self.SetAutoLayout(True) self.SetSizer(sizer) sizer.Fit(self)
def countersCallbackFunc(self, value=None, **kw): epics.poll() val = self.scalerDev.get_all() self.ui.IoCnt.display(value) self.ui.ItCnt.display(val['calc3']) self.ui.IfCnt.display(val['calc4']) self.ui.IrCnt.display(val['calc5'])
def start(self): "Start Struck" self.EraseStart = 1 if self.Acquiring == 0: poll() self.EraseStart = 1 return self.EraseStart
def start(self): "Start Struck" self.EraseStart = 1 if self.Acquiring == 0: epics.poll() self.EraseStart = 1 return self.EraseStart
def io(self): if not self.connected: print "Device not connected" return False d_o = [] a_o = [] d_i = [] a_i = [] d_outs = { 1: PV('digitalOut1'), 2: PV('digitalOut2'), 3: PV('digitalOut3'), 4: PV('digitalOut4'), 5: PV('digitalOut5'), 6: PV('digitalOut6'), 7: PV('digitalOut7'), 8: PV('digitalOut8') } d_ins = { 1: PV('digitalIn1'), 2: PV('digitalIn2'), 3: PV('digitalIn3'), 4: PV('digitalIn4'), 5: PV('digitalIn5'), 6: PV('digitalIn6'), 7: PV('digitalIn7'), 8: PV('digitalIn8') } a_outs = { 1: PV('analogOut1'), 2: PV('analogOut2'), 3: PV('analogOut3'), 4: PV('analogOut4'), 5: PV('analogOut5'), 6: PV('analogOut6'), 7: PV('analogOut7'), 8: PV('analogOut8') } a_ins = { 1: PV('analogIn1'), 2: PV('analogIn2'), 3: PV('analogIn3'), 4: PV('analogIn4'), 5: PV('analogIn5'), 6: PV('analogIn6'), 7: PV('analogIn7'), 8: PV('analogIn8'), } poll(evt=1.e-5, iot=0.01) for i in range(0, 8): d_o.append(util.put_check(d_outs[i + 1], 1)) a_o.append(util.put_check(a_outs[i + 1], i)) d_i.append(util.pv_check(d_ins[i + 1], 1)) a_i.append(a_ins[i + 1].get() != None) return [x for sublist in [d_i, a_i, d_o, a_o] for x in sublist]
def pre_scan(self, row=0, mode=None, npulses=None, dwelltime=None, filename=None, scan=None, **kws): "run just prior to scan" if mode is not None: self.mode = mode self.cam.put('Acquire', 0, wait=True) poll(0.05, 0.5) if filename is None: filename = '' filename = fix_varname("%s_%s" % (filename, self.label)) numcapture = npulses template = "%s%s.%4.4d" auto_increment = False if self.mode == SCALER_MODE: self.ScalerMode() auto_increment = True numcapture = scan.npts file_ext = self.filesaver.lower() if file_ext.endswith(':'): file_ext = file_ext[:-1] if file_ext.endswith('1'): file_ext = file_ext[:-1] template = "%%s%%s_%%4.4d.%s" % file_ext elif self.mode == ROI_MODE: self.ROIMode() elif self.mode == NDARRAY_MODE: time.sleep(0.01) filename = self.label self.NDArrayMode(dwelltime=dwelltime, numframes=npulses) if self.mode == NDARRAY_MODE: c1 = Counter("%s%sArrayCounter_RBV" % (self.prefix, self.cam_prefix), label='Image Counter') c2 = Counter("%s%sFileNumber_RBV" % (self.prefix, self.filesaver), label='File Counter') self.counters = [c1, c2] if dwelltime is not None: self.dwelltime = dwelltime if self.dwelltime is not None: self.dwelltime_pv.put(self.dwelltime) if npulses is not None: self.cam.put('NumImages', npulses) self.config_filesaver(name=filename, number=1, enable=True, auto_save=True, template=template, numcapture=numcapture, auto_increment=auto_increment) if hasattr(self, 'custom_pre_scan'): self.custom_pre_scan(row=row, mode=mode, npulse=npulses, dwelltime=dwelltime, **kws)
def _wait_for_foreground_busy(self, timeout): """Wait for the foreground busy flag to be set.""" t0 = time() while time() < t0 + timeout: if self.foreground_done.get() == 0: break poll(.01) else: raise RobotError('operation failed to start')
def del_roi(self, roiname): "delete an roi by name" if self.rois is None: self.get_rois() for roi in self.rois: if roi.Name.strip().lower() == roiname.strip().lower(): roi.clear() poll(0.010, 1.0) self.sort_rois()
def epics_connect(self,pvname): if self.pvs.has_key(pvname): return self.pvs[pvname] p = epics.PV(pvname) epics.poll() if p.connected: self.pvs[pvname] = p return p
def put_check(pv, value): # if pvname.get() is None: # pv = PV(pvname) # else: # pv = pvname pv.put(value) poll(evt=0.5, iot=0.25) return pv_check(pv, value)