Exemplo n.º 1
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")
Exemplo n.º 2
0
 def start_server(self):
     """
     Allow the current server to begin processing
     """
     if self.server is None:
         self.make_server()
     self.stop_server()
     self.server_thread = ServerThread(self.server)
     self.server_thread.start()
Exemplo n.º 3
0
 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()
Exemplo n.º 4
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()
Exemplo n.º 5
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()
Exemplo n.º 6
0
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
Exemplo n.º 7
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()
Exemplo n.º 8
0
class PVManager(object):
    def __init__(self, prefix):
        self.prefix = prefix
        self.thread = None

        self.server = CAServer()
        self.driver = None

    @property
    def pvs(self):
        return self.server.pvs

    def remove_pv(self, pvname):
        return self.server._remove_pv(pvname)

    def add_pv(self, pvname, write_callback=None, **kwargs):
        kwargs['port'] = CADriver.port

        pv = self.server._create_pv(self.prefix, pvname, kwargs)
        if self.driver is None:
            self.driver = CADriver(self, self.server.pvs)
        else:
            self.driver.check_pvs()

        if write_callback is not None:
            assert(hasattr(write_callback, '__call__'))
            pv._write_callbacks.add(write_callback)

        pv.driver = self.driver
        return pv

    def run(self):
        if self.thread is None or not self.thread.is_alive():
            self.thread = ServerThread(self.server)
            self.thread.setDaemon(True)
            self.thread.start()

    def stop(self, join=True):
        if self.thread is not None:
            self.thread.stop()
            if join:
                self.thread.join()

            print('CAS thread finished')
Exemplo n.º 9
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
Exemplo n.º 10
0
maxi = maxigauge(arguments.serial)
maxi.loadSensors()
_logger.info("I got %d sensors in the controller." % maxi._NumSensors)

prefixs = []
pvsGauge = {}
pvsRelay = {}

for j in range(len(maxi.sensors)):
    prefixs.append("PG%d" % j)
    pvsGauge.update(ioc.pvsPG(prefixs[-1]))

for j in range(len(maxi.relay)):
    prefixs.append("RL%d" % j)
    pvsRelay.update(ioc.pvsRELAY(prefixs[-1]))

server = SimpleServer()
server.createPV(prefix=arguments.ioc_prefix, pvdb=pvsGauge)
server.createPV(prefix=arguments.ioc_prefix, pvdb=pvsRelay)

driver = ioc.maxigauge_ioc(maxi, prefixs)
server_thread = ServerThread(server)
server_thread.start()

if __name__ == "__main__":
    while not (input("Press 'q' to quit: ") == 'q'):
        pass
    _logger.info("User requested ioc termination. Exiting.")
    server_thread.stop()
    sys.exit()
Exemplo n.º 11
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()
Exemplo n.º 12
0
        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_()
Exemplo n.º 13
0
class CAServer(multiprocessing.Process):
    """
    Process-based implementation of Channel Access server.

    Attributes:
        ca_server (SimpleServer): pcaspy SimpleServer instance

        ca_driver (Driver): pcaspy Driver instance

        server_thread (ServerThread): Thread for running the server

        exit_event (multiprocessing.Event): Event indicating shutdown

    """

    protocol = "ca"

    def __init__(
        self,
        prefix: str,
        input_variables: Dict[str, InputVariable],
        output_variables: Dict[str, OutputVariable],
        in_queue: multiprocessing.Queue,
        out_queue: multiprocessing.Queue,
        running_indicator: multiprocessing.Value,
        *args,
        **kwargs,
    ) -> None:
        """Initialize server process.

        Args:
            prefix (str): EPICS prefix for serving process variables

            input_variables (Dict[str, InputVariable]): Dictionary mapping pvname to lume-model input variable.

            output_variables (Dict[str, OutputVariable]):Dictionary mapping pvname to lume-model output variable.

            in_queue (multiprocessing.Queue): Queue for tracking updates to input variables

            out_queue (multiprocessing.Queue): Queue for tracking updates to output variables

        """
        super().__init__(*args, **kwargs)
        self.ca_server = None
        self.ca_driver = None
        self.server_thread = None
        self.exit_event = multiprocessing.Event()
        self._prefix = prefix
        self._input_variables = input_variables
        self._output_variables = output_variables
        self._in_queue = in_queue
        self._out_queue = out_queue
        self._providers = {}
        self._running_indicator = running_indicator

        # cached pv values
        self._cached_values = {}

    def update_pv(self, pvname, value) -> None:
        """Adds update to input process variable to the input queue.

        Args:
            pvname (str): Name of process variable

            value (Union[np.ndarray, float]): Value to set

        """
        val = value
        pvname = pvname.replace(f"{self._prefix}:", "")

        self._cached_values.update({pvname: val})

        # only update if not running
        if not self._running_indicator.value:
            self._in_queue.put({
                "protocol": self.protocol,
                "pvs": self._cached_values
            })
            self._cached_values = {}

    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")

    def update_pvs(
        self,
        input_variables: List[InputVariable],
        output_variables: List[OutputVariable],
    ):
        """Update process variables over Channel Access.

        Args:
            input_variables (List[InputVariable]): List of lume-epics output variables.

            output_variables (List[OutputVariable]): List of lume-model output variables.

        """
        variables = input_variables + output_variables
        self.ca_driver.update_pvs(variables)

    def run(self) -> None:
        """Start server process.

        """
        self.setup_server()
        while not self.exit_event.is_set():
            try:
                data = self._out_queue.get_nowait()
                inputs = data.get("input_variables", [])
                outputs = data.get("output_variables", [])
                self.update_pvs(inputs, outputs)
            except Empty:
                time.sleep(0.01)
                logger.debug("out queue empty")

        self.server_thread.stop()
        #        self.server_thread.join()
        logger.info("Channel access server stopped.")

    def shutdown(self):
        """Safely shutdown the server process.

        """
        self.exit_event.set()
Exemplo n.º 14
0
 def run(self):
     if self.thread is None or not self.thread.is_alive():
         self.thread = ServerThread(self.server)
         self.thread.setDaemon(True)
         self.thread.start()