예제 #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 setup_server(self) -> None:
        """Configure and start server.

        """
        # ignore interrupt in subprocess
        signal.signal(signal.SIGINT, signal.SIG_IGN)

        logger.info("Initializing CA server")

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

        # create all process variables using the process variables stored in
        # pvdb with the given prefix
        pvdb, self._child_to_parent_map = build_pvdb(self._input_variables,
                                                     self._output_variables)

        self.ca_server.createPV(self._prefix + ":", pvdb)

        # set up driver for handing read and write requests to process variables
        self.ca_driver = CADriver(server=self)

        # start the server thread
        self.server_thread = ServerThread(self.ca_server)
        self.server_thread.start()

        logger.info("CA server started")
예제 #3
0
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()
예제 #4
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)
예제 #5
0
파일: conftest.py 프로젝트: slaclab/pyca
 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()
예제 #6
0
    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()
예제 #7
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
예제 #8
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)
예제 #9
0
    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)
예제 #10
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)
예제 #11
0
    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()
예제 #12
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
예제 #13
0
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()
예제 #14
0
파일: conftest.py 프로젝트: slaclab/pyca
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
예제 #15
0
    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
예제 #16
0
파일: dynamic_pv.py 프로젝트: gitcyc/pcaspy
 def pvAttach(self, context, fullname):
     if fullname.startswith('MTEST:SPECTRUM'):
         if fullname not in spvs:
             pv = SpectrumPV(fullname)
             spvs[fullname] = pv
         return spvs[fullname]
     else:
         return SimpleServer.pvAttach(self, context, fullname)
예제 #17
0
 def pvAttach(self, context, fullname):
     if fullname.startswith('MTEST:SPECTRUM'):
         if fullname not in spvs:
             pv = SpectrumPV(fullname)
             spvs[fullname] = pv
         return spvs[fullname]
     else:
         return SimpleServer.pvAttach(self, context, fullname)
 def pvAttach(self, context, fullname):
     """A method that overrides the SimpleServer pvAttach method. It is called by channel access to attach a monitor
     to the specified PV. The method first checks against the dictionary at this server and then checks against the
     parent SimpleServer.
     """
     pv = self._strip_prefix(fullname)
     if pv is not None and pv in self._pvs:
         return self._pvs[pv]
     else:
         return SimpleServer.pvAttach(self, context, fullname)
예제 #19
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
예제 #20
0
    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 pvExistTest(self, context, addr, fullname):
     """A method that overrides the SimpleServer pvExistTest method. It is called by channel access to check if a PV
     exists at this server. The method first checks against the dictionary at this server and then checks against the
     parent SimpleServer.
     """
     try:
         pv = self._strip_prefix(fullname)
         if pv is not None and pv in self._pvs:
             return cas.pverExistsHere
         else:
             return SimpleServer.pvExistTest(self, context, addr, fullname)
     except:
         return cas.pverDoesNotExistHere
예제 #22
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)
예제 #23
0
    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
예제 #24
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)
예제 #25
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)
예제 #26
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
예제 #27
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)
예제 #28
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
예제 #29
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.")
예제 #30
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()
예제 #32
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
예제 #33
0
    def __init__(self):
        """
        Constructor

        """
        self.server = SimpleServer()
예제 #34
0
                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)
예제 #35
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)
예제 #36
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)
예제 #37
0
파일: dynamic_pv.py 프로젝트: gitcyc/pcaspy
 def __init__(self):
     SimpleServer.__init__(self)
예제 #38
0
#!/usr/bin/env python

from pcaspy import Driver, SimpleServer

prefix = 'MTEST:'
pvdb = {
    'LEVEL': {
    },
    'FILL' : {
        'prec' : 3,
        'asg'  : 'fill',
    },
}

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

if __name__ == '__main__':
    server = SimpleServer()
    server.initAccessSecurityFile('test.as', P=prefix)
    server.createPV(prefix, pvdb)
    driver = myDriver()
    # process CA transactions
    while True:
        server.process(0.1)
예제 #39
0
파일: qtgui.py 프로젝트: gitcyc/pcaspy
        super(Display, self).__init__()
        layout = QtGui.QHBoxLayout()
        layout.addWidget(QtGui.QLabel('Value:'))
        input = QtGui.QDoubleSpinBox()
        layout.addWidget(input)
        self.setLayout(layout)
        self.connect(input, QtCore.SIGNAL('valueChanged(double)'), self.newValue)
        self.drv = myDriver()

    def newValue(self, value):
        self.drv.write('RAND', value)
        self.drv.updatePVs()

if __name__ == '__main__':
    # create pcas server
    server = SimpleServer()
    server.createPV(prefix, pvdb)
    
    # create qt gui
    app = QtGui.QApplication(sys.argv)
    win = Display()
    win.show()
    
    # create pcas server thread and shut down when app exits
    server_thread = ServerThread(server)
    QtCore.QObject.connect(app, QtCore.SIGNAL('lastWindowClosed()'), server_thread.stop)

    # start pcas and gui event loop
    server_thread.start()
    app.exec_()
    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

예제 #41
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)

예제 #42
0
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
예제 #43
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)
예제 #44
0
                
            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)
                    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
예제 #46
0
파일: dynamic_pv.py 프로젝트: gitcyc/pcaspy
 def pvExistTest(self, context, addr, fullname):
     if fullname.startswith('MTEST:SPECTRUM'):
         return cas.pverExistsHere
     else:
         return SimpleServer.pvExistTest(self, context, addr, fullname)