Пример #1
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
Пример #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
 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()
Пример #5
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)
Пример #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
    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)
Пример #8
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)
Пример #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 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()
Пример #11
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()
Пример #12
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
Пример #13
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)
Пример #14
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
Пример #15
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
Пример #16
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.")
Пример #17
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 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()
Пример #19
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.")
Пример #20
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
Пример #21
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
Пример #22
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
Пример #23
0
def main():
    parser = ArgumentParser()
    parser.add_argument("--ioc_prefix",
                        type=str,
                        help="Global prefix of the IOC.")

    parser.add_argument("--pump_prefix",
                        type=str,
                        help="Prefix for pump shutter.")
    parser.add_argument("--pump_port", type=int, help="GPIO port of pump.")

    parser.add_argument("--probe_prefix",
                        type=str,
                        help="Prefix for probe shutter.")
    parser.add_argument("--probe_port", type=int, help="GPIO port of probe.")

    parser.add_argument("--valve_prefix",
                        type=str,
                        help="Prefix for pulse valve.")
    parser.add_argument("--valve_port",
                        type=str,
                        help="Serial port of pulse valve.")

    parser.add_argument("--notebook_prefix",
                        type=str,
                        help="Prefix for Notebook.")
    parser.add_argument("--log_level",
                        type=str,
                        help="Logging level for the iocs")

    arguments = parser.parse_args()

    logging.basicConfig(stream=sys.stdout, level=arguments.log_level)
    _logger = logging.getLogger(arguments.ioc_prefix[:-1])

    pvdb = {}
    pvdb.update(ioc_notebook.make_pvs(arguments.notebook_prefix))
    pvdb.update(ioc_RaspiGPIO.make_pvs(arguments.pump_prefix))
    pvdb.update(ioc_RaspiGPIO.make_pvs(arguments.probe_prefix))
    pvdb.update(ioc_AttoTech.make_pvs(arguments.valve_prefix))

    _logger.info("Starting ioc with prefix '%s'.", arguments.ioc_prefix)
    server = SimpleServer()
    server.createPV(prefix=arguments.ioc_prefix, pvdb=pvdb)

    #Setting devices drivers
    PumpShutter_driver = RaspiShutter(arguments.pump_port)
    if not (PumpShutter_driver.ready):
        _logger.ERROR("Error connecting to Pump shutter")
    HHGShutter_driver = RaspiShutter(arguments.probe_port)
    if not (HHGShutter_driver.ready):
        _logger.ERROR("Error connecting to ProbeShutter")
    valve_driver = AttoValve(arguments.valve_port)
    if not (valve_driver.ready):
        _logger.ERROR("Error connecting to AttoValve")

    driver = ioc.ioc_raspi1()

    valve_ioc = ioc_AttoTech.EpicsAttoTechDriver(valve_driver, driver,
                                                 arguments.valve_prefix)
    pumpshutter_ioc = ioc_RaspiGPIO.EpicsRaspiShutterDriver(
        PumpShutter_driver, driver, arguments.pump_prefix)
    hhgshutter_ioc = ioc_RaspiGPIO.EpicsRaspiShutterDriver(
        HHGShutter_driver, driver, arguments.probe_prefix)
    notebook_ioc = ioc_notebook.NoteBookIoc(driver, arguments.notebook_prefix)

    driver.add_ioc(valve_ioc)
    driver.add_ioc(pumpshutter_ioc)
    driver.add_ioc(hhgshutter_ioc)
    driver.add_ioc(notebook_ioc)

    server_thread = ServerThread(server)
    server_thread.start()
    while not (raw_input("Press 'q' to quit: ") == "q"):
        pass
    server_thread.stop()
    _logger.info("User requested ioc termination. Exiting.")
    PumpShutter_driver.close()
    HHGShutter_driver.close()
    valve_driver.close()
Пример #24
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)

Пример #25
0
            range_sensors_txtRack1 = [1, 8]
            range_sensors_txtRack2 = [9, 15]
            range_sensors_txtRack3 = [16, 20]
            leitura = np.append(leitura, get_file(1, range_sensors_txtRack1))
            leitura = np.append(leitura, get_file(2, range_sensors_txtRack2))
            leitura = np.append(leitura, get_file(3, range_sensors_txtRack3))

            for i in range(int(len(leitura) / 4)):
                paramD = "POT" + str(i + 1) + "_LEVEL"
                paramT = "POT" + str(i + 1) + "_TEMP"
                paramX = "POT" + str(i + 1) + "_POSX"
                paramY = "POT" + str(i + 1) + "_POSY"
                self.setParam(paramD, leitura[4 * i])
                self.setParam(paramT, leitura[4 * i + 1])
                self.setParam(paramX, leitura[4 * i + 2])
                self.setParam(paramY, leitura[4 * i + 3])
            self.updatePVs()
            time.sleep(0.5)


if __name__ == '__main__':
    server = SimpleServer()  # initializes the server parameters
    server.createPV(prefix, pvdb)  # creates the necessary PVs
    driver = myDriver(
    )  # calls the thread class that will handle data acquisition and communication
    httpclient = httplib2.HTTPConnectionWithTimeout("10.2.105.191:17665")
    req = httpclient.request("GET", "/mgmt/bpl/archivePV?pv=HLS:POSICAO1")
    # process CA transactions
    while True:
        server.process(0.1)
Пример #26
0
    def __init__(self):
        """
        Constructor

        """
        self.server = SimpleServer()
Пример #27
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