def __init__(self, json_connect_info): self.connect_info = json.loads(json_connect_info) print('*** connect_info') pp = pprint.PrettyPrinter() pp.pprint(self.connect_info) control_info = self.connect_info['body']['control']['0'][ 'control_info'] self.xpm_base = control_info['pv_base'] + ':XPM:' master_xpm_num = control_info['xpm_master'] self.master_xpm_pv = self.xpm_base + str(master_xpm_num) + ':' self.ctxt = Context('pva') self.get_xpm_info() self.get_readout_group_mask() # unfortunately, the hsd needs the Rx link reset before the Tx, # otherwise we get CRC errors on the link. # try commenting this out since Matt has made the links more reliable #self.xpm_link_reset('Rx') #self.xpm_link_reset('Tx') # must come after clear readout because clear readout increments # the event counters, and the pgp eb needs them to start from zero # comment this out since it was moved to control.py #self.l0_count_reset() # enables listening to deadtime self.xpm_link_enable() self.ctxt.close()
def pvMonitor(self): # Monitor is is easy as p4p provides it. if self._ctxt is None: self._ctxt = Context(self._provider) self._S = self._ctxt.monitor(self._pvName, self.callback, notify_disconnect=True)
def __init__(self, protocol: str, prefix, track_inputs: bool = False, input_pvs: list = None): """ Initializes controller. Stores protocol and creates context attribute if using pvAccess. Args: protocol (str): Protocol for getting values from variables ("pva" for pvAccess, "ca" for Channel Access) """ self.protocol = protocol self.last_update = "" self.pv_registry = defaultdict() self.track_inputs = track_inputs self.input_pvs = [f"{prefix}:{variable}" for variable in input_pvs] self.prefix = prefix # initalize context for pva self.context = None if self.protocol == "pva": self.context = Context("pva")
class CustomCollector(): def __init__(self,hutch): self.pvactx = Context('pva') self._hutch = hutch self._glob = {} self._pvs = {} def registerGlobalPV(self, name, pv): self._glob[name] = pv def registerPV(self, name, pv): pvs = [] for i in range(8): pvs.append( pv%i ) self._pvs[name] = pvs def collect(self): for name,pvs in self._glob.items(): g = GaugeMetricFamily(name, documentation='', labels=['instrument']) values = self.pvactx.get(pvs) logging.debug('collect %s: %s' % (pvs, str(values))) g.add_metric([self._hutch], values.raw.value) yield g for name,pvs in self._pvs.items(): g = GaugeMetricFamily(name, documentation='', labels=['instrument','partition']) values = self.pvactx.get(pvs) logging.debug('collect %s: %s' % (pvs, str(values))) for i in range(8): g.add_metric([self._hutch,str(i)], values[i].raw.value) yield g
def __init__(self, pvName, monitor='False', provider='pva', timeout=5.0, repeat=1.0, showValue=False, throw=False, verbose=False, checkPriorCount=False): self._lock = Lock() self._pvName = pvName self._history = {} self._priorValue = None self._Q = Queue() self._S = None self._T = None self._Op = None self._noConnectionYet = True self._shutDown = False self._provider = provider self._throw = throw #self._monitor = monitor self._repeat = repeat self._showValue = showValue self._timeout = timeout self._verbose = verbose self._checkPriorCount = checkPriorCount self._ctxt = Context(provider) #self._pvGetDone = threading.Event() self._pvGetPending = threading.Event() self._T = threading.Thread(target=self.pvGetTimeoutLoop, args=(self._timeout, self._throw, self._verbose)) self._T.start()
def start(self) : self.ctxt = Context('pva') self.firstCallback = True self.isClosed = False self.subscription = self.ctxt.monitor( self.getChannelName(), self.p4pcallback, request='field(value,dimension,codec,compressedSize,uncompressedSize)', notify_disconnect=True)
def start(self) : self.ctxt = Context('pva') self.firstCallback = True self.isClosed = False self.subscription = self.ctxt.monitor( getDynamicRecordName(), self.p4pcallback, request='field()', notify_disconnect=True)
def __init__(self, protocol: str): """ Store protocol and initialize context if using PVAccess. """ self.protocol = protocol # initalize context for pva self.context = None if protocol == "pva": self.context = Context("pva")
def hps_connect(root): ctxt = Context('pva') d = {} d['addr'] = ctxt.get(bldName + ':ADDR') d['port'] = ctxt.get(bldName + ':PORT') print('hps_connect {:}'.format(d)) ctxt.close() return d
def capvput(pvname, value, wait=False, timeout=5.0): global ctxt #channel = pvaccess.Channel(pvname, pvaccess.CA) #return channel.putFloat(value) if pvname.startswith('pva://'): if ctxt is None: from p4p.client.thread import Context ctxt = Context('pva') ctxt.put(pvname[6:], value, timeout=timeout, wait=wait) else: epics.caput(pvname, value, timeout=timeout, wait=wait)
def hsd_connect(epics_prefix): # Retrieve connection information from EPICS ctxt = Context('pva') values = ctxt.get(epics_prefix + ':PADDR_U') print(values) ctxt.close() d = {} d['paddr'] = values return json.dumps(d)
def __init__(self, args): print('__init__') self.args = args self.pv_xpm_base = 'DAQ:LAB2:XPM:%d' % args.x self.pvListMsgHeader = [] # filled in at alloc for g in range(8): if self.args.p & (1 << g): self.pvListMsgHeader.append(self.pv_xpm_base + ":PART:" + str(g) + ':MsgHeader') self.pvGroupMsgInsert = self.pv_xpm_base + ':GroupMsgInsert' self.ctxt = Context('pva', nt=None)
def hsd_unconfig(prefix): global epics_prefix epics_prefix = prefix ctxt = Context('pva') values = ctxt.get(epics_prefix + ':CONFIG') values['enable'] = 0 print(values) print(epics_prefix) ctxt.put(epics_prefix + ':CONFIG', values, wait=True) # This handshake seems to be necessary, or at least the .get() complete = False for i in range(100): complete = ctxt.get(epics_prefix + ':READY') != 0 if complete: break print('hsd_unconfig wait for complete', i) time.sleep(0.1) if complete: print('hsd unconfig complete') else: raise Exception('timed out waiting for hsd_unconfig') ctxt.close() return None
class TranControl(object): def __init__(self, args): print('__init__') self.args = args self.pv_xpm_base = 'DAQ:LAB2:XPM:%d' % args.x self.pvListMsgHeader = [] # filled in at alloc for g in range(8): if self.args.p & (1 << g): self.pvListMsgHeader.append(self.pv_xpm_base + ":PART:" + str(g) + ':MsgHeader') self.pvGroupMsgInsert = self.pv_xpm_base + ':GroupMsgInsert' self.ctxt = Context('pva', nt=None) def pv_put(self, pvName, val): retval = False try: self.ctxt.put(pvName, val) except TimeoutError: self.report_error("self.ctxt.put('%s', %d) timed out" % (pvName, val)) except Exception: self.report_error("self.ctxt.put('%s', %d) failed" % (pvName, val)) else: retval = True logging.debug("self.ctxt.put('%s', %d)" % (pvName, val)) return retval def run(self): print('run') self.groups = self.args.p self.pv_put(self.pvGroupMsgInsert, self.args.p) timer = 1. / self.args.r def expired(): self.pv_put(self.pvGroupMsgInsert, self.args.p) self.transitions = Timer(timer, expired) self.transitions.start() self.transitions = Timer(timer, expired) self.transitions.start() while (True): time.sleep(1)
def wave8_scan_keys(update): global prefix global ocfg # extract updates cfg = {} copy_reconfig_keys(cfg, ocfg, json.loads(update)) # Apply group ctxt = Context('pva') user_to_expert(ctxt, prefix + ':Top:', cfg, full=False) ctxt.close() # Retain mandatory fields for XTC translation for key in ('detType:RO', 'detName:RO', 'detId:RO', 'doc:RO', 'alg:RO'): copy_config_entry(cfg, ocfg, key) copy_config_entry(cfg[':types:'], ocfg[':types:'], key) return json.dumps(cfg)
def hsd_update(update): global ocfg # extract updates cfg = {} update_config_entry(cfg, ocfg, json.loads(update)) # Apply group user_to_expert(cfg, full=False) # Apply config ctxt = Context('pva') apply_config(ctxt, cfg) ctxt.close() # Retain mandatory fields for XTC translation for key in ('detType:RO', 'detName:RO', 'detId:RO', 'doc:RO', 'alg:RO'): copy_config_entry(cfg, ocfg, key) copy_config_entry(cfg[':types:'], ocfg[':types:'], key) return json.dumps(cfg)
def hsd_connect(epics_prefix): # Retrieve connection information from EPICS # May need to wait for other processes here {PVA Server, hsdioc}, so poll ctxt = Context('pva') for i in range(50): values = ctxt.get(epics_prefix+':PADDR_U') if values!=0: break print('{:} is zero, retry'.format(epics_prefix+':PADDR_U')) time.sleep(0.1) ctxt.close() d = {} d['paddr'] = values return json.dumps(d)
def wave8_connect(epics_prefix): # Retrieve connection information from EPICS # May need to wait for other processes here, so poll ctxt = Context('pva') for i in range(50): values = ctxt.get(epics_prefix+':Top:TriggerEventManager:XpmMessageAligner:RxId').raw.value if values!=0: break print('{:} is zero, retry'.format(epics_prefix+':Top:TriggerEventManager:XpmMessageAligner:RxId')) time.sleep(0.1) ctxt.close() d = {} d['paddr'] = values return json.dumps(d)
def pvGetInitiate(self, timeout=5.0, throw=False, verbose=True): #pdb.set_trace() # This code block does a synchronous get() #return self._ctxt.get( self._pvName, self.callback ) # Initiate async non-blocking pvGet using a ClientOperation. # self.pvGetCallback() handles the response and places it on self._Q if self._ctxt is None: self._ctxt = Context(self._provider) raw_get = super(Context, self._ctxt).get try: assert self._Op is None self._Op = raw_get(self._pvName, self.pvGetCallback) self._pvGetPending.set() except: raise return
def __init__(self, channelname='masarService'): """ masar service client library. Default channel name is masarService. """ self.channelname = channelname self._pva_context = Context('pva') self._proxy = MASAR(context=self._pva_context, format=channelname + ':')
def __init__(self, url_string, axisNum=1, log_debug=True): self.pvpfx = None # PV prefix, like IOC:m1 self.ctxt = None # P4P context, if any self.log_debug = log_debug if url_string.startswith("pva://"): self.url_scheme = "pva://" self.pvpfx = url_string[6:] from p4p.client.thread import Context self.ctxt = Context("pva") elif url_string.startswith("ca://"): # Channel access self.url_scheme = "ca://" self.pvpfx = url_string[5:] import epics as epics self.epics = epics else: help_and_exit(self, url_string, "invalid scheme")
def capvget(pvname, as_string=False, count=None, as_numpy=True, timeout=5.0, use_monitor=False): global ctxt #return epics.caget(pvname, as_string=as_string, count=count, as_numpy=as_numpy, timeout=timeout, use_monitor=use_monitor) #pvaccess.Channel(PVNAME, pvaccess.CA).get().getPyObject() #channel = pvaccess.Channel(pvname, pvaccess.CA) #return channel.get().getPyObject() if pvname.startswith('pva://'): if ctxt is None: from p4p.client.thread import Context ctxt = Context('pva') return ctxt.get(pvname[6:]) else: return epics.caget(pvname)
class CustomCollector(): def __init__(self): self.pvactx = Context('pva') def collect(self): g = GaugeMetricFamily('drp_dead_frac', documentation='', labels=['partition']) for p in range(8): value = self.pvactx.get('DAQ:LAB2:XPM:2:PART:%d:DeadFrac' % p) print('collect', value.raw.value) g.add_metric([str(p)], value.raw.value) yield g
def __init__(self, protocol: str, input_pvs: dict, output_pvs: dict, prefix): """ Initializes controller. Stores protocol and creates context attribute if using pvAccess. Args: protocol (str): Protocol for getting values from variables ("pva" for pvAccess, "ca" for Channel Access) input_pvs (dict): Dict mapping input variable names to variable output_pvs (dict): Dict mapping output variable names to variable """ self._protocol = protocol self._pv_registry = defaultdict() self._input_pvs = input_pvs self._output_pvs = output_pvs self._prefix = prefix self.last_input_update = "" self.last_output_update = "" # initalize context for pva self._context = None if self._protocol == "pva": self._context = Context("pva") # initialize controller for variable in {**input_pvs, **output_pvs}.values(): if variable.variable_type == "image": self.get_image(variable.name) elif variable.variable_type == "array": self.get_array(variable.name) else: self.get_value(variable.name)
def wave8_unconfig(epics_prefix): return None; ctxt = Context('pva') ctxt.put(epics_prefix+':TriggerEventManager:TriggerEventBuffer[0]:MasterEnable', 0, wait=True) ctxt.close() return None;
def __init__( self, producer: KafkaProducer, context: PVAContext, pv_name: str, output_topic: str, schema: str, periodic_update_ms: Optional[int] = None, ): self._logger = get_logger() self._producer = producer self._output_topic = output_topic request = context.makeRequest("field(value,timeStamp,alarm)") self._sub = context.monitor(pv_name, self._monitor_callback, request=request) self._pv_name = pv_name self._cached_update: Optional[Tuple[Value, int]] = None self._output_type = None self._stop_timer_flag = Event() self._repeating_timer = None self._cache_lock = Lock() try: self._message_publisher = schema_publishers[schema] except KeyError: raise ValueError( f"{schema} is not a recognised supported schema, use one of {list(schema_publishers.keys())}" ) if periodic_update_ms is not None: self._repeating_timer = RepeatTimer( milliseconds_to_seconds(periodic_update_ms), self.publish_cached_update) self._repeating_timer.start()
def main(args): sigs = [] with open(args.filename, 'r') as F: for line in F: line = line.strip() if len(line)==0 or line[:1]=='#': continue _log.debug("Read signal '%s'", line) sigs.append(line) with Context('pva') as ctxt: ctxt.put(args.pvname, sigs, wait=True) print("Success. Signal list now") for sig in ctxt.get(args.pvname): print(sig)
class CustomCollector(): def __init__(self): self.pvactx = Context('pva') self._name = None self._pv = None def registerPV(self, name, pv): self._name = name self._pv = pv def collect(self): if self._pv is None: return g = GaugeMetricFamily(self._name, documentation='', labels=['partition']) for p in range(8): pv = self._pv % p value = self.pvactx.get(pv) logging.debug('collect %s: %s' % (pv, str(value.raw.value))) g.add_metric([str(p)], value.raw.value) yield g
@rpccall('%secho') def echo(value='s', delay='d'): pass def getargs(): from argparse import ArgumentParser P = ArgumentParser() P.add_argument('-d', '--debug', action='store_true', default=False) P.add_argument('prefix') P.add_argument('method') P.add_argument('args', nargs='*') return P.parse_args() args = getargs() logging.basicConfig(level=logging.DEBUG if args.debug else logging.INFO) ctxt = Context('pva') proxy = ExampleProxy(context=ctxt, format=args.prefix) if args.method == 'add': print(proxy.add(*args.args[:2])) elif args.method == 'echo': print(proxy.echo(*args.args[:2])) else: print("No method", P.method) sys.exit(1)
class AxisCom: def __init__(self, url_string, axisNum=1, log_debug=True): self.pvpfx = None # PV prefix, like IOC:m1 self.ctxt = None # P4P context, if any self.log_debug = log_debug if url_string.startswith("pva://"): self.url_scheme = "pva://" self.pvpfx = url_string[6:] from p4p.client.thread import Context self.ctxt = Context("pva") elif url_string.startswith("ca://"): # Channel access self.url_scheme = "ca://" self.pvpfx = url_string[5:] import epics as epics self.epics = epics else: help_and_exit(self, url_string, "invalid scheme") def get( self, pvsuf, as_string=False, count=None, as_numpy=True, timeout=25.0, use_monitor=False, ): pvname = self.pvpfx + pvsuf fullname = self.url_scheme + pvname ret = None if as_string == True: raise Exception("as_string=True not supported") if self.log_debug: print( f"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} get {fullname}" ) if self.ctxt is not None: ret = self.ctxt.get(pvname, timeout=timeout) else: ret = self.epics.caget(pvname, timeout=timeout, use_monitor=use_monitor) if self.log_debug: print( f"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} get {fullname} ret={ret}" ) if ret is None: raise Exception("get None") return ret def put( self, pvsuf, value, wait=False, timeout=5.0, ): pvname = self.pvpfx + pvsuf fullname = self.url_scheme + pvname ret = None if self.log_debug: if wait: print( f"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} put {fullname} timeout={timeout} wait={wait} value={value}" ) print( f"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} put {fullname} value={value}" ) if self.ctxt is not None: ret = self.ctxt.put(pvname, value, timeout=timeout, wait=wait) if self.log_debug: print( f"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} put {fullname} value={value} pvput_ret={ret}" ) else: caput_ret = self.epics.caput(pvname, value, timeout=timeout, wait=wait) # This function returns 1 on success, # and a negative number if the timeout has been exceeded if self.log_debug: print( f"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} put {fullname} value={value} caput_ret={ret}" ) if caput_ret != 1: raise Exception( f"caput({pvname},{value}) returned error {caput_ret}") def putDbgStrToLOG(self, value, wait=True, timeout=5.0): pvsuf = "-DbgStrToLOG" try: self.put(pvsuf, value, wait=wait, timeout=timeout) except Exception as ex: print( f"{datetime.datetime.now():%Y-%m-%d %H:%M:%S} {filnam} put {pvsuf} value={value} ex={ex}" ) def getMotorPvName(self): return self.pvpfx