Exemple #1
0
def bench_threading_get_speed(pvname,
                              *,
                              initial_value=None,
                              log_level='ERROR'):
    from caproto.threading.client import (PV, SharedBroadcaster, Context as
                                          ThreadingContext)

    shared_broadcaster = SharedBroadcaster()
    context = ThreadingContext(broadcaster=shared_broadcaster,
                               log_level=log_level)

    def threading():
        value = pv.get(use_monitor=False)
        if initial_value is not None:
            assert len(value) == len(initial_value)

    pv = PV(pvname, auto_monitor=False, context=context)
    if initial_value is not None:
        pv.put(initial_value, wait=True)
    yield threading
    logger.debug('Disconnecting threading pv %s', pv)
    pv.disconnect()
    logger.debug('Disconnecting shared broadcaster %s', shared_broadcaster)
    shared_broadcaster.disconnect()
    logger.debug('Done')
Exemple #2
0
def shared_broadcaster(request):
    sb = SharedBroadcaster()
    yield sb
    sb.disconnect()
    assert not sb._command_thread.is_alive()
    assert not sb.selector.thread.is_alive()
    assert not sb._retry_unanswered_searches_thread.is_alive()
Exemple #3
0
def bench_threading_many_connections(pv_names,
                                     *,
                                     initial_value=None,
                                     log_level='DEBUG'):
    from caproto.threading.client import (PV, SharedBroadcaster, Context as
                                          ThreadingContext)

    shared_broadcaster = SharedBroadcaster()
    context = ThreadingContext(broadcaster=shared_broadcaster,
                               log_level=log_level)

    pvs = []

    def threading():
        nonlocal pvs

        pvs = [
            PV(pvname, auto_monitor=False, context=context)
            for pvname in pv_names
        ]

        while not all(pv.connected for pv in pvs):
            time.sleep(0.01)

    try:
        yield threading
    finally:
        for pv in pvs:
            pv.disconnect()

        shared_broadcaster.disconnect()
    logger.debug('Done')
def test_specified_port(monkeypatch, context, ioc):
    pv, = context.get_pvs(ioc.pvs['float'])
    pv.wait_for_connection(timeout=10)

    circuit = pv.circuit_manager.circuit
    address_list = list(caproto.get_address_list())
    address_list.append('{}:{}'.format(circuit.host, circuit.port))

    def get_address_list():
        return address_list

    for module in (caproto._utils, caproto, caproto.threading.client):
        if hasattr(module, 'get_address_list'):
            print('patching', module)
            monkeypatch.setattr(module, 'get_address_list', get_address_list)

    print()
    print('- address list is now:', address_list)
    shared_broadcaster = SharedBroadcaster()
    new_context = Context(shared_broadcaster)
    pv1, = new_context.get_pvs(ioc.pvs['float'])
    pv1.wait_for_connection()
    assert pv1.connected
    pv1.read()
    new_context.disconnect()
Exemple #5
0
    def client_test():
        shared_broadcaster = SharedBroadcaster()
        cntx = PVContext(broadcaster=shared_broadcaster, log_level='DEBUG')

        pv = cntx.get_pv('int')
        assert pv.get() == caget_pvdb['int'].value
        print('get', pv.get())

        monitor_values = []

        def callback(value=None, **kwargs):
            print('monitor', value)
            monitor_values.append(value[0])

        pv.add_callback(callback)
        pv.put(1, wait=True)
        pv.put(2, wait=True)
        pv.put(3, wait=True)

        for i in range(3):
            if pv.get() == 3:
                break
            else:
                time.sleep(0.1)

        assert len(monitor_values) == 4
def shared_broadcaster(request):
    broadcaster = SharedBroadcaster()

    def cleanup():
        broadcaster.disconnect()

    request.addfinalizer(cleanup)
    return broadcaster
Exemple #7
0
def setup_module(module):
    default_setup_module(module)

    shared_broadcaster = SharedBroadcaster()
    PV._default_context = Context(broadcaster=shared_broadcaster,
                                  log_level='DEBUG')
    thread_client._dflt_context = thread_client.PVContext(shared_broadcaster)
    PV._default_context.register()
Exemple #8
0
def threading_broadcaster(request):
    from caproto.threading.client import SharedBroadcaster
    broadcaster = SharedBroadcaster()

    def cleanup():
        broadcaster.disconnect()

    request.addfinalizer(cleanup)
    return broadcaster
Exemple #9
0
def setup_module(module):
    from conftest import start_repeater
    start_repeater()

    shared_broadcaster = SharedBroadcaster()
    PV._default_context = Context(broadcaster=shared_broadcaster,
                                  log_level='DEBUG')
    thread_client._dflt_context = thread_client.PVContext(shared_broadcaster)
    PV._default_context.register()
def shared_broadcaster(request):
    sb = SharedBroadcaster()

    def cleanup():
        sb.disconnect()
        assert not sb._command_thread.is_alive()
        assert not sb.selector.thread.is_alive()
        assert not sb._retry_unanswered_searches_thread.is_alive()

    request.addfinalizer(cleanup)
    return sb
Exemple #11
0
def bench_threading_put_speed(pvname, *, value, log_level='ERROR'):
    from caproto.threading.client import (PV, SharedBroadcaster, Context as
                                          ThreadingContext)

    shared_broadcaster = SharedBroadcaster()
    context = ThreadingContext(broadcaster=shared_broadcaster,
                               log_level=log_level)

    def threading():
        pv.put(value, wait=True)

    pv = PV(pvname, auto_monitor=False, context=context)

    yield threading

    np.testing.assert_array_almost_equal(pv.get(), value)

    logger.debug('Disconnecting threading pv %s', pv)
    pv.disconnect()
    logger.debug('Disconnecting shared broadcaster %s', shared_broadcaster)
    shared_broadcaster.disconnect()
    logger.debug('Done')
Exemple #12
0
def main(pvname1='int', pvname2='str'):
    '''Simple example which connects to two motorsim PVs (by default).

    It tests reading, writing, and subscriptions.
    '''

    shared_broadcaster = SharedBroadcaster()
    ctx = Context(broadcaster=shared_broadcaster)

    # Some user function to call when subscriptions receive data.
    called = []

    def user_callback(command):
        print("Subscription has received data: {}".format(command))
        called.append(command)

    pv1, pv2 = ctx.get_pvs(pvname1, pvname2)
    pv1.wait_for_connection()
    pv2.wait_for_connection()

    # Read and subscribe to pv1
    reading = pv1.read()
    print(f'{pv1} read back: {reading}')
    sub = pv1.subscribe()
    sub.add_callback(user_callback)
    print(f'{pv2} read back: {pv2.read()}')

    # Test writing a couple values:
    value1, value2 = [val + 1 for val in reading.data], reading.data

    pv1.write(value1, timeout=5)
    reading = pv1.read()
    print(f'wrote {value1} and read back: {reading.data}')

    time.sleep(0.1)

    pv1.write(value2, timeout=5)
    reading = pv1.read()
    print(f'wrote {value2} and read back: {reading.data}')

    time.sleep(0.1)

    # Clean up the subscription
    sub.clear()

    pv2.go_idle()
    pv1.go_idle()

    print('The subscription callback saw the following data:')
    for command in called:
        print(f'    * {command.data}')
def main(pv1="XF:31IDA-OP{Tbl-Ax:X1}Mtr.VAL",
         pv2="XF:31IDA-OP{Tbl-Ax:X2}Mtr.VAL"):
    '''Simple example which connects to two motorsim PVs (by default).

    It tests reading, writing, and subscriptions.
    '''

    shared_broadcaster = SharedBroadcaster()
    pv1 = "XF:31IDA-OP{Tbl-Ax:X1}Mtr.VAL"
    pv2 = "XF:31IDA-OP{Tbl-Ax:X2}Mtr.VAL"

    # Some user function to call when subscriptions receive data.
    called = []

    def user_callback(command):
        print("Subscription has received data: {}".format(command))
        called.append(True)

    ctx = Context(broadcaster=shared_broadcaster, log_level='DEBUG')
    ctx.register()
    ctx.search(pv1)
    ctx.search(pv2)
    # Send out connection requests without waiting for responses...
    chan1 = ctx.create_channel(pv1)
    chan2 = ctx.create_channel(pv2)
    # Set up a function to call when subscriptions are received.
    chan1.register_user_callback(user_callback)

    reading = chan1.read()
    print('reading:', reading)
    chan1.subscribe()
    chan2.read()
    chan1.unsubscribe(0)
    chan1.write((5, ))
    reading = chan1.read()
    assert reading.data == 5
    print('reading:', reading)
    chan1.write((6, ))
    reading = chan1.read()
    assert reading.data == 6
    print('reading:', reading)
    chan2.disconnect()
    chan1.disconnect()
    assert called
Exemple #14
0
    def _run(self):
        from caproto.threading.client import Context, SharedBroadcaster
        broadcaster = SharedBroadcaster()
        context = Context(broadcaster)

        self.pvs = {
            key: pv
            for key, pv in zip(self.pvs, context.get_pvs(*self.pvs.values()))
        }

        for pv in self.pvs.values():
            pv.wait_for_connection()

        if self.acquire:
            self.pvs['enabled'].write([1], wait=True)
            self.pvs['image_mode'].write('Continuous',
                                         data_type=ChannelType.STRING,
                                         wait=True)
            self.pvs['acquire'].write(1, wait=False)

        width = self.pvs['array_size0'].read().data[0]
        height = self.pvs['array_size1'].read().data[0]
        depth = self.pvs['array_size2'].read().data[0]

        color_mode = self.pvs['color_mode'].read(
            data_type=ca.ChannelType.STRING)
        color_mode = color_mode.data[0].decode('ascii')

        bayer_pattern = self.pvs['bayer_pattern'].read(
            data_type=ca.ChannelType.STRING)
        bayer_pattern = bayer_pattern.data[0].decode('ascii')

        self.new_image_size.emit(width, height, depth, color_mode,
                                 bayer_pattern)

        print(f'width: {width} height: {height} depth: {depth} '
              f'color_mode: {color_mode}')

        def update(response):
            if self.stop_event.is_set():
                if self.sub is not None:
                    self.sub.clear()
                    self.sub = None
                return

            native_type = ca.field_types['native'][response.data_type]
            self.new_image.emit(response.metadata.timestamp, width, height,
                                depth, color_mode, bayer_pattern, native_type,
                                response.data)

        array_data = self.pvs['array_data']
        dtype = ca.field_types['time'][array_data.channel.native_data_type]

        if self.barrier is not None:
            # Synchronize with image viewer widget, if necessary
            self.barrier.wait()

        self.sub = self.pvs['array_data'].subscribe(data_type=dtype)
        # NOTE: threading client requires that the callback function stays in
        # scope, as it uses a weak reference.
        self.sub.add_callback(update)
        print('Monitor has begun')
        self.stop_event.wait()
Exemple #15
0
def _setup_threading_client(log_level):
    from caproto.threading.client import (PV, SharedBroadcaster, Context)
    logging.getLogger('caproto').setLevel(log_level)
    shared_broadcaster = SharedBroadcaster()
    context = Context(broadcaster=shared_broadcaster)
    return shared_broadcaster, context, PV