def main(cls: Type[PVGroup], default_prefix: str = 'sim:', macros: Optional[Dict[str, str]] = None, ) -> PVGroup: """ Boilerplate for running a simple IOC. Expects a usable docstring on the class. Parameters ---------- cls : PVGroup class The top-level PVGroup. default_prefix : str, optional The default prefix. macros : dict, optional The macro options to pass to `ioc_arg_parser`. Returns ------- ioc : PVGroup The instantiated PVGroup, after the IOC runs. """ ioc_options, run_options = ioc_arg_parser( default_prefix=default_prefix, desc=dedent(cls.__doc__), macros=macros, ) ioc = cls(**ioc_options) run(ioc.pvdb, **run_options) return ioc
def start(server_prefix, client_pvs): from sequence_server_wrapper.template import Server from sequence_server_wrapper.template import ThreadingClient ioc_options, run_options = ioc_arg_parser( default_prefix=server_prefix, desc='description') io_server = ServerExample(**ioc_options) print(f'io device is {io_server.device}') # instantiate of the Device object and initializes it. system = DeviceExample() system.init() # Esteblish crosslinks between device and io (server) system.io = io_server io_server.seq.system = io_server.system = system pvs = client_pvs io_client = ThreadingClient(pvs) io_client.system = system #start async caproto server IO run(io_server.pvdb, **run_options)
def main(): ioc_options, run_options = ioc_arg_parser( default_prefix="{system}:{subsystem}", desc='Solid attenuator IOC', macros={ 'system': 'AT1K4', 'subsystem': subsystem, 'ev_pv': eV_name, 'pmps_run_pv': pmps_run_name, 'pmps_tdes_pv': pmps_tdes_name, 'motor_prefix': motor_prefix, 'autosave_path': autosave_path, }, ) ioc = create_ioc( **ioc_options, filter_group={ N: f'{N:02d}' for N in range(FIRST_FILTER, NUM_BLADES + FIRST_FILTER) }, ) util.config_logging(ioc.log, level=log_level) run(ioc.pvdb, **run_options)
def main(): service = CavityService() loop = asyncio.get_event_loop() _, run_options = ioc_arg_parser( default_prefix='', desc="Simulated CM Cavity Service") run(service, **run_options)
def __init__(self, pump_id, prefix=''): """ """ from syringe_pump.device import Device import sys if pump_id == 1 or pump_id == 3: orientation = 'Y' elif pump_id == 2 or pump_id == 4: orientation = 'Z' pump = Device() pump.init(pump_id, 0.1, 100, orientation, 250) pump.start() from tempfile import gettempdir import logging filename = gettempdir() + f'/syringe_pump_device_io_{pump_id}.log' print(filename) logging.basicConfig( filename=filename, level=logging.DEBUG, format= "%(asctime)s %(levelname)s %(module)s.%(funcName)s: %(message)s") debug('test write debug') ioc_options, run_options = ioc_arg_parser( default_prefix=prefix + 'SYRINGE' + str(pump_id) + '.', desc='Run an IOC that does blocking tasks on a worker thread.') ioc = Server(**ioc_options) ioc.device = pump run(ioc.pvdb, **run_options)
def main(): print(''' *** WARNING *** This script spawns an EPICS IOC which responds to ALL caget, caput, camonitor requests. As this is effectively a PV black hole, it may affect the performance and functionality of other IOCs on your network. The script ignores the --interfaces command line argument, always binding only to 127.0.0.1, superseding the usual default (0.0.0.0) and any user-provided value. *** WARNING *** Press return if you have acknowledged the above, or Ctrl-C to quit.''') try: input() except KeyboardInterrupt: print() return print(''' PV blackhole started ''') _, run_options = ioc_arg_parser(default_prefix='', desc="PV black hole") run_options['interfaces'] = ['127.0.0.1'] run(ReallyDefaultDict(fabricate_channel), **run_options)
def main(): service = ProfMonService() loop = asyncio.get_event_loop() _, run_options = ioc_arg_parser(default_prefix='', desc="Simulated Profile Monitor Service") loop.create_task(service.recv_profiles()) loop.call_soon(service.request_profiles) run(service, **run_options)
def main(): ioc_options, run_options = ioc_arg_parser( default_prefix='type_varieties:', desc='Run an IOC with PVs of various data types.') prefix = ioc_options['prefix'] prefixed_pvdb = {prefix + key: value for key, value in pvdb.items()} warnings.warn("The IOC options are ignored by this IOC. " "It needs to be updated.") run(prefixed_pvdb, **run_options)
def main(): service = BPMService() loop = asyncio.get_event_loop() _, run_options = ioc_arg_parser(default_prefix='', desc="Simulated BPM Service") loop.create_task(service.publish_z()) loop.create_task(service.recv_orbit_array()) loop.call_soon(service.request_orbit) run(service, **run_options)
def main(): service = BMAGService() loop = asyncio.get_event_loop() _, run_options = ioc_arg_parser(default_prefix='', desc="Simulated Undulator Match Service") loop.create_task(service.recv_twiss_list()) loop.create_task(service.rotate_buffer()) loop.create_task(service.print_buffer()) loop.call_soon(service.request_twiss) run(service, **run_options)
def main(): """Console script for lakeshore336_ioc.""" ioc_options, run_options = ioc_arg_parser( default_prefix='ES7011:LakeShore336:', desc=dedent(LakeshoreModel336.__doc__)) ioc = LakeshoreModel336(**ioc_options) run(ioc.pvdb, **run_options) return 0
def main(): _, run_options = ioc_arg_parser(default_prefix='', desc="PV black hole") router = Router(fabricate_channel) router.add_route("BPMS:.+:[0-9]+:(X|Y|TMIT)", data_type=float, get=bpm.get, new_subscription=bpm.subscribe, remove_subscription=bpm.unsubscribe) run(router, **run_options)
def main(): pvdb = {} with open("xcor_list.json") as f: mags = json.load(f) pvs = [MagnetPV(mag["devname"], "XCOR{}".format(mag["devname"].split(":")[-1]), prefix=mag["devname"]) for mag in mags] for pv in pvs: pvdb.update(**pv.pvdb) _, run_options = ioc_arg_parser( default_prefix='', desc="Simulated Corrector Magnet IOC") run(pvdb, **run_options)
def main(): ioc_options, run_options = ioc_arg_parser( default_prefix='', desc=IOCMain.__doc__, macros={ 'system': 'AT1K4', 'pmps_run': 'PMPS:HXR:AT1K4:RUN', 'ev_pv': 'LCLS:SXR:BEAM:EV', }, ) ioc = IOCMain(**ioc_options) run(ioc.pvdb, **run_options)
def main(): """Console script for fastccd_support_ioc.""" ioc_options, run_options = ioc_arg_parser( default_prefix='ES7011:FastCCD:cam1:', desc=dedent(FCCDSupport.__doc__)) ioc = FCCDSupport(camera_prefix='ES7011:FastCCD:cam1:', shutter_prefix='ES7011:ShutterDelayGenerator:', hdf5_prefix='ES7011:FastCCD:HDF1:', **ioc_options) run(ioc.pvdb, **run_options) return 0
def main(): pvdb = {} with open("xcor_list.json") as f: mags = json.load(f) pvs = [ MagnetPV(mag["devname"], "XCOR{}".format(mag["devname"].split(":")[-1]), prefix=mag["devname"]) for mag in mags ] for pv in pvs: pvdb.update(**pv.pvdb) _, run_options = ioc_arg_parser(default_prefix='', desc="Simulated Corrector Magnet IOC") run(pvdb, **run_options)
def main(): ioc_options, run_options = ioc_arg_parser(default_prefix=prefix, desc='Solid attenuator IOC', macros={ 'ev_pv': eV_name, 'pmps_run_pv': pmps_run_name, 'pmps_tdes_pv': pmps_tdes_name, 'motor_prefix': motor_prefix, 'autosave_path': autosave_path, }) ioc = create_ioc(**ioc_args, **ioc_options) util.config_logging(ioc.log, level=log_level) run(ioc.pvdb, **run_options)
def main(): """Console script for fastccd_support_ioc.""" ioc_options, run_options = ioc_arg_parser( default_prefix='ES7011:ShutterDelayGenerator:', desc=dedent(DelayGenerator.__doc__)) ioc = DelayGenerator(**ioc_options) logger.info('\n'.join([ "\nAuto-generated Ophyd device for this PVGroup", "#" * 80, str(conversion.group_to_device(ioc)), "#" * 80 ])) run(ioc.pvdb, **run_options) return 0
def run_io(command, device): """ """ #from system level import System Level class from tempfile import gettempdir import logging logfile_name = 'syringe_pump_device_io.log' print(f"the location of the log file is {gettempdir()+'/' + logfile_name}") logging.basicConfig(filename=gettempdir()+'/'+logfile_name, level=logging.DEBUG, format="%(asctime)s %(levelname)s: %(message)s") debug('test write debug') ioc_options, run_options = ioc_arg_parser( default_prefix='NIH:SYRINGE.', desc='Run an IOC that does blocking tasks on a worker thread.') ioc = Server(**ioc_options) ioc.device = device run(ioc.pvdb, **run_options)
def run_server(name = 'simple_daq'): from caproto_sandbox.simple_daq.driver import Driver from caproto_sandbox.simple_daq.device import Device from caproto_sandbox.simple_daq.server import Server import sys print(sys.argv) sys.argv.append('--list-pvs') driver = Driver() device = Device(driver = driver) device.start() ioc_options, run_options = ioc_arg_parser( default_prefix=f'{name}:', desc=dedent(Server.__doc__)) server = Server(**ioc_options) # pass the device instance into the server instance for bidirectional communication server.device = device run(server.pvdb, **run_options)
"""#!/usr/bin/env python3 """ Simple IOC based on caproto library. It has """ from caproto.server import pvproperty, PVGroup, ioc_arg_parser, run import caproto from textwrap import dedent from pdb import pm from numpy import random, array, zeros, ndarray, nan, isnan from time import time, sleep, ctime if __name__ == '__main__': from icarus_nmr.device_server import Server from icarus_nmr.device_daq import DI4108_DL device = DI4108_DL() device.pr_buffer_size = (6400, 10) from icarus_nmr.mock_driver import Driver driver = Driver() device.bind_driver(driver) device.init() ioc_options, run_options = ioc_arg_parser(default_prefix='device_dl:', desc=dedent(Server.__doc__)) ioc = Server(**ioc_options) device.pr_pracket_size = 128 ioc.device = device run(ioc.pvdb, **run_options)
import pathlib temp_path = pathlib.Path( '/tmp' if sys.platform != 'win32' else os.environ.get('TEMP')) class CustomWrite(PVGroup): """ When a PV is written to, write the new value into a file as a string. """ DIRECTORY = temp_path async def my_write(self, instance, value): # Compose the filename based on whichever PV this is. pv_name = instance.pvspec.attr # 'A' or 'B', for this IOC with open(self.DIRECTORY / pv_name, 'w') as f: f.write(str(value)) print(f'Wrote {value} to {self.DIRECTORY / pv_name}') return value A = pvproperty(put=my_write, value=0) B = pvproperty(put=my_write, value=0) if __name__ == '__main__': ioc_options, run_options = ioc_arg_parser( default_prefix='custom_write:', desc='Run an IOC with PVs that, when written to, update a file.') ioc = CustomWrite(**ioc_options) run(ioc.pvdb, **run_options)
return 'idle' @acquire.startup async def acquire(self, instance, async_lib): # monkey patch the instance like whoa instance.async_lib = async_lib instance.ev = async_lib.Event() instance.ev.set() wait = pvproperty(value=2.0) wait_time = pvproperty(value=0) @wait.startup async def wait(self, instance, async_lib): instance.async_lib = async_lib @wait.getter async def wait(self, instance): sleep_time = random.randint(0, 15) await self.wait_time.write(sleep_time) await instance.async_lib.library.sleep(sleep_time) return sleep_time if __name__ == '__main__': ioc_options, run_options = ioc_arg_parser( default_prefix='trigger_with_pc:', desc=dedent(TriggeredIOC.__doc__)) ioc = TriggeredIOC(**ioc_options) run(ioc.pvdb, **run_options)
def main(): service = GenericPVService() _, run_options = ioc_arg_parser( default_prefix='', desc="Generic PV Service") run(service, **run_options)
A = pvproperty(value=1) B = pvproperty(value=2) # ADDED THIS LINE C = pvproperty(value=2.0, dtype=float, precision=5, name='foo', units='m', ) @C.putter async def C(self, instance, value): print("I got value ", value) return max(.1, value) @C.getter async def C(self, instance): print("Hi Mom!") D = pvproperty(value=0.0, dtype=float, read_only=True) @D.getter async def D(self, instance): await self.C.write(random.random() * self.A.value) return time.time() if __name__ == '__main__': ioc_options, run_options = ioc_arg_parser( default_prefix='simple:', desc="Run an IOC with two simple, uncoupled, readable/writable PVs.") ioc = SimpleIOC(**ioc_options) run(ioc.pvdb, **run_options)
@process.putter async def process(self, instance, value): # Gather the current values in a `locals()` dictionary: formula_locals = { name: self._all_variables[name].value for name in self.variables.value } # Actually run the formula: ret = eval(self.code_object, formula_locals) print('Evaluating:', self.formula.value, '=', ret) print( 'where:', ', '.join(f'{name}={value}' for name, value in formula_locals.items() if not name.startswith('_'))) # And stash the result in `output`: await self.output.write(ret) return 0 if __name__ == '__main__': ioc_options, run_options = ioc_arg_parser( default_prefix='dyncalc:', desc="Run an IOC that dynamically adds channels for the formula") ioc = DynamicCalc(**ioc_options) run(ioc.pvdb, **run_options)
async def actuate(self, instance, async_lib): step_size = self.step_size.value setpoint = self.setpoint.value readback = self.readback.value moving = self.moving.value actuate = self.actuate.value stop = self.stop.value if stop: await self.stop.write(0) await self.moving.write(0) elif actuate or moving: if moving != 1: await self.actuate.write(0) await self.moving.write(1) delta = setpoint - readback if abs(delta) <= step_size: await self.readback.write(setpoint) await self.moving.write(0) else: await self.readback.write(readback + np.sign(delta) * step_size) if __name__ == '__main__': ioc_options, run_options = ioc_arg_parser( default_prefix='fake_motor:', desc="An IOC which mocks a simple motor") ioc = FakeMotorIOC(**ioc_options) run(ioc.pvdb, **run_options)
# This method will be called when the server starts up. print('* t1 method called at server startup') queue = async_lib.ThreadsafeQueue() # Start a separate thread that monitors keyboard input, telling it to # put new values into our async-friendly queue thread = threading.Thread(target=device.start_io_interrupt_monitor, daemon=True, kwargs=dict(new_value_callback=queue.put)) thread.start() # Loop and grab items from the queue one at a time while True: value = await queue.async_get() if 'image' in list(value.keys()): await self.image.write(value['image']) print('image in ioc:', self.image.value.mean(), self.image.value.max(), self.image.value.min()) device = Device() if __name__ == '__main__': ioc_options, run_options = ioc_arg_parser( default_prefix='camera:', desc='Run an IOC that updates via I/O interrupt on key-press events.') ioc = IOInterruptIOC(**ioc_options) print(ioc.image) run(ioc.pvdb, **run_options)
gate17 = pvproperty(name='.G17', dtype=int) gate18 = pvproperty(name='.G18', dtype=int) gate19 = pvproperty(name='.G19', dtype=int) gate20 = pvproperty(name='.G20', dtype=int) gate21 = pvproperty(name='.G21', dtype=int) gate22 = pvproperty(name='.G22', dtype=int) gate23 = pvproperty(name='.G23', dtype=int) gate24 = pvproperty(name='.G24', dtype=int) gate25 = pvproperty(name='.G25', dtype=int) gate26 = pvproperty(name='.G26', dtype=int) gate27 = pvproperty(name='.G27', dtype=int) gate28 = pvproperty(name='.G28', dtype=int) gate29 = pvproperty(name='.G29', dtype=int) gate30 = pvproperty(name='.G30', dtype=int) gate31 = pvproperty(name='.G31', dtype=int) gate32 = pvproperty(name='.G32', dtype=int) gates = SubGroup(GatesGroup, prefix='') update_rate = pvproperty(name='.RATE', dtype=int) auto_count_update_rate = pvproperty(name='.RAT1', dtype=int) egu = pvproperty(value='EGU', name='.EGU', dtype=ChannelType.STRING) if __name__ == '__main__': ioc_options, run_options = ioc_arg_parser( default_prefix='scaler_tests:', desc="ophyd.tests.test_scaler test IOC") ioc = EpicsScalerGroup(**ioc_options) run(ioc.pvdb, **run_options)
setpoint = self.parent.value pos = setpoint + random.random() / 100.0 # Set the use, dial, and then raw readbacks: timestamp = time.time() await instance.write(pos, timestamp=timestamp) await self.dial_readback_value.write(pos, timestamp=timestamp) await self.raw_readback_value.write(int(pos * 100000.), timestamp=timestamp) class RecordMockingIOC(PVGroup): # Define two records, an analog input (ai) record: motor1 = pvproperty(value=1.0, mock_record='my_motor') motor2 = pvproperty(value=2.0, mock_record='my_motor') if __name__ == '__main__': ioc_options, run_options = ioc_arg_parser( default_prefix='mock:', desc='Run an IOC that mocks a custom motor record') # Instantiate the IOC, assigning a prefix for the PV names. ioc = RecordMockingIOC(**ioc_options) print('PVs:', list(ioc.pvdb)) # ... but what you don't see are all of the analog input record fields print('Fields of motor1:', list(ioc.motor1.fields.keys())) # Run IOC. run(ioc.pvdb, **run_options)
driver = Driver() device = Device(driver = driver) device.start() ioc_options, run_options = ioc_arg_parser( default_prefix=f'{name}:', desc=dedent(Server.__doc__)) server = Server(**ioc_options) # pass the device instance into the server instance for bidirectional communication server.device = device run(server.pvdb, **run_options) if __name__ == '__main__': from caproto_sandbox.simple_daq.driver import Driver from caproto_sandbox.simple_daq.device import Device import sys driver = Driver() device = Device(driver = driver) device.start() ioc_options, run_options = ioc_arg_parser( default_prefix='simple_daq:', desc=dedent(Server.__doc__)) server = Server(**ioc_options) # pass the device instance into the server instance for bidirectional communication server.device = device print(sys.argv) run(server.pvdb, **run_options)
while True: # compute next value # Let the async library wait for the next iteration t1 = time() await async_lib.library.sleep(self.dt.value) t2 = time() # update the ChannelData instance and notify any subscribers await instance.write(value=(t2 - t1)) @float.startup async def float(self, instance, async_lib): 'Periodically update the value' from time import time, sleep print(self.float.value) while True: # compute next value # Let the async library wait for the next iteration t1 = time() await async_lib.library.sleep(self.dt.value) t2 = time() # update the ChannelData instance and notify any subscribers await instance.write(value=self.t.value) from ubcs_auxiliary.threading import start_new_safe_thread if __name__ == '__main__': ioc_options, run_options = ioc_arg_parser(default_prefix='simple:', desc=dedent(SimpleIOC.__doc__)) ioc = SimpleIOC(**ioc_options) run(ioc.pvdb, **run_options)
input_count_rate = pvproperty( name='InputCountRate', dtype=unknown, read_only=True) output_count_rate = pvproperty( name='OutputCountRate', dtype=unknown, read_only=True) mca_bin_width = pvproperty( name='MCABinWidth_RBV', dtype=unknown, read_only=True) calibration_energy = pvproperty( name='CalibrationEnergy_RBV', dtype=unknown, read_only=True) current_pixel = pvproperty(name='CurrentPixel', dtype=unknown) dynamic_range = pvproperty( name='DynamicRange_RBV', dtype=unknown, read_only=True) preset_events = pvproperty_with_rbv(name='PresetEvents', dtype=unknown) preset_triggers = pvproperty_with_rbv(name='PresetTriggers', dtype=unknown) trace_data = pvproperty(name='TraceData', dtype=unknown) trace_mode = pvproperty_with_rbv(value='Mode', name='TraceMode', dtype=str) trace_time_array = pvproperty(name='TraceTimeArray', dtype=unknown) trace_time = pvproperty_with_rbv(name='TraceTime', dtype=unknown) class McaDxpIOC(PVGroup): mca = SubGroup(EpicsMCAGroup, prefix='mca') dxp = SubGroup(EpicsDXPGroup, prefix='dxp:') if __name__ == '__main__': ioc_options, run_options = ioc_arg_parser( default_prefix='test_mca:', desc="ophyd.tests.test_mca test IOC") ioc = McaDxpIOC(**ioc_options) run(ioc.pvdb, **run_options)
_readback_suffix = ":PRESS_RBV" ''' enum_strings = ['NOT OK', 'OK'] ghc_ILK_OK_RBV = pvproperty(value=0, enum_strings=enum_strings, dtype=ChannelType.ENUM, name = 'ghc:ILK_OK_RBV') enum_strings = ['PressInvalid', 'GaugeDisconnected', 'OoR', 'Off', 'Starting', 'Valid', 'ValidHi', 'ValidLo' ] ghc_STATE_RBV = pvproperty(value=0, enum_strings=enum_strings, dtype=ChannelType.ENUM, name = 'ghc:STATE_RBV') ghc_PRESS_RBV = pvproperty(value=5E-25, record = 'ai', name = 'ghc:PRESS_RBV') if __name__ == '__main__': ioc_options, run_options = ioc_arg_parser( default_prefix='test:', desc='Run an IOC that mocks enum pv.') # Instantiate the IOC, assigning a prefix for the PV names. ioc = RecordMockingIOC(**ioc_options) # Run IOC. run(ioc.pvdb, **run_options)
alarm_group='alarm_a') pair_rbv = pvproperty(value=0.0, read_only=True, alarm_group='alarm_a') pair_set = pvproperty(value=0.0, lower_ctrl_limit=-100.0, upper_ctrl_limit=100.0, alarm_group='alarm_a') @pair_set.putter async def pair_set(self, instance, value): await self.pair_rbv.write(value=value) waveform = pvproperty(value=[ord('a'), ord('b'), ord('c')], read_only=True, alarm_group='alarm_a') bool_enum = pvproperty(value=True, alarm_group='alarm_a') alarm_status = pvproperty(value=0) set_severity = pvproperty(value=0) @set_severity.putter async def set_severity(self, instance, severity): await self.read_only.alarm.write( severity=severity, status=self.alarm_status.value) if __name__ == '__main__': ioc_options, run_options = ioc_arg_parser( default_prefix='signal_tests:', desc="ophyd.tests.test_signal test IOC") ioc = SignalTestIOC(**ioc_options) run(ioc.pvdb, **run_options)