예제 #1
0
    def __init__(self, name, cb, notify_disconnect=False):
        self.name, self._S, self._cb = name, None, cb
        self._notify_disconnect = notify_disconnect

        self._Q = cothread.EventQueue()

        if notify_disconnect:
            self._Q.Signal(Disconnected())  # all subscriptions are inittially disconnected

        self._T = cothread.Spawn(self._handle)
예제 #2
0
def test_cothread_ioc(cothread_ioc):
    import cothread
    from cothread.catools import ca_nothing, caget, caput, camonitor

    pre = cothread_ioc.pv_prefix

    with Listener(ADDRESS) as listener, listener.accept() as conn:

        select_and_recv(conn, "R")  # "Ready"

        # Start
        assert caget(pre + ":UPTIME").startswith("00:00:0")
        # WAVEFORM
        caput(pre + ":SINN", 4, wait=True)
        q = cothread.EventQueue()
        m = camonitor(pre + ":SIN", q.Signal, notify_disconnect=True)
        assert len(q.Wait(1)) == 4
        # STRINGOUT
        assert caget(pre + ":STRINGOUT") == "watevah"
        caput(pre + ":STRINGOUT", "something", wait=True)
        assert caget(pre + ":STRINGOUT") == "something"
        # Check pvaccess works
        from p4p.client.cothread import Context
        with Context("pva") as ctx:
            assert ctx.get(pre + ":STRINGOUT") == "something"

        conn.send("D")  # "Done"

        select_and_recv(conn, "D")  # "Done"

        # Stop
        cothread_ioc.proc.send_signal(signal.SIGINT)
        # Disconnect
        assert isinstance(q.Wait(10), ca_nothing)
        m.close()

    # check closed and output
    out, err = cothread_ioc.proc.communicate()
    out = out.decode()
    err = err.decode()
    # check closed and output
    try:
        assert "%s:SINN.VAL 1024 -> 4" % pre in out
        assert 'update_sin_wf 4' in out
        assert "%s:STRINGOUT.VAL watevah -> something" % pre in out
        assert 'on_update \'something\'' in out
        assert 'Starting iocInit' in err
        assert 'iocRun: All initialization complete' in err
    except Exception:
        # Useful printing for when things go wrong!
        print("Out:", out)
        print("Err:", err)
        raise
예제 #3
0
    def __init__(self, bpm, server, volume):
        self.server = server
        self.volume = volume
        self.channels = 'b'

        cothread.Spawn(self.player)

        self.queue = cothread.EventQueue()
        self.sub = None

        # Hang onto input volume level history for last 5 seconds.
        self.mvolume = 100 * numpy.ones(50)
        self.set_bpm(bpm)
예제 #4
0
        def testClientDisconn(self):
            self.pv.open(1.0)

            with Context('pva', conf=self.server.conf(), useenv=False, unwrap={}) as ctxt:
                Q = cothread.EventQueue()
                with ctxt.monitor('foo', Q.Signal, notify_disconnect=True):

                    Q.Wait(timeout=self.timeout) # initial update

                    _log.debug('TEST')
                    self.H.evt.Wait(self.timeout) # onFirstConnect()
                    self.H.evt.Reset()
                    self.assertTrue(self.H.conn)

            self.H.evt.Wait(self.timeout) # onLastDisconnect()
            _log.debug('SHUTDOWN')
            self.assertFalse(self.H.conn)
예제 #5
0
        def testServerShutdown(self):
            self.pv.open(1.0)

            with Context('pva', conf=self.server.conf(), useenv=False, unwrap={}) as ctxt:
                Q = cothread.EventQueue()
                with ctxt.monitor('foo', Q.Signal, notify_disconnect=True):

                    Q.Wait(timeout=self.timeout)

                    _log.debug('TEST')
                    self.H.evt.Wait(self.timeout) # initial update
                    self.H.evt.Reset()
                    self.assertIs(self.H.conn, True)

                    self.server.stop()

                    self.H.evt.Wait(self.timeout) # wait for
                    _log.debug('SHUTDOWN')
                    self.assertIs(self.H.conn, False)
예제 #6
0
    def __init__(self, at_lattice, callback=None, emit_calc=True):
        """
        .. Note:: To avoid errors, the physics data must be initially
           calculated here, during creation, otherwise it could be accidentally
           referenced before the attributes _emitdata and _lindata exist due to
           delay between class creation and the end of the first calculation in
           the thread.

        Args:
            at_lattice (at.lattice_object.Lattice): An instance of an AT
                                                     lattice object.
            callback (callable): Optional, if passed it is called on completion
                                  of each round of physics calculations.
            emit_calc (bool): Whether or not to perform the beam envelope based
                               emittance calculations.

        **Methods:**
        """
        if (not callable(callback)) and (callback is not None):
            raise TypeError("If passed, 'callback' should be callable, {0} is "
                            "not.".format(callback))
        self._at_lat = at_lattice
        self._rp = numpy.ones(len(at_lattice) + 1, dtype=bool)
        self._emit_calc = emit_calc
        # Initial phys data calculation.
        if self._emit_calc:
            self._at_lat.radiation_on()
            self._emitdata = self._at_lat.ohmi_envelope(self._rp)
        self._at_lat.radiation_off()
        self._lindata = self._at_lat.linopt(refpts=self._rp,
                                            get_chrom=True,
                                            coupled=False)
        self._radint = self._at_lat.get_radiation_integrals(
            0.0, self._lindata[3])
        # Threading stuff initialisation.
        self._queue = cothread.EventQueue()
        # Explicitly manage the cothread Events, so turn off auto_reset.
        self._paused = cothread.Event(auto_reset=False)
        self.up_to_date = cothread.Event(auto_reset=False)
        self.up_to_date.Signal()
        self._calculation_thread = cothread.Spawn(self._recalculate_phys_data,
                                                  callback)
예제 #7
0
        def testPVClose(self):
            self.pv.open(1.0)

            with Context('pva', conf=self.server.conf(), useenv=False, unwrap={}) as ctxt:
                Q = cothread.EventQueue()
                with ctxt.monitor('foo', Q.Signal, notify_disconnect=True):

                    Q.Wait(timeout=self.timeout) # initial update

                    _log.debug('TEST')
                    self.H.evt.Wait(self.timeout)
                    self.H.evt.Reset()
                    self.assertTrue(self.H.conn)

                    _log.debug('CLOSING')
                    self.sprov.remove('foo') # prevent new connections while destroying
                    self.pv.close(destroy=True, sync=True, timeout=self.timeout)

                    _log.debug('CLOSED')
                    self.assertFalse(self.H.conn)
예제 #8
0
        def test_monitor(self):
            with Server(providers=[self.provider], isolate=True) as S:
                with Context('pva', conf=S.conf(), useenv=False) as C:

                    Q = cothread.EventQueue()

                    with C.monitor('foo', Q.Signal, notify_disconnect=True) as sub:
                        self.assertIsInstance(Q.Wait(timeout=self.timeout), Disconnected)

                        self.assertEqual(0, Q.Wait(timeout=self.timeout))

                        C.put('foo', 2)

                        self.assertEqual(2 * 2, Q.Wait(timeout=self.timeout))

                        self.pv.close()

                        self.assertIsInstance(Q.Wait(timeout=self.timeout), Disconnected)

                        self.pv.open(3)

                        self.assertEqual(3, Q.Wait(timeout=self.timeout))
예제 #9
0
 def __init__(self):
     self.q = cothread.EventQueue()
     cothread.Spawn(self.run)
예제 #10
0
#!/usr/bin/env dls-python2.6

# Test Callback mechanism

from __future__ import print_function

import require
import cothread
import time
import thread
import numpy

THREADS = 5

signal = cothread.EventQueue()


def do_signal(name, n):
    signal.Signal((name, n))


def signaller(name):
    n = 0
    while True:
        n += 1
        cothread.Callback(do_signal, name, n)
        time.sleep(0.1 * numpy.random.random())


for n in range(THREADS):
    thread.start_new_thread(signaller, ('Thread %d' % n, ))
예제 #11
0
 def setUp(self):
     self.o = cothread.EventQueue()
예제 #12
0
import cothread
import random

queue = cothread.EventQueue()


def producer(queue):
    for i in range(25):
        cothread.Sleep(random.random() * 1.5)
        print(f'item produced: {i}')
        queue.Signal(i)


def consumer(queue):
    for item in queue:
        cothread.Sleep(random.random() * 0.5)
        print(f'item consumed: {item}')


c = cothread.Spawn(consumer, queue)
p = cothread.Spawn(producer, queue)

cothread.Sleep(10)

c.Wait()
p.Wait()
예제 #13
0
 def __init__(self):
     if get_thread_ident() == cothread.scheduler_thread_id:
         self._event_queue = cothread.EventQueue()
     else:
         self._event_queue = cothread.ThreadedEventQueue()