Пример #1
0
    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
Пример #2
0
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
Пример #3
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)
Пример #4
0
 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)
Пример #5
0
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
Пример #6
0
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)
Пример #7
0
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)
Пример #8
0
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)
Пример #9
0
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)
Пример #10
0
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)
Пример #11
0
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
Пример #12
0
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.")
Пример #13
0
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 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()
Пример #15
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.")
Пример #16
0
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
Пример #17
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
            #print('==================================================\n')

            if len(else_gammaBuffer) > sample:
                else_gammaBuffer = else_gammaBuffer[1:]
            if len(else_neutronBuffer) > sample:
                else_neutronBuffer = else_neutronBuffer[1:]
            if len(else_dataBuffer) > sample:
                else_dataBuffer = else_dataBuffer[1:]
            if len(thermo_gammaBuffer) > sample:
                thermo_gammaBuffer = thermo_gammaBuffer[1:]
            if len(thermo_neutronBuffer) > sample:
                thermo_neutronBuffer = thermo_neutronBuffer[1:]
            if len(thermo_dataBuffer) > sample:
                thermo_dataBuffer = thermo_dataBuffer[1:]
            if len(berthold_gammaBuffer) > sample:
                berthold_gammaBuffer = berthold_gammaBuffer[1:]
            if len(berthold_neutronBuffer) > sample:
                berthold_neutronBuffer = berthold_neutronBuffer[1:]
            if len(berthold_dataBuffer) > sample:
                berthold_dataBuffer = berthold_dataBuffer[1:]
            if len(timeBuffer) > sample:
                timeBuffer = timeBuffer[1:]
            if len(deltatimeBuffer) > sample:
                deltatimeBuffer = deltatimeBuffer[1:]

            CAserver.process(0.1)

        except Exception as e:
            print(e)
            pass
Пример #19
0
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
                    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
Пример #21
0
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()
Пример #22
0
        nr_inits)
    pnr_mode = BeamlineMode("pnr", PARAMS_FIELDS.keys(), pnr_inits)
    disabled_mode = BeamlineMode("disabled", [])

    modes = [nr_mode, pnr_mode, disabled_mode]

    # init beamline
    bl = Beamline(comps, params, [], modes)
    bl.set_incoming_beam(beam_start)
    bl.active_mode = nr_mode
    return bl, modes


beamline, modes = create_beamline()

pv_db = PVManager(PARAMS_FIELDS, [mode.name for mode in modes])
SERVER = SimpleServer()
print("Prefix: {}".format(REFLECTOMETRY_PREFIX))
for pv_name in pv_db.PVDB.keys():
    print("creating pv: {}".format(pv_name))
SERVER.createPV(REFLECTOMETRY_PREFIX, pv_db.PVDB)
DRIVER = ReflectometryDriver(SERVER, beamline, pv_db)

# Process CA transactions
while True:
    try:
        SERVER.process(0.1)
    except Exception as err:
        print(err)
        break
Пример #23
0
                  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)
Пример #24
0
    'LEBT_PS:SOL_01:IMon': {},
    'ADS:G2:MC': {},
    'ADS:G3:MC': {},
    'LEBT_PS:DCH_01:IMon': {},
    'LEBT_PS:DCH_02:IMon': {},
    'LEBT_PS:DCV_01:IMon': {},
    'LEBT_PS:DCV_02:IMon': {}
}



class myDriver(Driver):
    def __init__(self):
        Driver.__init__(self)

    def write(self, reason, value):
        status = True
        # take proper actions
        self.setParam(reason, value)
        return status

if __name__ == '__main__':
    server = SimpleServer()
    server.createPV(prefix, pvdb)

    driver = myDriver()

    while True:
        # process CA transactions
        server.process(0.01)
        'value': [1.2, 5.6, 7.1]
    },
    'PUT_STRING_WAVEFORM': {
        'type': 'string',
        'count': 5,
        'value': ['You', 'got', 'a', 'fast', 'car']
    }
}


class testDriver(Driver):
    def __init__(self):
        super(testDriver, self).__init__()

    def read(self, reason):
        if reason is 'COUNTER':
            value = self.getParam(reason) + 1
            self.setParam(reason, value)
        else:
            value = self.getParam(reason)
        return value


server = SimpleServer()
server.createPV(prefix, pvdb)

driver = testDriver()

while True:
    server.process(.1)
Пример #26
0
                    # 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)
Пример #27
0
# 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)
Пример #28
0
        'type': 'float',
        'count': 3,
        'value': [1.2, 5.6, 7.1]
    },
    'PUT_STRING_WAVEFORM' : {
        'type': 'string',
        'count': 5,
        'value': ['You', 'got', 'a', 'fast', 'car']
    }
}

class testDriver(Driver):
    def __init__(self):
        super(testDriver, self).__init__()
    def read(self, reason):
        if reason is 'COUNTER':
            value = self.getParam(reason) + 1
            self.setParam(reason, value)
        else:
            value = self.getParam(reason)
        return value

server = SimpleServer()
server.createPV(prefix, pvdb)

driver = testDriver()

while True:
    server.process(.1)

Пример #29
0
class CAServer:
    """
    Server object for channel access process variables that updates and reads process \\
    values in a single thread.

    Attributes
    ----------
    model: online_model.model.surrogate_model.OnlineSurrogateModel
        OnlineSurrogateModel instance used for getting predictions

    pvdb: dict
        Dictionary that maps the process variable string to type (str), prec \\
        (precision), value (float), units (str), range (List[float])

    input_pv_state: dict
        Dictionary that maps the input process variables to their current values

    output_pv_state:
        Dictionary that maps the output process variables to their current values

    server: pcaspy.driver.SimpleServer
        Server class that interfaces between the channel access client and the driver. \\
        Forwards the read/write requests to the driver

    driver: online_model.server.ca.SimDriver
        Class that reacts to process variable read/write requests

    """

    def __init__(
        self,
        model_class,
        model_kwargs: dict,
        input_pvdb: Dict[str, dict],
        output_pvdb: Dict[str, dict],
        prefix: str,
    ) -> None:
        """
        Create OnlineSurrogateModel instance and initialize output variables by running \\
        with the input process variable state, set up the proces variable database and \\
        input/output variable tracking, start the server, create the process variables, \\
        and start the driver.

        Parameters
        ----------
        model_class
            Model class to be instantiated

        model_kwargs: dict
            kwargs for initialization

        in_pvdb: dict
            Dictionary that maps the input process variable string to type (str), prec \\
             (precision), value (float), units (str), range (List[float])

        out_pvdb: dict
            Dictionary that maps the output process variable string to type (str), prec \\
            (precision), value (float), units (str), range (List[float])

        """
        surrogate_model = model_class(**model_kwargs)
        self.model = OnlineSurrogateModel([surrogate_model])

        # set up db for initializing process variables
        self.pvdb = {}

        # set up input process variables
        self.pvdb.update(input_pvdb)
        self.input_pv_state = {pv: input_pvdb[pv]["value"] for pv in input_pvdb}

        # get starting output from the model and set up output process variables
        self.output_pv_state = self.model.run(self.input_pv_state)
        self.pvdb.update(output_pvdb)

        # initialize channel access server
        self.server = SimpleServer()

        # create all process variables using the process variables stored in self.pvdb
        # with the given prefix
        self.server.createPV(prefix + ":", self.pvdb)

        # set up driver for handing read and write requests to process variables
        self.driver = SimDriver(self.input_pv_state, self.output_pv_state)

    def start_server(self) -> None:
        """
        Start the channel access server and continually update.
        """
        sim_pv_state = copy.deepcopy(self.input_pv_state)

        # Initialize output variables
        print("Initializing sim...")
        output_pv_state = self.model.run(self.input_pv_state)
        self.driver.set_output_pvs(output_pv_state)
        print("...finished initializing.")

        while True:
            # process channel access transactions
            self.server.process(0.1)

            # check if the input process variable state has been updated as
            # an indicator of new input values
            while not all(
                np.array_equal(sim_pv_state[key], self.input_pv_state[key])
                for key in self.input_pv_state
            ):

                sim_pv_state = copy.deepcopy(self.input_pv_state)
                model_output = self.model.run(self.input_pv_state)
                self.driver.set_output_pvs(model_output)
Пример #30
0
		'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)
Пример #31
0
        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)
Пример #32
0
            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)

Пример #33
0
        if reason == 'VAL':                      #if EPICS input VAL
           print ('new speed is'); print (speedval)        #print to Arduino current speed
           x = str((speedval+0.2)*60)                #calculation for rps with offset
           ser.write (x)                        #send value for speed to Arduino

        if status:
           self.setParam(reason, speedval)

        return status

    def read(self, reason):
        if reason == 'RBV':                        #if EPICS input RBV (in progress)
            ser.write("speed")
            time.sleep(0.01)
            value=float(ser.readline())
            self.setParam(reason, value)
            print ('speed is '); print (value)
        else:
            value = self.getParam(reason)
        return value


if __name__ == '__main__':                    #create PVs based on prefix and pvdb definition
    server = SimpleServer()
    server.createPV(prefix, pvdb)
    driver = myDriver()

    while True:
        server.process(0.1)                    # process CA transactions