def serve_forever(ioc_name: str, pv_prefix: str, macros: Dict[str, str]): """ Server the PVs for the remote ioc server Args: ioc_name: The name of the IOC to be run, including ioc number (e.g. LSICORR_01) pv_prefix: prefix for the pvs macros: Dictionary containing IOC macros Returns: """ ioc_name_with_pv_prefix = "{pv_prefix}{ioc_name}:".format(pv_prefix=pv_prefix, ioc_name=ioc_name) print_and_log(ioc_name_with_pv_prefix) server = SimpleServer() server.createPV(ioc_name_with_pv_prefix, STATIC_PV_DATABASE) # Run heartbeat IOC, this is done with a different prefix server.createPV(prefix="{pv_prefix}CS:IOC:{ioc_name}:DEVIOS:".format(pv_prefix=pv_prefix, ioc_name=ioc_name), pvdb={"HEARTBEAT": {"type": "int", "value": 0}}) # Looks like it does nothing, but this creates *and automatically registers* the driver # (via metaclasses in pcaspy). See declaration of DriverType in pcaspy/driver.py for details # of how it achieves this. LSiCorrelatorIOC(pv_prefix, macros) register_ioc_start(ioc_name, STATIC_PV_DATABASE, ioc_name_with_pv_prefix) try: while True: server.process(0.1) except Exception: print_and_log(traceback.format_exc()) raise
def pv_server(scope='function'): prefix = 'Ts:' pvdb = { 'pv1': { 'value': 0, 'hihi': 10, 'high': 5, 'low': -5, 'lolo': -10 }, 'pv2': {}, 'wf': { 'type': 'char', 'count': 300, 'value': 'some initial message. but it can become very long.' } } server = SimpleServer() server.createPV(prefix, pvdb) driver = ioDriver() server_thread = ServerThread(server) server_thread.start() yield server_thread # After tests have completed or faileds server_thread.stop()
def run(self, target, bindings, *args, **kwargs): server = SimpleServer() server.createPV(prefix=kwargs['pv_prefix'], pvdb=bindings) driver = PropertyExposingDriver(target=target, pv_dict=bindings) delta = 0.0 # Delta between cycles count = 0 # Cycles per second counter timer = 0.0 # Second counter while True: start = datetime.now() # pcaspy's process() is weird. Docs claim argument is "processing time" in seconds. # But this is not at all consistent with the calculated delta. # Having "watch caget" running has a huge effect too (runs faster when watching!) # Additionally, if you don't call it every ~0.05s or less, PVs stop working. Annoying. # Set it to 0.0 for maximum cycle speed. server.process(0.1) target.process(delta) driver.process(delta) delta = (datetime.now() - start).total_seconds() count += 1 timer += delta if timer >= 1.0: print "Running at %d cycles per second (%.3f ms per cycle)" % (count, 1000.0 / count) count = 0 timer = 0.0
class FbServer(object): """ This class is a server that controls the FbDriver. """ def __init__(self): """ Constructor """ self.server = SimpleServer() def init_driver(self, detector, feedback_pvs): """ This function initiates the driver. It creates process variables for the requested lidt of pv names. For each data type combination with the applicable quality check two pvs are created: one holding frame index, and one holding count of failed frames. It creates FbDriver instance and returns it to the calling function. Parameters ---------- detector : str a pv name of the detector feedback_pvs : list a list of feedback process variables names, for each data type combination with the applicable quality check Returns ------- driver : FbDriver FbDriver instance """ prefix = detector + ':' pvdb = {} counters = {} #add PV that follow index of failed farames and count of failed frames for each quality check for pv in feedback_pvs: pvdb[pv + '_res'] = { 'prec': 0, } pvdb[pv + '_ctr'] = { 'prec': 0, } counters[pv] = 0 self.server.createPV(prefix, pvdb) driver = FbDriver(counters=counters) return driver def activate_pv(self): """ Infinite loop processing the pvs defined in server; exits when parent process exits. """ while True: self.server.process(.1)
def run(self): server = SimpleServer() server.createPV("TU-", pvp.pvdb()) EpicsServer.driver = EpicsDriver() recordAction("[%s] Action: EPICS server and driver started" % getDateTime()) while True: server.process(0.1)
class SimCAServer(): '''Defines basic PV server that continuously syncs the input model to the input (command) EPICS PV values and publishes updated model data to output EPICS PVs. Assumes fast model execution, as the model executes in the main CAS server thread. CAS for the input and ouput PVs is handled by the SimDriver object''' def __init__(self, pv_file, model=None): self.serve_data = False inputs = parse_pv_file(pv_file) assert 'name' in inputs self.name = inputs['name'] assert 'input' in inputs, 'User supplied pv definitions must contain "input" pvs.' if (model is None): self.model = Model() else: self.model = model self.pvdb = {**inputs['input'], **inputs['output']} self.server = SimpleServer() self.server.createPV(self.name + ':', self.pvdb) self.driver = SimCADriver(inputs['input'], inputs['output']) def start(self): self.serve_data = True current_sim_input_pv_state = self.driver.get_input_pv_state() # Do initial simulation vprint("Initializing sim...", True) self.driver.set_output_pvs( self.model.run(current_sim_input_pv_state, verbose=True)) vprint("...done.", True) while self.serve_data: # process CA transactions self.server.process(0.1) while (current_sim_input_pv_state != self.driver.get_input_pv_state()): current_sim_input_pv_state = self.driver.get_input_pv_state() vprint('Running model and updating pvs...', True) t1 = time.time() self.driver.set_output_pvs( self.model.run(current_sim_input_pv_state, verbose=True)) t2 = time.time() dt = ((t2 - t1) * unit_registry('s')).to_compact() vprint('...done. Time ellapsed: {:.3E}'.format(dt), True) def stop(self): self.serve_data = False
class FbServer: """ This class is a server that controls the FbDriver. """ def __init__(self): """ Constructor """ self.server = SimpleServer() def init_driver(self, detector, feedback_pvs): """ This function initiates the driver. It creates process variables for the requested lidt of pv names. For each data type combination with the applicable quality check two pvs are created: one holding frame index, and one holding count of failed frames. It creates FbDriver instance and returns it to the calling function. Parameters ---------- detector : str a pv name of the detector feedback_pvs : list a list of feedback process variables names, for each data type combination with the applicable quality check Returns ------- driver : FbDriver FbDriver instance """ prefix = detector + ':' pvdb = {} counters = {} for pv in feedback_pvs: pvdb[pv+'_ind'] = { 'prec' : 0,} pvdb[pv+'_ctr'] = { 'prec' : 0, 'hihi' : 1, } counters[pv] = 0 self.server = SimpleServer() self.server.createPV(prefix, pvdb) driver = FbDriver(counters) return driver def activate_pv(self): """ Infinite loop processing the pvs defined in server; exits when parent process exits. """ while True: self.server.process(.1)
def run(driver_class, prefix=None, pvdb=None): prefix = driver_class.prefix if prefix is None else prefix pvdb = driver_class.pvdb if pvdb is None else pvdb server = SimpleServer() server.createPV(prefix, pvdb) driver = driver_class() # process CA transactions while True: server.process(0.1)
def run(): util.write_pid(pidfile) server = SimpleServer() server.createPV(prefix, pvdb) context = zmq.Context() driver = myDriver(context) # process CA transactions while forever: server.process(0.1)
def main(args): server = SimpleServer() server.createPV(args.prefix, pvdb) server_thread = ServerThread(server) driver = Model() def signal_handler(sig, frame): print("Shut down server") server_thread.stop() signal.signal(signal.SIGINT, signal_handler) server_thread.start()
class TestServer(object): """ Class to create temporary pvs to check in psp_plugin """ def __init__(self, pvbase, **pvdb): self.pvbase = pvbase self.pvdb = pvdb self.kill_server() def make_server(self): """ Create a new server and start it """ logger.debug('Create new server') self.server = SimpleServer() self.server.createPV(self.pvbase + ":", self.pvdb) self.driver = TestDriver() def kill_server(self): """ Remove the existing server (if it exists) and re-initialize """ logger.debug('Kill server') self.stop_server() self.server = None self.driver = None def start_server(self): """ Allow the current server to begin processing """ logger.debug('Restarting pcaspy server') if self.server is None: self.make_server() self.stop_server() self.server_thread = ServerThread(self.server) logger.debug('Pressing start') self.server_thread.start() def stop_server(self): """ Pause server processing """ logger.debug('Stop old server, if exists') try: self.server_thread.stop() except Exception: pass
def epics_ca_ioc(pv_input): if (isinstance(pv_input, str)): pvdefs = yaml.safe_load(open(pv_input)) elif (isinstance(pv_input, dict)): pvdefs = pv_input prefix = pvdefs['prefix'] pvdb = pvdefs['pv'] server = SimpleServer() server.createPV(prefix, pvdb) driver = ReadWriteDriver() while True: # process CA transactions server.process(0.1)
def main(prefix, pvdb, port): LOG.info('Starting ACQ ioc, abort with Ctrl-C') server = SimpleServer() server.createPV(_check_prefix(prefix), pvdb) driver = AcqDriver(_check_prefix(prefix), pvdb, port) myString = "pvdb = " + str(pvdb) #print myString LOG.debug('ACQ IOC is now started') try: # Run the driver process loop while driver.run: try: # process CA transactions server.process(0.1) except KeyboardInterrupt: LOG.info('ACQ IOC stopped by console interrupt!') driver.run = False finally: pass
def main(): parser = ArgumentParser(description='Shimadzu HPLC CBM20 IOC') parser.add_argument("ioc_prefix", type=str, help="Prefix of the IOC, include seperator.") parser.add_argument("pump_host", type=str, help="Pump host.") parser.add_argument("--polling_interval", default=1, type=float, help="Pump polling interval.") parser.add_argument( "--log_level", default="WARNING", choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'], help="Log level to use.") arguments = parser.parse_args() logging.basicConfig(stream=sys.stdout, level=arguments.log_level) _logger = logging.getLogger(arguments.ioc_prefix) _logger.info( "Starting ioc with prefix '%s', pump polling interval '%s' seconds, and pump_host '%s'.", arguments.ioc_prefix, arguments.polling_interval, arguments.pump_host) server = SimpleServer() server.createPV(prefix=arguments.ioc_prefix, pvdb=ioc.pvdb) communication_driver = ShimadzuCbm20(host=arguments.pump_host) driver = ioc.EpicsShimadzuPumpDriver( communication_driver=communication_driver, pump_polling_interval=arguments.polling_interval, hostname=arguments.pump_host) try: while True: server.process(0.1) except KeyboardInterrupt: _logger.info("User requested ioc termination. Exiting.")
def run_ioc(camera_type, ioc_name, prefix, platform, readout_grp, interface): LOG.info('%s camera server, abort with Ctrl-C', camera_type) ioc_prefix = "IOC:%s"%prefix pvdb = db.init(camera_type) if pvdb is None: LOG.error('Unsupported camera type: %s', camera_type) return 2 dtype = db.get_dtype(camera_type) os.environ['EPICS_CA_MAX_ARRAY_BYTES'] = str(db.get_max_array_size(camera_type)) server = SimpleServer() server.createPV(prefix, pvdb) server.createPV(ioc_prefix, IocAdmin.ioc_pvdb) driver = CameraDriver(pvdb, dtype, platform, readout_grp, interface, prefix, ioc_prefix, ioc_name) LOG.debug('%s camera server is now started', camera_type) try: while driver.run: try: # process CA transactions server.process(0.1) except KeyboardInterrupt: LOG.info('%s camera server stopped by console interrupt!', camera_type) driver.run = False finally: # process CA transactions server.process(0.1) server.process(0.1) # why 2? only psi knows... driver.shutdown() # do a final autosave driver.ioc.shutdown() # If we get here the server died in an unexpected way if driver.run: LOG.error('%s camera server exited unexpectedly!', camera_type) return 1 else: LOG.info('%s camera server exited normally', camera_type) return 0
def start_test_ioc(ioc_prefix, polling_interval): _logger.info( "Starting test IOC with prefix '%s' and polling_interval '%s'.", ioc_prefix, polling_interval) server = SimpleServer() server.createPV(prefix=ioc_prefix, pvdb=pvdb) _logger.info("Available PVs:\n%s", [ioc_prefix + pv for pv in pvdb.keys()]) communication_driver = MockShimadzuCbm20() driver = EpicsShimadzuPumpDriver(communication_driver=communication_driver, pump_polling_interval=polling_interval) try: while True: server.process(0.1) except KeyboardInterrupt: _logger.info("User terminated execution.")
def main(): pid = int(sys.argv[1]) prefix = sys.argv[2] print("pid = {0}".format(pid)) info = get_child_info(pid) db = create_db(info) server = SimpleServer() server.createPV(prefix, db) driver = RODriver() while True: next = time.time() + 0.25 server.process(0.25) while time.time() < next: time.sleep(0.01) info = get_child_info(pid) for thread_name in info: if thread_name in db: driver.setParam(thread_name, info[thread_name]) driver.updatePVs()
def _execute(prefix, host, platform, ioc_name=None, ioc_prefix=None): for descpv, valpv in pvlabels: pvdb[descpv] = {'type': 'string'} pvdb[valpv] = {'type': 'string'} for descpv, valpv in pvcontrols: pvdb[descpv] = {'type': 'string'} pvdb[valpv] = {'type': 'float', 'prec': 3} # If no IOC prefix is given just use the base prefix if ioc_prefix is None: ioc_prefix = prefix LOG.info('Starting DAQ server, abort with Ctrl-C') server = SimpleServer() server.createPV(prefix, pvdb) server.createPV(ioc_prefix, ioc_pvdb) driver = DaqDriver(host, platform, prefix, ioc_prefix, ioc_name) LOG.debug('DAQ server is now started') try: # Run the driver process loop while driver.run: try: # process CA transactions server.process(0.1) except KeyboardInterrupt: LOG.info('DAQ server stopped by console interrupt!') driver.run = False finally: # do a final autosave driver.ioc.shutdown() # If we get here the server died in an unexpected way if driver.run: LOG.error('DAQ server exited unexpectedly!') return 1 else: LOG.info('DAQ server exited normally') return 0
def to_subproc(): prefix = 'BSTEST:' pvdb = { 'VAL': { 'prec': 3, }, } class myDriver(Driver): def __init__(self): super(myDriver, self).__init__() if __name__ == '__main__': server = SimpleServer() server.createPV(prefix, pvdb) driver = myDriver() # process CA transactions while True: try: server.process(0.1) except KeyboardInterrupt: break
blocks_mon.initialise_block(b) else: pass time.sleep(1) def start_thread(self): """Starts the thread that monitors the block names for changes. """ t = threading.Thread(target=self._monitor_changes, args=(self,)) t.setDaemon(True) t.start() if __name__ == '__main__': my_prefix = os.environ["MYPVPREFIX"] print "Prefix is %s" % my_prefix SERVER = SimpleServer() SERVER.createPV(my_prefix, PVDB) DRIVER = BlocksMonitor(my_prefix) DRIVER.start_thread() # Process CA transactions while True: try: SERVER.process(0.1) except Exception as err: print_and_log(str(err), "MAJOR") break
# Main Thread if (__name__ == "__main__"): # PVs I/O PV_input = sys.argv[1] PV_output = sys.argv[2] # PV config PVs = { PV_output: { "type": "float", "prec": 3, "unit": "uSv", "low": -0.1, "high": 1.5, "lolo": -0.1, "hihi": 2 } } # Start Threads prl and CA CA_server = SimpleServer() CA_server.createPV("", PVs) driver = IntegralDriver(PV_input, PV_output) # Main loop while (True): CA_server.process(0.1)
else: for key in _pvs: if key != "GPS:Fix" and "GPS" in key: self.setParamStatus(key, Alarm.READ_ALARM, Severity.INVALID_ALARM) self.updatePVs() time.sleep(1) # Overrides superclass read () method to print which variable will be read def read(self, reason): print 'Reading "%s"' % reason return Driver.read(self, reason) # Main function. Instantiates a new server and a new driver. if __name__ == "__main__": CAserver = SimpleServer() CAserver.createPV(_prefix, _pvs) driver = NTPDriver() # Processes request each 100 ms while (True): CAserver.process(0.1)
GATEWAY_PREFIX = GATEWAY_PREFIX.replace('%MYPVPREFIX%', MACROS["$(MYPVPREFIX)"]) print_and_log("BLOCK GATEWAY PREFIX = %s" % GATEWAY_PREFIX) CONFIG_DIR = os.path.abspath(args.config_dir[0]) print_and_log("CONFIGURATION DIRECTORROOT_DIR %s" % CONFIG_DIR) SCHEMA_DIR = os.path.abspath(args.schema_dir[0]) print_and_log("SCHEMA DIRECTORY = %s" % SCHEMA_DIR) ARCHIVE_UPLOADER = args.archive_uploader[0].replace('%EPICS_KIT_ROOT%', MACROS["$(EPICS_KIT_ROOT)"]) print_and_log("ARCHIVE UPLOADER = %s" % ARCHIVE_UPLOADER) ARCHIVE_SETTINGS = args.archive_settings[0].replace('%EPICS_KIT_ROOT%', MACROS["$(EPICS_KIT_ROOT)"]) print_and_log("ARCHIVE SETTINGS = %s" % ARCHIVE_SETTINGS) PVLIST_FILE = args.pvlist_name[0] print_and_log("BLOCKSERVER PREFIX = %s" % BLOCKSERVER_PREFIX) SERVER = SimpleServer() SERVER.createPV(BLOCKSERVER_PREFIX, PVDB) DRIVER = BlockServer(SERVER) # Process CA transactions while True: try: SERVER.process(0.1) except Exception as err: print_and_log(err,"MAJOR") break
maxi = maxigauge(arguments.serial) maxi.loadSensors() _logger.info("I got %d sensors in the controller." % maxi._NumSensors) prefixs = [] pvsGauge = {} pvsRelay = {} for j in range(len(maxi.sensors)): prefixs.append("PG%d" % j) pvsGauge.update(ioc.pvsPG(prefixs[-1])) for j in range(len(maxi.relay)): prefixs.append("RL%d" % j) pvsRelay.update(ioc.pvsRELAY(prefixs[-1])) server = SimpleServer() server.createPV(prefix=arguments.ioc_prefix, pvdb=pvsGauge) server.createPV(prefix=arguments.ioc_prefix, pvdb=pvsRelay) driver = ioc.maxigauge_ioc(maxi, prefixs) server_thread = ServerThread(server) server_thread.start() if __name__ == "__main__": while not (input("Press 'q' to quit: ") == 'q'): pass _logger.info("User requested ioc termination. Exiting.") server_thread.stop() sys.exit()
if value == 1: self.setParam('CMD', 1) self.thread = thread.start_new_thread(self.run, ()) return True return False def run(self): print("Running...") self.updatePVs() time.sleep(4.0) self.setParam('RBV', self.getParam('RBV') + 1) self.setParam('CMD', 0) self.updatePVs() print("Done.") self.callbackPV('CMD') self.thread = None server = SimpleServer() server.createPV(prefix, pvdb) driver = MyDriver() print("Try camonitor Python:CMD Python:RBV") print("then caput -c -w 10 Python:CMD 1") while True: server.process(0.1)
self.updatePVs() self.eid.set() self.eid.clear() super(myDriver, self).write(reason, value) def runChargeIntegration(self): updateTime = .1 while True: run = self.getParam('SWITCH') if run: self.eid.wait(updateTime) else: self.eid.wait() run = self.getParam('SWITCH') if not run: continue current = self.getParam('2') charge = self.getParam('BEAMINT') self.setParam('BEAMINT', charge + current * updateTime) self.updatePVs() if __name__ == '__main__': server = SimpleServer() server.createPV(prefix_current, pvdb_current) server.createPV(prefix_integrated, pvdb_integrated) driver = myDriver() # process CA transactions while True: server.process(0.1)
class Frame_Thread(QThread): frame_signal = pyqtSignal(np.ndarray) distrs_signal = pyqtSignal(np.ndarray, np.ndarray) params_signal = pyqtSignal(np.ndarray, np.ndarray, np.ndarray, np.ndarray) def __init__(self): super(QThread, self).__init__() super(QThread, self).__init__() self.isRunning = False self.device_manager = gx.DeviceManager() self.camera = None self.exposure = None self.img_shape = [None, None] self.img_ranges = [None, None, None, None] self.calibr = [None, None] self.isProfile = False self.isCalcParams = False self.configfile = 'config.ini' self.config = configparser.ConfigParser() self.lastFrame = None self.exposure_changed = False self.pvs = {'prefix' : None, 'pos_x' : None, 'pos_y' : None} self.server = None self.drv = None self.server_thread = None self.isAvg = False self.avgFrames = 1 self.avgDelay = 0 def __del__(self): pass def camerasList(self): dev_num, dev_info_list = self.device_manager.update_device_list() return dev_info_list if dev_num > 0 else None def setCamera(self, index): self.camera = self.device_manager.open_device_by_index(index+1) self.exposure = self.camera.ExposureTime.get() self.img_shape = [self.camera.Width.get(), self.camera.Height.get()] self.camera.Gain.set(0) self.camera.TriggerMode.set(gx.GxSwitchEntry.OFF) def setExposure(self, value): self.exposure = value self.exposure_changed = True def setConfig(self): self.config.read(self.configfile) if len(self.config.sections()) > 0: frame = np.array(list(self.config['FRAME'].values()), dtype='int32') shape = [self.img_shape[0]-10, self.img_shape[0], \ self.img_shape[1]-10, self.img_shape[1]] self.img_ranges = np.maximum([0,10,0,10], np.minimum(frame, shape)) self.calibr[0] = float(self.config['CALIBR_cm_per_px']['x']) self.calibr[1] = float(self.config['CALIBR_cm_per_px']['y']) self.pvs = dict(self.config['PV_NAMES']) def saveConfig(self): self.config['FRAME'] = {'min_x' : str(self.img_ranges[0]), \ 'max_x' : str(self.img_ranges[1]), \ 'min_y' : str(self.img_ranges[2]), \ 'max_y' : str(self.img_ranges[3]) } with open(self.configfile, 'w') as configfile: self.config.write(configfile) def startEpics(self): self.server = SimpleServer() self.server.createPV(prefix=self.pvs['prefix'], \ pvdb={self.pvs['pos_x'] : {'prec' : 3}, }) self.server.createPV(prefix=self.pvs['prefix'], \ pvdb={self.pvs['pos_y'] : {'prec' : 3}, }) self.drv = myDriver() self.server_thread = ServerThread(self.server) self.server_thread.start() def stopEpics(self): if self.server_thread is not None: self.server_thread.stop() self.drv = None def run(self): self.isRunning = True self.camera.stream_on() #print(f'camera: {self.camera}') while self.isRunning: if self.exposure_changed == True: self.camera.ExposureTime.set(self.exposure) self.exposure_changed = False img = self.camera.data_stream[0].get_image() if img == None: continue self.lastFrame = img.get_numpy_array() self.frame_signal.emit(self.lastFrame) if self.isProfile or self.isCalcParams: proc = self.lastFrame[self.img_ranges[2]:self.img_ranges[3],\ self.img_ranges[0]:self.img_ranges[1]] x, y = np.sum(proc, axis=0), np.sum(proc, axis=1) if self.isProfile: self.distrs_signal.emit(x, y) if self.isCalcParams: optx = fit(x) opty = fit(y) self.params_signal.emit(x, y, optx, opty) if self.drv is not None: self.drv.update(self.pvs['pos_x'], 10*self.calibr[0]*optx[1]) self.drv.update(self.pvs['pos_y'], 10*self.calibr[1]*opty[1]) self.camera.stream_off() def stop(self): self.isRunning = False
'hihi' : 140, 'high' : 100, 'low' : -100, 'lolo' : -140, 'lolim' : -180, 'unit' : 'deg' }, 'STATUS': { 'type': 'enum', 'enums': ['Off', 'On'], 'states': [Severity.MINOR_ALARM, Severity.NO_ALARM], }, 'WAVE': { 'count': 16, 'prec': 2, 'value': numpy.arange(16, dtype=float) } } class myDriver(Driver): def __init__(self): super(myDriver, self).__init__() if __name__ == '__main__': server = SimpleServer() server.createPV(prefix, pvdb) driver = myDriver() print "Server is running... (ctrl+c to close)" while True: server.process(0.1)
class EpicsAdapter(Adapter): """ Inheriting from this class provides an EPICS-interface to a device, powered by the pcaspy-module. In the simplest case all that is required is to inherit from this class and override the `pvs`-member. It should be a dictionary that contains PV-names (without prefix) as keys and instances of PV as values. For a simple device with two properties, speed and position, the first of which should be read-only, it's enough to define the following: class SimpleDeviceEpicsAdapter(EpicsAdapter): pvs = { 'VELO': PV('speed', read_only=True), 'POS': PV('position', lolo=0, hihi=100) } For more complex behavior, the adapter could contain properties that do not exist in the device itself. If the device should also have a PV called STOP that "stops the device", the adapter could look like this: class SimpleDeviceEpicsAdapter(EpicsAdapter): pvs = { 'VELO': PV('speed', read_only=True), 'POS': PV('position', lolo=0, hihi=100), 'STOP': PV('stop', type='int'), } @property def stop(self): return 0 @stop.setter def stop(self, value): if value == 1: self._device.halt() Even though the device does _not_ have a property called 'stop' (but a method called 'halt'), issuing the command caput STOP 1 will achieve the desired behavior, because EpicsAdapter merges the properties of the device into SimpleDeviceEpicsAdapter itself, so that it is does not matter whether the specified property in PV exists in the device or the adapter. The intention of this design is to keep device classes small and free of protocol specific stuff, such as in the case above where stopping a device via EPICS might involve writing a value to a PV, whereas other protocols may offer an RPC-way of achieving the same thing. """ protocol = 'epics' pvs = None def __init__(self, device, arguments=None): super(EpicsAdapter, self).__init__(device, arguments) if arguments is not None: self._options = self._parseArguments(arguments) self._create_properties(self.pvs.values()) self._server = None self._driver = None def start_server(self): self._server = SimpleServer() self._server.createPV(prefix=self._options.prefix, pvdb={k: v.config for k, v in self.pvs.items()}) self._driver = PropertyExposingDriver(target=self, pv_dict=self.pvs) self._last_update = datetime.now() def _create_properties(self, pvs): for pv in pvs: prop = pv.property if not prop in dir(self): if not prop in dir(self._device): raise AttributeError('Can not find property \'' + prop + '\' in device or interface.') setattr(type(self), prop, ForwardProperty('_device', prop)) def _parseArguments(self, arguments): parser = ArgumentParser( description="Adapter to expose a device via EPICS") parser.add_argument('-p', '--prefix', help='Prefix to use for all PVs', default='') return parser.parse_args(arguments) def handle(self, cycle_delay=0.1): # pcaspy's process() is weird. Docs claim argument is "processing time" in seconds. # But this is not at all consistent with the calculated delta. # Having "watch caget" running has a huge effect too (runs faster when watching!) # Additionally, if you don't call it every ~0.05s or less, PVs stop working. Annoying. # Set it to 0.0 for maximum cycle speed. self._server.process(cycle_delay) self._driver.process_pv_updates(seconds_since(self._last_update)) self._last_update = datetime.now()
#import p4p from pcaspy import Driver, SimpleServer pvdb = { "pv1": { "prec": 3, "value": 1.0 }, } class myDriver(Driver): def __init__(self): super(myDriver, self).__init__() if __name__ == "__main__": server = SimpleServer() server.createPV("test:", pvdb) driver = myDriver() while True: server.process(0.1)
action="store", type="string", dest="speed", help="set Megamp serial port speed (e.g. 9600)") (options, args) = parser.parse_args() if (options.port): port = options.port else: if (os.environ.get("MA_PORT")): port = os.environ.get("MA_PORT") if (options.speed): speed = options.speed else: if (os.environ.get("MA_SPEED")): speed = os.environ.get("MA_SPEED") print("Megamp serial parameter: port = " + port + " speed = " + str(speed)) driver = iocDriver.myDriver(port, speed) server = SimpleServer() server.createPV(prefix, driver.getPVdb()) driver.start() # print(driver.getPVdb()) while True: server.process(1)
try: # Covert delta values into an absolute position us_des, ds_des, roll_des = delta_to_abs_pos( d_x, d_y, d_pitch, d_roll, d_yaw) print "us_rbk", US_RBK, "\nds_rbk", DS_RBK, "\nroll_rbk", ROLL_RBK print "us_des", us_des, "\nds_des", ds_des, "\nroll_des", roll_des print "us_diff", US_RBK - us_des, "\nds_diff", DS_RBK - ds_des, "\nroll_diff", ROLL_RBK - roll_des # Calculate a new cam position cam_rad = gird_pos_to_cam_angle(us_des, ds_des, roll_des) cam_deg = map(lambda value: value * 180 / np.pi, cam_rad) print "desired positions\nin radians:", cam_rad, "\nin degrees", cam_deg, "\n", CAM_ANGLE_DEG print np.floor(CAM_ANGLE_DEG * 100000) / 100000 - np.floor( cam_deg * 100000) / 100000, # Write the value to the motors and start the move set_cam_angles(cam_deg) except ValueError, e: print e self.setParam('GIRD_MOVE_ERR', 1) self.updatePVs() if __name__ == '__main__': server = SimpleServer() server.createPV(PV_PREFIX, PY_DB) driver = UndGirdXYMovDriver() # process CA transactions while True: server.process(0.1)
class SyncedSimPVServer(): '''Defines basic PV server that continuously syncs the input model to the input (command) EPICS PV values and publishes updated model data to output EPICS PVs. Assumes fast model execution, as the model executes in the main CAS server thread. CAS for the input and ouput PVs is handled by the SimDriver object''' def __init__(self, name, input_pvdb, output_pvdb, noise_params, model, sim_params=None): self.name = name self.pvdb = {} self.input_pv_state = {} self.output_pv_state = {} self.model = model for pv in input_pvdb: #print(pv) self.pvdb[pv] = input_pvdb[pv] self.input_pv_state[pv] = input_pvdb[pv]["value"] output_pv_state = {} for pv in output_pvdb: self.pvdb[pv] = output_pvdb[pv] output_pv_state[pv] = output_pvdb[pv]["value"] for pv in output_pvdb: if (pv in noise_params): self.pvdb[pv + ':sigma'] = { 'type': 'float', 'value': noise_params[pv]['sigma'] } self.pvdb[pv + ':dist'] = { 'type': 'char', 'count': 100, 'value': noise_params[pv]['dist'] } prefix = self.name + ":" self.server = SimpleServer() self.server.createPV(prefix, self.pvdb) self.driver = SimDriver(self.input_pv_state, output_pv_state, noise_params) self.serve_data = False self.sim_params = sim_params def set_sim_params(**params): self.sim_params = params def start_server(self): self.serve_data = True sim_pv_state = copy.deepcopy(self.input_pv_state) # Do initial simulation print("Initializing sim...") output_pv_state = self.model.run(self.input_pv_state, verbose=True) self.driver.set_output_pvs(output_pv_state) print("...done.") while self.serve_data: # process CA transactions self.server.process(0.1) while (sim_pv_state != self.input_pv_state): sim_pv_state = copy.deepcopy(self.input_pv_state) output_pv_state = self.model.run(self.input_pv_state, verbose=True) self.driver.set_output_pvs(output_pv_state) def stop_server(self): self.serve_data = False
# Multimetro realiza 10 ciclos de integracao para cada leitura. # Logo, cada leitura toma um tempo maior em relacao ao caso passado self.scan_delay = 1 self.sendSerialCommand(":SYST:RWL; *CLS; :CONF:VOLT:DC 10,0.00001\x0D\x0A", 0.300) elif item[1] == 100: # 100 ciclos de integracao por leitura, equivalendo ao caso mais lento self.scan_delay = 10 self.sendSerialCommand(":SYST:RWL; *CLS; :CONF:VOLT:DC 10, MIN\x0D\x0A", 0.300) self.updatePVs() # Envia um comando a interface serial e espera delay segundos. def sendSerialCommand (self, command, delay): self.serial.write(command) time.sleep(delay) if __name__ == '__main__': CAserver = SimpleServer() CAserver.createPV("Cnt:Measure:", PVs) driver = PROSAC2HP232() while (True): CAserver.process(0.1)
f.close() if __name__ == '__main__': import sys import argparse parser = argparse.ArgumentParser(description='Hamamatsu MCD Control') parser.add_argument('--prefix', default='iMott:', help='EPICS PVs prefix') parser.add_argument('--gui', action='store_true', default=False, help='start QtQuick GUI') args = parser.parse_args() server = SimpleServer() server.createPV(args.prefix, pvdb) driver = HamamatsuMCDriver() if args.gui: server_thread = ServerThread(server) server_thread.start() from PyQt5 import QtCore, QtGui, QtQuick app = QtGui.QGuiApplication(sys.argv) view = QtQuick.QQuickView() view.setResizeMode(QtQuick.QQuickView.SizeRootObjectToView) view.setSource(QtCore.QUrl.fromLocalFile('mcd.qml')) view.setTitle('Hamamatsu C7557-1 Control') view.show() app.lastWindowClosed.connect(server_thread.stop)
pvdb[prefix + ':PD'] = {'type': 'int', 'value': 0} pvdb[prefix + ':DPDPS'] = {'type': 'float', 'value': 0} pvdb[prefix + ':DPDPSA'] = {'type': 'float', 'value': 0} pvdb[prefix + ':DPD'] = {'type': 'int', 'value': 0} pvdb[prefix + ':TXD'] = {'type': 'int', 'value': 0} pvdb[prefix + ':DTXDPS'] = {'type': 'float', 'value': 0} pvdb[prefix + ':DTXD'] = {'type': 'int', 'value': 0} prefix = ':CH%u:SCAN' % (i) pvdb[prefix + ':STAGE'] = {'type': 'int', 'value': 0} pvdb[prefix + ':TXD'] = {'type': 'int', 'value': 0} pvdb[prefix + ':PD'] = {'type': 'int', 'value': 0} pvdb[prefix + ':TXDPS'] = {'type': 'float', 'value': 0} pvdb[prefix + ':PDPS'] = {'type': 'float', 'value': 0} pvdb[prefix + ':CLK'] = {'type': 'int', 'value': 0} pvdb[prefix + ':DCLK'] = {'type': 'int', 'value': 0} printDb(args.P) server = SimpleServer() server.createPV(args.P, pvdb) driver = myDriver() try: # process CA transactions while True: server.process(0.1) except KeyboardInterrupt: print '\nInterrupted'
return value def write(self, reason, value): lolim = pvdb[reason].get('lolim') if lolim is not None and value < lolim: return False hilim = pvdb[reason].get('hilim') if hilim is not None and value > hilim: return False self.setParam(reason, value) return True if __name__ == '__main__': import os os.environ['EPICS_CAS_INTF_ADDR_LIST'] = 'localhost' ioc_server = SimpleServer() ioc_server.createPV(prefix, pvdb) driver = TestDriver() print('Please note: you will need to set EPICS_CA_ADDR_LIST=localhost ' 'to access PVs served by this IOC.') while True: ioc_server.process(.1)