def caproto_context_test(): ctx = CaprotoContext() pva, = ctx.get_pvs(pvnamea) # Ignore bulk conn option pva.read() start = time.time() pvb, = ctx.get_pvs(pvnameb) mid = time.time() val = pvb.read() end = time.time() print(mid - start) print(end - mid)
class Client(object): RBV = None VAL = None VELO = None VALVE = None def __init__(self, prefix): from caproto.threading.client import Context self.prefix = prefix self.ctx = Context() self.RBV, = self.ctx.get_pvs(self.prefix + 'RBV') self.VAL, = self.ctx.get_pvs(self.prefix + 'VAL') self.VELO, = self.ctx.get_pvs(self.prefix + 'VELO') self.VALVE, = self.ctx.get_pvs(self.prefix + 'VALVE')
def test_trigger_mode(): """ Do the two TriggerMode IntEnums agree? Do all the NewPerkinElmerDetector.TriggertModes read and write as expected? """ with ioc_process() as ioc: client = CaprotoThreadingClient() setpoint_pv, readback_pv = client.get_pvs( "Sim[det1]:cam1:TriggerMode", "Sim[det1]:cam1:TriggerMode_RBV") trigger_mode_setpoint = setpoint_pv.read().data trigger_mode_readback = readback_pv.read().data # expect the trigger mode to be INTERNAL when the IOC starts up assert (trigger_mode_setpoint == SimulatedPerkinElmerDetectorIoc.TriggerMode.INTERNAL) assert (trigger_mode_readback == SimulatedPerkinElmerDetectorIoc.TriggerMode.INTERNAL) assert trigger_mode_setpoint == NewPerkinElmerDetector.TriggerMode.INTERNAL assert trigger_mode_readback == NewPerkinElmerDetector.TriggerMode.INTERNAL for trigger_mode_client, trigger_mode_server in zip( NewPerkinElmerDetector.TriggerMode, SimulatedPerkinElmerDetectorIoc.TriggerMode, ): setpoint_pv.write(trigger_mode_client) trigger_mode_setpoint = setpoint_pv.read().data trigger_mode_readback = readback_pv.read().data assert trigger_mode_setpoint == trigger_mode_client assert trigger_mode_readback == trigger_mode_client assert trigger_mode_setpoint == trigger_mode_server assert trigger_mode_readback == trigger_mode_server
def test_specified_port(monkeypatch, context, ioc): pv, = context.get_pvs(ioc.pvs['float']) pv.wait_for_connection(timeout=10) circuit = pv.circuit_manager.circuit address_list = list(caproto.get_address_list()) address_list.append('{}:{}'.format(circuit.host, circuit.port)) def get_address_list(): return address_list for module in (caproto._utils, caproto, caproto.threading.client): if hasattr(module, 'get_address_list'): print('patching', module) monkeypatch.setattr(module, 'get_address_list', get_address_list) print() print('- address list is now:', address_list) shared_broadcaster = SharedBroadcaster() new_context = Context(shared_broadcaster) pv1, = new_context.get_pvs(ioc.pvs['float']) pv1.wait_for_connection() assert pv1.connected pv1.read() new_context.disconnect()
def __init__( self, producer: KafkaProducer, context: CAContext, 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 (self._pv, ) = context.get_pvs(pv_name) # Subscribe with "data_type='time'" to get timestamp and alarm fields sub = self._pv.subscribe(data_type="time") sub.add_callback(self._monitor_callback) self._cached_update: Optional[Tuple[ReadNotifyResponse, int]] = None self._output_type = None 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 __init__(self): self.io_push_queue = None self.io_pull_queue = None self.dt = 0.1 from caproto.threading.client import Context ctx = Context() record_name = 'simple_dl' self.lst, = ctx.get_pvs(f'{record_name}:LIST')
def __init__(self): from caproto.threading.client import Context ctx = Context() dt, t, cpu, memory, battery = ctx.get_pvs('simple_daq:dt', 'simple_daq:TIME', 'simple_daq:CPU', 'simple_daq:MEMORY', 'simple_daq:BATTERY') self.dt, self.t, self.cpu, self.memory, self.battery = dt, t, cpu, memory, battery
def __init__(self, pvs): from caproto.threading.client import Context ctx = Context() self.pvs = {} self.sub = {} self.token = {} for pv in pvs: print(f"subscribing to {pv}") self.pvs[pv], = ctx.get_pvs(pv) self.sub[pv] = self.pvs[pv].subscribe() self.token['MOCK:Nested_Indices'] = self.sub['MOCK:Nested_Indices'].add_callback(self.monitor)
def main(pvname1='int', pvname2='str'): '''Simple example which connects to two motorsim PVs (by default). It tests reading, writing, and subscriptions. ''' shared_broadcaster = SharedBroadcaster() ctx = Context(broadcaster=shared_broadcaster) # Some user function to call when subscriptions receive data. called = [] def user_callback(command): print("Subscription has received data: {}".format(command)) called.append(command) pv1, pv2 = ctx.get_pvs(pvname1, pvname2) pv1.wait_for_connection() pv2.wait_for_connection() # Read and subscribe to pv1 reading = pv1.read() print(f'{pv1} read back: {reading}') sub = pv1.subscribe() sub.add_callback(user_callback) print(f'{pv2} read back: {pv2.read()}') # Test writing a couple values: value1, value2 = [val + 1 for val in reading.data], reading.data pv1.write(value1, timeout=5) reading = pv1.read() print(f'wrote {value1} and read back: {reading.data}') time.sleep(0.1) pv1.write(value2, timeout=5) reading = pv1.read() print(f'wrote {value2} and read back: {reading.data}') time.sleep(0.1) # Clean up the subscription sub.clear() pv2.go_idle() pv1.go_idle() print('The subscription callback saw the following data:') for command in called: print(f' * {command.data}')
def get_connected_pvs(pv_list, timeout=TIMEOUT): """ Returns a list of connected PVs from the given PV list. Args: pv_list (list): The full PV names list. timeout (int, optional): PV connection timeout. Returns: (list): The connected PVs. """ ctx = Context() pvs = ctx.get_pvs(*pv_list, timeout=timeout) time.sleep(timeout) return [pv.name for pv in pvs if pv.connected]
class Client(): def __init__(self, device_ca_server_prefix='device_mock:'): """ ToDo: rewrite the function to include the list of PVs. - restructure subscription to PVs to be saved as a dictionary. this will allow potential future expansions. """ from caproto.threading.client import Context self.ctx = Context() self.ca_name = device_ca_server_prefix self.dio, = self.ctx.get_pvs(f'{self.ca_name}dio', ) def get_dio(self): """ a wrapper to get digital state from the device handler process Parameters ---------- Returns ------- value :: integer Examples -------- >>> value = client.get_dio() """ return self.dio.read().data[0] def set_dio(self, value): """ a wrapper to get digital state from the device handler process Parameters ---------- value :: integer Returns ------- Examples -------- >>> client.set_dio(127) """ result = self.dio.write(value)
class PVDataSource: def __init__(self): self.ctx = Context(timeout=5) @rest_request_handler @require_authentication(permission='Read') async def read_pvs(self, request): post_data = await request.json() # strip non-ascii characters jso_str = json.dumps(post_data) jso_str = jso_str.encode('ascii', errors='ignore').decode() pv_names = json.loads(jso_str) pvs = self.ctx.get_pvs(*pv_names) data_list = [] for pv in pvs: data = self.pv_to_data(pv) data_list.append(data) return data_list @rest_request_handler @require_authentication(permission='Read') async def read_pv(self, request): pv_name = request.match_info.get('pv_name') pv = self.ctx.get_pvs(pv_name)[0] data = self.pv_to_data(pv) return data @rest_request_handler @require_authentication(permission='Write') async def write_pv(self, request): pv_name = request.match_info.get('pv_name') skip_wait = False if request.match_info.get('skip_wait'): skip_wait = True post_data = await request.json() # strip non-ascii characters jso_str = json.dumps(post_data) jso_str = jso_str.encode('ascii', errors='ignore').decode() post_data = json.loads(jso_str) pv = self.ctx.get_pvs(pv_name)[0] enum_post_data = post_data control_pv = pv.read(data_type='control') if 'ENUM' in control_pv.data_type.name: enum_post_data = [] for val in post_data: if isinstance(val, int): enum_post_data.append(val) else: enum_val = control_pv.metadata.enum_strings.index( val.encode()) enum_post_data.append(enum_val) result = pv.write(enum_post_data, wait=not skip_wait) if skip_wait or result.status.success == 1: data = self.pv_to_data(pv) return { 'status': 'success', 'message': 'PV value updated', 'data': data, } else: return { 'status': 'fail', 'message': result.status.description, } def pv_to_data(self, pv): if not pv.connected: return {'name': pv.name} pv_value = pv.read(data_type='time') data_type = pv_value.data_type.name meta_data = pv_value.metadata data_list = [] timestamp = 0 if 'ENUM' in data_type: timestamp = meta_data.timestamp * 1000 control_pv = pv.read(data_type='control') for data in pv_value.data: enum_val = control_pv.metadata.enum_strings[data] if type(enum_val) is bytes: data_list.append(enum_val.decode("utf-8")) else: data_list.append(enum_val) else: timestamp = meta_data.stamp.as_datetime().timestamp() * 1000 for data in pv_value.data: if type(data) is bytes: data_list.append(data.decode("utf-8")) else: data_list = pv_value.data.tolist() break return { 'data_type': pv_value.data_type.name, 'time_stamp': timestamp, 'alarm_status': caproto.AlarmStatus(meta_data.status).name, 'alarm_severity': caproto.AlarmSeverity(meta_data.severity).name, 'data': data_list, 'name': pv.name }
from caproto.threading.client import Context prefix = 'bitmap_generator:' ctx = Context() t1, = ctx.get_pvs(prefix + 't1') shape, = ctx.get_pvs(prefix + 'shape') image, = ctx.get_pvs(prefix + 'image')
def _run(self): from caproto.threading.client import Context, SharedBroadcaster broadcaster = SharedBroadcaster() context = Context(broadcaster) self.pvs = { key: pv for key, pv in zip(self.pvs, context.get_pvs(*self.pvs.values())) } for pv in self.pvs.values(): pv.wait_for_connection() if self.acquire: self.pvs['enabled'].write([1], wait=True) self.pvs['image_mode'].write('Continuous', data_type=ChannelType.STRING, wait=True) self.pvs['acquire'].write(1, wait=False) width = self.pvs['array_size0'].read().data[0] height = self.pvs['array_size1'].read().data[0] depth = self.pvs['array_size2'].read().data[0] color_mode = self.pvs['color_mode'].read( data_type=ca.ChannelType.STRING) color_mode = color_mode.data[0].decode('ascii') bayer_pattern = self.pvs['bayer_pattern'].read( data_type=ca.ChannelType.STRING) bayer_pattern = bayer_pattern.data[0].decode('ascii') self.new_image_size.emit(width, height, depth, color_mode, bayer_pattern) print(f'width: {width} height: {height} depth: {depth} ' f'color_mode: {color_mode}') def update(response): if self.stop_event.is_set(): if self.sub is not None: self.sub.clear() self.sub = None return native_type = ca.field_types['native'][response.data_type] self.new_image.emit(response.metadata.timestamp, width, height, depth, color_mode, bayer_pattern, native_type, response.data) array_data = self.pvs['array_data'] dtype = ca.field_types['time'][array_data.channel.native_data_type] if self.barrier is not None: # Synchronize with image viewer widget, if necessary self.barrier.wait() self.sub = self.pvs['array_data'].subscribe(data_type=dtype) # NOTE: threading client requires that the callback function stays in # scope, as it uses a weak reference. self.sub.add_callback(update) print('Monitor has begun') self.stop_event.wait()
class Client(): def __init__(self,device_ca_server_prefix = 'device_mock:'): """ ToDo: rewrite the function to include the list of PVs. - restructure subscription to PVs to be saved as a dictionary. this will allow potential future expansions. """ from caproto.threading.client import Context self.ctx = Context() self.ca_name = device_ca_server_prefix self.pv_names = ['freq', 'dio', 'queue_length', 'data', 'peek_data', 'packet_shape', 'LIST'] self.pvs = {} for item in self.pv_names: self.pvs[item], = self.ctx.get_pvs(f'{self.ca_name}{item}',) def get_all(self): """ get all PV values as a dictionary """ dict = {} for key in self.pvs.keys(): dict[key] = self.pvs[key].read().data return dict def get_dio(self): """ a wrapper to get digital state from the device handler process Parameters ---------- Returns ------- value :: integer Examples -------- >>> value = client.get_dio() """ return self.dio.read().data[0] def set_dio(self, value): """ a wrapper to get digital state from the device handler process Parameters ---------- value :: integer Returns ------- Examples -------- >>> client.set_dio(127) """ result = self.dio.write(value)
default_prefix='camera:' print('epics Client') image = epics.PV(pvname = default_prefix+'image', connection_timeout = 20) t1 = time() def image_get(): """ I have created this fucntion to simplify the call from timeit. It doesn't change the fact that pyepics is slower than caproto """ global image return image.get(timeout = 20) img = image.get(timeout = 20) t2 = time() print(t2-t1, img.mean(), img.max(), img.min()) img2 = img.reshape((3960,3960)) print('caproto Client') ctx = Context() img_caproto, = ctx.get_pvs(default_prefix+'image') t1 = time() img_caproto_data = img_caproto.read() t2 = time() print(t2-t1, img_caproto_data.data.reshape((3960,3960)).mean(), img_caproto_data.data.reshape((3960,3960)).max(), img_caproto_data.data.reshape((3960,3960)).min()) from timeit import timeit t = timeit(image_get, number = 10) print('pyepics client: {}'.format(t/10)) t = timeit(img_caproto.read, number = 10) print('caproto client: {}'.format(t/10))
#!/usr/bin/python # -*- coding: utf-8 -*- from caproto.threading.client import Context ctx = Context() pvs = ctx.get_pvs('chart:image', 'chart:t1') def read_pvs(pvs): for pv in pvs: print(pv.read().data) if __name__ == '__main__': pass
import logging from logging import debug, info, warning, error logging.getLogger(__name__).addHandler(logging.NullHandler()) from caproto.threading.client import Context ctx = Context() prefix = 'camera_bottom' image, frameID = ctx.get_pvs(f'{prefix}:image', f'{prefix}:frameID') if __name__ == '__main__': import logging logging.basicConfig( filename=gettempdir() + '/camera_bottom_DLC.log', level=logging.DEBUG, format= "%(asctime)-15s|PID:%(process)-6s|%(levelname)-8s|%(name)s| module:%(module)s-%(funcName)s|message:%(message)s" )
""" """ from matplotlib import pyplot as plt from logging import debug, warn, info, error import epics from time import time, sleep from _thread import start_new_thread from caproto.threading.client import Context from pdb import pm import epics from numpy import nan, argmax default_prefix = 'io_device_single:' ctx = Context() ca_img, ca_t1, ca_t2 = ctx.get_pvs(default_prefix + 'image', default_prefix + 't1', default_prefix + 't2') image = epics.PV(pvname=default_prefix + 'image', connection_timeout=20, verbose=True, auto_monitor=False) t1 = epics.PV(pvname=default_prefix + 't1', verbose=False) t2 = epics.PV(pvname=default_prefix + 't2', verbose=False) lst = [] def pyepics_for_loop(): print('img,img.shape,img.max(),img.mean(),t1.get(),t2.get()') for i in range(10):
#!/usr/bin/env python3 from caproto.threading.client import Context prefix='NIH:PI1.' ctx = Context() ipaddress, = ctx.get_pvs(prefix+'ipaddress') hostname, = ctx.get_pvs(prefix+'hostname') def data_to_str(arr): str = '' for i in arr: str += chr(i) return str if __name__ == '__main__': pass
#!/usr/bin/env python3 """ """ import socket device_ca_server_prefix = f'{socket.gethostname()}_dio_controller:' from caproto.threading.client import Context ctx = Context() ca_name = device_ca_server_prefix pv_names = [ 'dio', 'bit0_indicator', 'bit0', 'bit0_enable', 'bit1_indicator', 'bit1', 'bit1_enable', 'bit2_indicator', 'bit2', 'bit2_enable', 'bit3_indicator', 'bit3', 'bit3_enable', 'shutdown_state', 'operating_mode', 'pulse_generator_depre_width', 'pulse_generator_pre_width', 'pulse_generator_delay', 'pulse_generator_period' ] pvs = {} for item in pv_names: pvs[item], = ctx.get_pvs(f'{ca_name}{item}', ) if __name__ == '__main__': pass
#!/usr/bin/env python3 from caproto.threading.client import Context ctx = Context() dt,t,cpu,memory,battery = ctx.get_pvs('simple:dt','simple:TIME','simple:CPU','simple:MEMORY','simple:BATTERY')
#!/usr/bin/env python3 import time from caproto.threading.client import Context ctx = Context() keypress, = ctx.get_pvs('io:keypress') res = keypress.read() print("Keypress value when startup up: %s" % res.data[0]) sub = keypress.subscribe() def f(response): print("New keypress received: %s" % response.data[0]) token = sub.add_callback(f) def sleep(seconds): print("sleeping for %s seconds" % seconds) time.sleep(seconds) sleep(120)
#!/usr/bin/env python3 from caproto.threading.client import Context from caproto.sync.client import read ctx = Context() # a client Context used to explore the servers below #a, b, c = ctx.get_pvs('simple:A', 'simple:B', 'simple:C') #mocka, mockb, mockc = ctx.get_pvs('mock:A', 'mock:B', 'mock:C') #integer ,float ,vector, string, dict, t, dt = ctx.get_pvs('simple:integer', 'simple:float', 'simple:vector', 'simple:string','simple:pickle','simple:t','simple:dt') from caproto.threading.client import Context ctx = Context() dt, x, y = ctx.get_pvs('2d_random_walk:dt', '2d_random_walk:x', '2d_random_walk:y')
#!/usr/bin/env python3 from caproto.threading.client import Context prefix = 'wt:' ctx = Context() request, response = ctx.get_pvs(prefix + 'request', prefix + 'response') request.read() response.read()
#!/usr/bin/env python3 from caproto.threading.client import Context prefix = 'NIH:DI245.' ctx = Context() counter, = ctx.get_pvs(prefix + 'counter') update_time, = ctx.get_pvs(prefix + 'update_time')
#!/usr/bin/env python3 import time from caproto.threading.client import Context def sleep(seconds): print("sleeping for %s seconds" % seconds) time.sleep(seconds) ctx = Context() a, b = ctx.get_pvs('simple:A', 'simple:B') print("Value of a: %s" % a.read().data[0]) print("Value of b: %s" % b.read().data[0]) sleep(1) print("Setting value of b to: %s" % 5) b.write([5], wait=True) sleep(1) print("Value of b now: %s" % b.read().data[0])
from caproto.threading.client import Context ctx = Context() image, = ctx.get_pvs('big_image:image') # def f(sub,response): # responses.append(response.data) # # sub = image.subscribe() # token = sub.add_callback(f) def test_iamge_read(image, N=10): from time import time for i in range(N): t1 = time() arr = image.read().data t2 = time() print(t2 - t1)
def simulated_traffic(send_queue, receive_queue): while True: item = send_queue.get() time.sleep(random.random()) receive_queue.put(item) receive_queue = queue.Queue() traffic_thread = threading.Thread(target=simulated_traffic, args=(send_queue, receive_queue)) traffic_thread.start() # Subscribe to position ctx = Context() pv, = ctx.get_pvs('random_walk:pos') pos_subscription = pv.subscribe(data_type='time') pos_readings = [] def append_pos_reading(reading): pos_readings.append(reading) pos_subscription.add_callback(append_pos_reading) def plan(threshold): yield from bps.open_run() yield from bps.kickoff(det, wait=True) target_pos = -3.0
#!/usr/bin/env python3 from caproto.threading.client import Context prefix = 'MOCK:' ctx = Context() start, = ctx.get_pvs(prefix + 'start') status, = ctx.get_pvs(prefix + 'status') period, = ctx.get_pvs(prefix + 'period') Nested_Indices, = ctx.get_pvs(prefix + 'Nested_Indices') if __name__ == '__main__': prefix = 'TEST:CLIENT.' from pdb import pm from tempfile import gettempdir import logging print(gettempdir() + '/{}.log'.format(prefix)) logging.basicConfig(filename=gettempdir() + '/{}.log'.format(prefix), level=logging.DEBUG, format="%(asctime)s %(levelname)s: %(message)s")