当前位置: 首页>>代码示例>>Python>>正文


Python Event.wait方法代码示例

本文整理汇总了Python中cocotb.triggers.Event.wait方法的典型用法代码示例。如果您正苦于以下问题:Python Event.wait方法的具体用法?Python Event.wait怎么用?Python Event.wait使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在cocotb.triggers.Event的用法示例。


在下文中一共展示了Event.wait方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_drv

# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import wait [as 别名]
class test_drv(BusDriver):
    _signals = ["A", "B", "X"]
    _optional_signals= []

    def __init__(self, entity, name, clock):
        BusDriver.__init__(self, entity, name, clock)
        self.bus.A.setimmediatevalue(5)
        self.bus.B.setimmediatevalue(5)
        self.log.debug("Test DrvM created")
        self.busy_event = Event("%s_busy" % name)
        self.busy = False

    @cocotb.coroutine
    def _acquire_lock(self):
        if self.busy:
            yield self.busy_event.wait()
        self.busy_event.clear()
        self.busy = True

    def _release_lock(self):
        self.busy = False
        self.busy_event.set()


    @cocotb.coroutine
    def write(self, value_a, value_b, sync=True):
        """
        """
        yield self._acquire_lock()

        if sync:
            yield RisingEdge(self.clock)
        self.bus.A <= value_a
        self.bus.B <= value_b

        self._release_lock()
开发者ID:kirknodeng,项目名称:cocotb,代码行数:38,代码来源:test_drv.py

示例2: Monitor

# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import wait [as 别名]
class Monitor(object):
    """Base class for Monitor objects. 

    Monitors are passive 'listening' objects that monitor pins going in or out of a DUT. 
    This class should not be used
    directly, but should be subclassed and the internal :any:`_monitor_recv` method
    should be overridden and decorated as a :any:`coroutine`.  This :any:`_monitor_recv`
    method should capture some behavior of the pins, form a transaction, and
    pass this transaction to the internal :any:`_recv` method.  The :any:`_monitor_recv`
    method is added to the cocotb scheduler during the ``__init__`` phase, so it
    should not be yielded anywhere.

    The primary use of a Monitor is as an interface for a
    :class:`~cocotb.scoreboard.Scoreboard`.

    Args:
        callback (callable): Callback to be called with each recovered transaction 
            as the argument. If the callback isn't used, received transactions will 
            be placed on a queue and the event used to notify any consumers.
        event (event): Object that supports a ``set`` method that will be called when
            a transaction is received through the internal :any:`_recv` method.
    """

    def __init__(self, callback=None, event=None):
        self._event = event
        self._wait_event = None
        self._recvQ = deque()
        self._callbacks = []
        self.stats = MonitorStatistics()
        self._wait_event = Event()

        # Subclasses may already set up logging
        if not hasattr(self, "log"):
            self.log = SimLog("cocotb.monitor.%s" % (self.__class__.__name__))

        if callback is not None:
            self.add_callback(callback)

        # Create an independent coroutine which can receive stuff
        self._thread = cocotb.scheduler.add(self._monitor_recv())

    def kill(self):
        """Kill the monitor coroutine."""
        if self._thread:
            self._thread.kill()
            self._thread = None

    def __len__(self):
        return len(self._recvQ)

    def __getitem__(self, idx):
        return self._recvQ[idx]

    def add_callback(self, callback):
        """Add function as a callback.

        Args:
            callback (callable): The function to call back.
        """
        self.log.debug("Adding callback of function %s to monitor" %
                       (callback.__name__))
        self._callbacks.append(callback)

    @coroutine
    def wait_for_recv(self, timeout=None):
        """With *timeout*, :meth:`.wait` for transaction to arrive on monitor 
        and return its data.

        Args:
            timeout (optional): The timeout value for :class:`~.triggers.Timer`.
                Defaults to ``None``.

        Returns: Data of received transaction.
        """
        if timeout:
            t = Timer(timeout)
            fired = yield [self._wait_event.wait(), t]
            if fired is t:
                raise ReturnValue(None)
        else:
            yield self._wait_event.wait()

        pkt = self._wait_event.data
        raise ReturnValue(pkt)

    @coroutine
    def _monitor_recv(self):
        """Actual implementation of the receiver.

        Subclasses should override this method to implement the actual receive
        routine and call :any:`_recv` with the recovered transaction.
        """
        raise NotImplementedError("Attempt to use base monitor class without "
                                  "providing a ``_monitor_recv`` method")

    def _recv(self, transaction):
        """Common handling of a received transaction."""

        self.stats.received_transactions += 1

#.........这里部分代码省略.........
开发者ID:zpan007,项目名称:cocotb,代码行数:103,代码来源:__init__.py

示例3: OPBMaster

# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import wait [as 别名]
class OPBMaster(BusDriver):
    """
    On-chip peripheral bus master
    """
    _signals = ["xferAck", "errAck", "toutSup", "retry", "DBus_out", "select", "RNW", "BE", "ABus", "DBus_in"]
    _optional_signals = ["seqAddr"]
    _max_cycles = 16

    def __init__(self, entity, name, clock):
        BusDriver.__init__(self, entity, name, clock)
        self.bus.select.setimmediatevalue(0)
        self.log.debug("OPBMaster created")
        self.busy_event = Event("%s_busy" % name)
        self.busy = False

    @cocotb.coroutine
    def _acquire_lock(self):
        if self.busy:
            yield self.busy_event.wait()
        self.busy_event.clear()
        self.busy = True

    def _release_lock(self):
        self.busy = False
        self.busy_event.set()

    @cocotb.coroutine
    def read(self, address, sync=True):
        """
        Issue a request to the bus and block until this
        comes back. Simulation time still progresses
        but syntactically it blocks.
        """
        yield self._acquire_lock()

        # Apply values for next clock edge
        if sync:
            yield RisingEdge(self.clock)
        self.bus.ABus <= address
        self.bus.select <= 1
        self.bus.RNW <= 1
        self.bus.BE <= 0xF

        count = 0
        while not int(self.bus.xferAck.value):
            yield RisingEdge(self.clock)
            yield ReadOnly()
            if int(self.bus.toutSup.value):
                count = 0
            else:
                count += 1
            if count >= self._max_cycles:
                raise OPBException("Read took longer than 16 cycles")
        data = int(self.bus.DBus_out.value)

        # Deassert read
        self.bus.select <= 0
        self._release_lock()
        self.log.info("Read of address 0x%x returned 0x%08x" % (address, data))
        raise ReturnValue(data)

    @cocotb.coroutine
    def write(self, address, value, sync=True):
        """
        """
        yield self._acquire_lock()

        if sync:
            yield RisingEdge(self.clock)
        self.bus.ABus <= address
        self.bus.select <= 1
        self.bus.RNW <= 0
        self.bus.BE <= 0xF
        self.bus.DBus_out <= value

        count = 0
        while not int(self.bus.xferAck.value):
            yield RisingEdge(self.clock)
            yield ReadOnly()
            if int(self.bus.toutSup.value):
                count = 0
            else:
                count += 1
            if count >= self._max_cycles:
                raise OPBException("Write took longer than 16 cycles")

        self.bus.select <= 0
        self._release_lock()
开发者ID:enchanter,项目名称:cocotb,代码行数:90,代码来源:opb.py

示例4: AvalonMaster

# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import wait [as 别名]
class AvalonMaster(AvalonMM):
    """Avalon Memory Mapped Interface (Avalon-MM) Master"""
    def __init__(self, entity, name, clock, **kwargs):
        AvalonMM.__init__(self, entity, name, clock, **kwargs)
        self.log.debug("AvalonMaster created")
        self.busy_event = Event("%s_busy" % name)
        self.busy = False

    def __len__(self):
        return 2**len(self.bus.address)

    @coroutine
    def _acquire_lock(self):
        if self.busy:
            yield self.busy_event.wait()
        self.busy_event.clear()
        self.busy = True

    def _release_lock(self):
        self.busy = False
        self.busy_event.set()

    @coroutine
    def read(self, address, sync=True):
        """Issue a request to the bus and block until this
        comes back. Simulation time still progresses
        but syntactically it blocks.
        
        Args:
            address (int): The address to read from.
            sync (bool, optional): Wait for rising edge on clock initially.
                Defaults to True.
            
        Returns:
            BinaryValue: The read data value.
            
        Raises:
            :any:`TestError`: If master is write-only.
        """
        if not self._can_read:
            self.log.error("Cannot read - have no read signal")
            raise TestError("Attempt to read on a write-only AvalonMaster")

        yield self._acquire_lock()

        # Apply values for next clock edge
        if sync:
            yield RisingEdge(self.clock)
        self.bus.address <= address
        self.bus.read <= 1
        if hasattr(self.bus, "byteenable"):
            self.bus.byteenable <= int("1"*len(self.bus.byteenable), 2)
        if hasattr(self.bus, "cs"):
            self.bus.cs <= 1

        # Wait for waitrequest to be low
        if hasattr(self.bus, "waitrequest"):
            yield self._wait_for_nsignal(self.bus.waitrequest)
        yield RisingEdge(self.clock)

        # Deassert read
        self.bus.read <= 0
        if hasattr(self.bus, "byteenable"):
            self.bus.byteenable <= 0
        if hasattr(self.bus, "cs"):
            self.bus.cs <= 0
        v = self.bus.address.value
        v.binstr = "x" * len(self.bus.address)
        self.bus.address <= v

        if hasattr(self.bus, "readdatavalid"):
            while True:
                yield ReadOnly()
                if int(self.bus.readdatavalid):
                    break
                yield RisingEdge(self.clock)
        else:
            # Assume readLatency = 1 if no readdatavalid
            # FIXME need to configure this,
            # should take a dictionary of Avalon properties.
            yield ReadOnly()

        # Get the data
        data = self.bus.readdata.value

        self._release_lock()
        raise ReturnValue(data)

    @coroutine
    def write(self, address, value):
        """Issue a write to the given address with the specified
        value.

        Args:
            address (int): The address to write to.
            value (int): The data value to write.

        Raises:
            :any:`TestError`: If master is read-only.
        """
#.........这里部分代码省略.........
开发者ID:TC01,项目名称:cocotb,代码行数:103,代码来源:avalon.py

示例5: Driver

# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import wait [as 别名]
class Driver(object):
    """

    Class defining the standard interface for a driver within a testbench

    The driver is responsible for serialising transactions onto the physical
    pins of the interface.  This may consume simulation time.
    """
    def __init__(self):
        """
        Constructor for a driver instance
        """
        # self._busy = Lock()
        self._pending = Event(name="Driver._pending")
        self._sendQ = deque()

        # Subclasses may already set up logging
        if not hasattr(self, "log"):
            self.log = SimLog("cocotb.driver.%s" % (self.__class__.__name__))

        # Create an independent coroutine which can send stuff
        self._thread = cocotb.scheduler.add(self._send_thread())

    def kill(self):
        if self._thread:
            self._thread.kill()
            self._thread = None

    def append(self, transaction, callback=None, event=None):
        """
        Queue up a transaction to be sent over the bus.

        Mechanisms are provided to permit the caller to know when the
        transaction is processed

        callback: optional function to be called when the transaction has been
        sent

        event: event to be set when the tansaction has been sent
        """
        self._sendQ.append((transaction, callback, event))
        self._pending.set()

    def clear(self):
        """
        Clear any queued transactions without sending them onto the bus
        """
        self._sendQ = deque()

    @coroutine
    def send(self, transaction, sync=True):
        """
        Blocking send call (hence must be "yielded" rather than called)

        Sends the transaction over the bus

        Args:
            transaction (any): the transaction to send

        Kwargs:
            sync (boolean): synchronise the transfer by waiting for risingedge
        """
        yield self._send(transaction, None, None, sync=sync)

    def _driver_send(self, transaction, sync=True):
        """
        actual impementation of the send.

        subclasses should override this method to implement the actual send
        routine
        """
        raise NotImplementedError("Subclasses of Driver should define a "
                                  "_driver_send coroutine")

    @coroutine
    def _send(self, transaction, callback, event, sync=True):
        """
        assumes the caller has already acquired the busy lock

        releases busy lock once sending is complete
        """
        yield self._driver_send(transaction, sync=sync)

        # Notify the world that this transaction is complete
        if event:
            event.set()
        if callback:
            callback(transaction)

        # No longer hogging the bus
        # self.busy.release()

    @coroutine
    def _send_thread(self):
        while True:

            # Sleep until we have something to send
            while not self._sendQ:
                self._pending.clear()
                yield self._pending.wait()
#.........这里部分代码省略.........
开发者ID:tgingold,项目名称:cocotb,代码行数:103,代码来源:__init__.py

示例6: AvalonMaster

# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import wait [as 别名]
class AvalonMaster(AvalonMM):
    """Avalon-MM master
    """
    def __init__(self, entity, name, clock):
        AvalonMM.__init__(self, entity, name, clock)
        self.log.debug("AvalonMaster created")
        self.busy_event = Event("%s_busy" % name)
        self.busy = False

    def __len__(self):
        return 2**len(self.bus.address)

    @coroutine
    def _acquire_lock(self):
        if self.busy:
            yield self.busy_event.wait()
        self.busy_event.clear()
        self.busy = True

    def _release_lock(self):
        self.busy = False
        self.busy_event.set()

    @coroutine
    def read(self, address, sync=True):
        """
        Issue a request to the bus and block until this
        comes back. Simulation time still progresses
        but syntactically it blocks.
        See http://www.altera.com/literature/manual/mnl_avalon_spec_1_3.pdf
        """
        if not self._can_read:
            self.log.error("Cannot read - have no read signal")
            raise TestError("Attempt to read on a write-only AvalonMaster")

        yield self._acquire_lock()

        # Apply values for next clock edge
        if sync:
            yield RisingEdge(self.clock)
        self.bus.address <= address
        self.bus.read <= 1
        if hasattr(self.bus, "byteenable"):
            self.bus.byteenable <= int("1"*len(self.bus.byteenable), 2)
        if hasattr(self.bus, "cs"):
            self.bus.cs <= 1

        # Wait for waitrequest to be low
        if hasattr(self.bus, "waitrequest"):
            yield self._wait_for_nsignal(self.bus.waitrequest)
        yield RisingEdge(self.clock)
        # Get the data
        data = self.bus.readdata.value
        # Deassert read
        self.bus.read <= 0
        if hasattr(self.bus, "byteenable"):
            self.bus.byteenable <= 0
        if hasattr(self.bus, "cs"):
            self.bus.cs <= 0
        v = self.bus.address.value
        v.binstr = "x" * len(self.bus.address)
        self.bus.address <= v

        if hasattr(self.bus, "readdatavalid"):
            while True:
                yield ReadOnly()
                # Get the data
                if int(self.bus.readdatavalid):
                    data = self.bus.readdata.value
                    break
                yield RisingEdge(self.clock)
        else:
            # Assume readLatency = 1 if no readdatavalid
            # FIXME need to configure this,
            # should take a dictionary of Avalon properties.
            yield ReadOnly()

        self._release_lock()
        raise ReturnValue(data)

    @coroutine
    def write(self, address, value):
        """
        Issue a write to the given address with the specified
        value.
        See http://www.altera.com/literature/manual/mnl_avalon_spec_1_3.pdf
        """
        if not self._can_write:
            self.log.error("Cannot write - have no write signal")
            raise TestError("Attempt to write on a read-only AvalonMaster")

        yield self._acquire_lock()

        # Apply valuse to bus
        yield RisingEdge(self.clock)
        self.bus.address <= address
        self.bus.writedata <= value
        self.bus.write <= 1
        if hasattr(self.bus, "byteenable"):
            self.bus.byteenable <= int("1"*len(self.bus.byteenable), 2)
#.........这里部分代码省略.........
开发者ID:Martoni,项目名称:cocotb,代码行数:103,代码来源:avalon.py

示例7: Driver

# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import wait [as 别名]
class Driver(object):
    """Class defining the standard interface for a driver within a testbench.

    The driver is responsible for serialising transactions onto the physical
    pins of the interface.  This may consume simulation time.
    """
    def __init__(self):
        """Constructor for a driver instance."""
        self._pending = Event(name="Driver._pending")
        self._sendQ = deque()

        # Subclasses may already set up logging
        if not hasattr(self, "log"):
            self.log = SimLog("cocotb.driver.%s" % (self.__class__.__name__))

        # Create an independent coroutine which can send stuff
        self._thread = cocotb.scheduler.add(self._send_thread())

    def kill(self):
        """Kill the coroutine sending stuff."""
        if self._thread:
            self._thread.kill()
            self._thread = None

    def append(self, transaction, callback=None, event=None, **kwargs):
        """Queue up a transaction to be sent over the bus.

        Mechanisms are provided to permit the caller to know when the
        transaction is processed.

        Args:
            transaction (any): The transaction to be sent.
            callback (callable, optional): Optional function to be called 
                when the transaction has been sent.
            event (optional): :class:`~cocotb.triggers.Event` to be set
                when the transaction has been sent.
            **kwargs: Any additional arguments used in child class' 
                :any:`_driver_send` method.
        """
        self._sendQ.append((transaction, callback, event, kwargs))
        self._pending.set()

    def clear(self):
        """Clear any queued transactions without sending them onto the bus."""
        self._sendQ = deque()

    @coroutine
    def send(self, transaction, sync=True, **kwargs):
        """Blocking send call (hence must be "yielded" rather than called).

        Sends the transaction over the bus.

        Args:
            transaction (any): The transaction to be sent.
            sync (bool, optional): Synchronise the transfer by waiting for a rising edge.
            **kwargs (dict): Additional arguments used in child class'
                :any:`_driver_send` method.
        """
        yield self._send(transaction, None, None, sync=sync, **kwargs)

    def _driver_send(self, transaction, sync=True, **kwargs):
        """Actual implementation of the send.

        Subclasses should override this method to implement the actual 
        :meth:`~cocotb.drivers.Driver.send` routine.

        Args:
            transaction (any): The transaction to be sent.
            sync (boolean, optional): Synchronise the transfer by waiting for a rising edge.
            **kwargs: Additional arguments if required for protocol implemented in subclass.
        """
        raise NotImplementedError("Subclasses of Driver should define a "
                                  "_driver_send coroutine")

    @coroutine
    def _send(self, transaction, callback, event, sync=True, **kwargs):
        """Send coroutine.

        Args:
            transaction (any): The transaction to be sent.
            callback (callable, optional): Optional function to be called 
                when the transaction has been sent.
            event (optional): event to be set when the transaction has been sent.
            sync (boolean, optional): Synchronise the transfer by waiting for a rising edge.
            **kwargs: Any additional arguments used in child class' 
                :any:`_driver_send` method.
        """
        yield self._driver_send(transaction, sync=sync, **kwargs)

        # Notify the world that this transaction is complete
        if event:
            event.set()
        if callback:
            callback(transaction)

    @coroutine
    def _send_thread(self):
        while True:

            # Sleep until we have something to send
#.........这里部分代码省略.........
开发者ID:TC01,项目名称:cocotb,代码行数:103,代码来源:__init__.py

示例8: Monitor

# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import wait [as 别名]
class Monitor(object):

    def __init__(self, callback=None, event=None):
        """
        Constructor for a monitor instance

        callback will be called with each recovered transaction as the argument

        If the callback isn't used, received transactions will be placed on a
        queue and the event used to notify any consumers.
        """
        self._event = event
        self._wait_event = None
        self._recvQ = []
        self._callbacks = []
        self.stats = MonitorStatistics()
        self._wait_event = Event()

        # Subclasses may already set up logging
        if not hasattr(self, "log"):
            self.log = SimLog("cocotb.monitor.%s" % (self.__class__.__name__))

        if callback is not None:
            self.add_callback(callback)

        # Create an independent coroutine which can receive stuff
        self._thread = cocotb.scheduler.add(self._monitor_recv())

    def kill(self):
        if self._thread:
            self._thread.kill()
            self._thread = None

    def __len__(self):
        return len(self._recvQ)

    def __getitem__(self, idx):
        return self._recvQ[idx]

    def add_callback(self, callback):
        self.log.debug("Adding callback of function %s to monitor" %
                       (callback.__name__))
        self._callbacks.append(callback)

    @coroutine
    def wait_for_recv(self, timeout=None):
        if timeout:
            t = Timer(timeout)
            fired = yield [self._wait_event.wait(), t]
            if fired is t:
                raise ReturnValue(None)
        else:
            yield self._wait_event.wait()

        pkt = self._wait_event.data
        raise ReturnValue(pkt)

    @coroutine
    def _monitor_recv(self):
        """
        actual impementation of the receiver

        subclasses should override this method to implement the actual receive
        routine and call self._recv() with the recovered transaction
        """
        raise NotImplementedError("Attempt to use base monitor class without "
                                  "providing a _monitor_recv method")

    def _recv(self, transaction):
        """Common handling of a received transaction."""

        self.stats.received_transactions += 1

        # either callback based consumer
        for callback in self._callbacks:
            callback(transaction)

        # Or queued with a notification
        if not self._callbacks:
            self._recvQ.append(transaction)

        if self._event is not None:
            self._event.set()

        # If anyone was waiting then let them know
        if self._wait_event is not None:
            self._wait_event.set(data=transaction)
            self._wait_event.clear()
开发者ID:cpehle,项目名称:cocotb,代码行数:90,代码来源:__init__.py

示例9: Scheduler

# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import wait [as 别名]
class Scheduler(object):
    """The main scheduler.

    Here we accept callbacks from the simulator and schedule the appropriate
    coroutines.

    A callback fires, causing the :any:`react` method to be called, with the
    trigger that caused the callback as the first argument.

    We look up a list of coroutines to schedule (indexed by the trigger) and
    schedule them in turn. NB implementors should not depend on the scheduling
    order!

    Some additional management is required since coroutines can return a list
    of triggers, to be scheduled when any one of the triggers fires.  To
    ensure we don't receive spurious callbacks, we have to un-prime all the
    other triggers when any one fires.

    Due to the simulator nuances and fun with delta delays we have the
    following modes:

    Normal mode
        - Callbacks cause coroutines to be scheduled
        - Any pending writes are cached and do not happen immediately

    ReadOnly mode
        - Corresponds to cbReadOnlySynch (VPI) or vhpiCbLastKnownDeltaCycle
          (VHPI).  In this state we are not allowed to perform writes.

    Write mode
        - Corresponds to cbReadWriteSynch (VPI) or vhpiCbEndOfProcesses (VHPI)
          In this mode we play back all the cached write updates.

    We can legally transition from normal->write by registering a ReadWrite
    callback, however usually once a simulator has entered the ReadOnly phase
    of a given timestep then we must move to a new timestep before performing
    any writes.  The mechanism for moving to a new timestep may not be
    consistent across simulators and therefore we provide an abstraction to
    assist with compatibility.


    Unless a coroutine has explicitly requested to be scheduled in ReadOnly
    mode (for example wanting to sample the finally settled value after all
    delta delays) then it can reasonably be expected to be scheduled during
    "normal mode" i.e. where writes are permitted.
    """

    _MODE_NORMAL   = 1  # noqa
    _MODE_READONLY = 2  # noqa
    _MODE_WRITE    = 3  # noqa
    _MODE_TERM     = 4  # noqa

    # Singleton events, recycled to avoid spurious object creation
    _readonly = ReadOnly()
    _timer1 = Timer(1)

    def __init__(self):

        self.log = SimLog("cocotb.scheduler")
        if _debug:
            self.log.setLevel(logging.DEBUG)

        # Use OrderedDict here for deterministic behavior (gh-934)

        # A dictionary of pending coroutines for each trigger,
        # indexed by trigger
        self._trigger2coros = collections.OrderedDict()

        # A dictionary mapping coroutines to the trigger they are waiting for
        self._coro2trigger = collections.OrderedDict()

        # Our main state
        self._mode = Scheduler._MODE_NORMAL

        # A dictionary of pending writes
        self._writes = collections.OrderedDict()

        self._pending_coros = []
        self._pending_triggers = []
        self._pending_threads = []
        self._pending_events = []   # Events we need to call set on once we've unwound

        self._terminate = False
        self._test_result = None
        self._entrypoint = None
        self._main_thread = threading.current_thread()

        self._is_reacting = False

        self._write_coro_inst = None
        self._writes_pending = Event()

    @cocotb.decorators.coroutine
    def _do_writes(self):
        """ An internal coroutine that performs pending writes """
        while True:
            yield self._writes_pending.wait()
            if self._mode != Scheduler._MODE_NORMAL:
                yield NextTimeStep()

#.........这里部分代码省略.........
开发者ID:cmarqu,项目名称:cocotb,代码行数:103,代码来源:scheduler.py

示例10: WishboneMaster

# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import wait [as 别名]
class WishboneMaster(Wishbone):
    """Wishbone master
    """
    _acked_ops          = 0  # ack cntr. comp with opbuf len. wait for equality before releasing lock
    _res_buf            = [] # save readdata/ack/err
    _aux_buf            = [] # save read/write order
    _op_cnt             = 0 # number of ops we've been issued
    _clk_cycle_count    = 0
    _timeout            = None

    
    def __init__(self, entity, name, clock, timeout=5000):
        Wishbone.__init__(self, entity, name, clock)
        sTo = ", no cycle timeout"        
        if not (timeout is None):
            sTo = ", cycle timeout is %u clockcycles" % timeout
        self.log.info("Wishbone Master created%s" % sTo)
        self.busy_event = Event("%s_busy" % name)
        self.busy = False
        self._timeout = timeout
        
    @coroutine 
    def _clk_cycle_counter(self):
        """
            Cycle counter to time bus operations
        """
        clkedge = RisingEdge(self.clock)
        self._clk_cycle_count = 0
        while self.busy:
            yield clkedge
            self._clk_cycle_count += 1    
  
    @coroutine
    def _open_cycle(self):
        #Open new wishbone cycle        
        if self.busy:
            self.log.error("Opening Cycle, but WB Driver is already busy. Someting's wrong")
            yield self.busy_event.wait()
        self.busy_event.clear()
        self.busy       = True
        cocotb.fork(self._read())
        cocotb.fork(self._clk_cycle_counter()) 
        self.bus.cyc    <= 1
        self._acked_ops = 0  
        self._res_buf   = [] 
        self._aux_buf   = []
        self.log.debug("Opening cycle, %u Ops" % self._op_cnt)
        
    @coroutine    
    def _close_cycle(self):
        #Close current wishbone cycle  
        clkedge = RisingEdge(self.clock)
        count           = 0
        last_acked_ops  = 0
        #Wait for all Operations being acknowledged by the slave before lowering the cycle line
        #This is not mandatory by the bus standard, but a crossbar might send acks to the wrong master
        #if we don't wait. We don't want to risk that, it could hang the bus
        while self._acked_ops < self._op_cnt:
            if last_acked_ops != self._acked_ops:
                self.log.debug("Waiting for missing acks: %u/%u" % (self._acked_ops, self._op_cnt) )
            last_acked_ops = self._acked_ops    
            #check for timeout when finishing the cycle            
            count += 1
            if (not (self._timeout is None)):
                if (count > self._timeout): 
                    raise TestFailure("Timeout of %u clock cycles reached when waiting for reply from slave" % self._timeout)                
            yield clkedge
            
        self.busy = False
        self.busy_event.set()
        self.bus.cyc <= 0 
        self.log.debug("Closing cycle")
        yield clkedge        

    
    @coroutine
    def _wait_stall(self):
        """Wait for stall to be low before continuing
        """
        clkedge = RisingEdge(self.clock)
        count = 0
        if hasattr(self.bus, "stall"):
            count = 0            
            while self.bus.stall.getvalue():
                yield clkedge
                count += 1
                if (not (self._timeout is None)):
                    if (count > self._timeout): 
                        raise TestFailure("Timeout of %u clock cycles reached when on stall from slave" % self._timeout)                
            self.log.debug("Stalled for %u cycles" % count)
        raise ReturnValue(count)
    
    
    @coroutine
    def _wait_ack(self):
        """Wait for ACK on the bus before continuing
        """
        #wait for acknownledgement before continuing - Classic Wishbone without pipelining
        clkedge = RisingEdge(self.clock)
        count = 0
#.........这里部分代码省略.........
开发者ID:mkreider,项目名称:cocotb2,代码行数:103,代码来源:wishbone.py

示例11: __init__

# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import wait [as 别名]
class I2CHALAnalyser:

    def __init__(self, helperSlave, listOperation):
        self.sda = helperSlave.io.sda_rd
        self.scl = helperSlave.io.scl_rd
        self.clk = helperSlave.io.clk

        self.event_RisingEdge  = Event()
        self.event_FallingEdge  = Event()

        self.event_Start = Event()
        self.event_Stop  = Event()

        self.listOp = list()
        self.refListOp = listOperation
        self.dataBinRead = list()

        self.startSeq = 0


    #==========================================================================
    # Start to analyse the bus
    #==========================================================================
    @cocotb.coroutine
    def start(self):

        self.fork_falling = cocotb.fork(self._FallingEdgeDetection())
        self.fork_rising  = cocotb.fork(self._RisingEdgeDetection())
        self.fork_start   = cocotb.fork(self._startDetection())
        self.fork_stop    = cocotb.fork(self._stopDetection())
        yield self._analyser()


    #==========================================================================
    # Stop all processes
    #==========================================================================
    def stop(self):
        self.fork_falling.kill()
        self.fork_rising.kill()
        self.fork_start.kill()
        self.fork_stop.kill()


    #==========================================================================
    # Store all event appening on the bus
    #==========================================================================
    @cocotb.coroutine
    def _analyser(self):

        self.listOp = list()

        # Start ---------------------------------------------------------------
        yield self.event_Start.wait()
        yield RisingEdge(self.clk)
        self.startSeq = 0

        while True:

            dataBinRead = list()
            index = 0
            # Read data -----------------------------------------------------------
            while index < I2CConfig.dataWdith:
                yield self.event_RisingEdge.wait()
                dataBinRead.append(int(self.sda))
                #print("data ", index, " value " , int(self.sda), "index ", index, "start " , self.startSeq )

                if self.startSeq == 1:
                    index = 0
                    self.startSeq = 0
                    dataBinRead = list()
                    dataBinRead.append(int(self.sda))

                index += 1

            dataInRead = int("".join([str(x) for x in dataBinRead]), 2)
            self.listOp.append(DATA(dataInRead))

            # Read ACK ------------------------------------------------------------
            yield self.event_RisingEdge.wait()
            if int(self.sda) == 0:
                self.listOp.append(ACK())
            else:
                self.listOp.append(NACK())

            #print()

    #==========================================================================
    # Detect the start condition
    #==========================================================================
    @cocotb.coroutine
    def _startDetection(self):
        yield RisingEdge(self.clk)
        while True:
            prev = int(self.sda)
            yield RisingEdge(self.clk)
            if prev == 1 and int(self.sda) == 0:
                if int(self.scl) == 1:
                    self.event_Start.set()
                    self.listOp.append(START())
                    self.startSeq = 1
#.........这里部分代码省略.........
开发者ID:svancau,项目名称:SpinalHDL,代码行数:103,代码来源:I2CHAL.py

示例12: AvalonMaster

# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import wait [as 别名]
class AvalonMaster(AvalonMM):
    """Avalon-MM master
    """
    def __init__(self, entity, name, clock):
        AvalonMM.__init__(self, entity, name, clock)
        self.log.debug("AvalonMaster created")
        self.busy_event = Event("%s_busy" % name)
        self.busy = False

    @coroutine
    def _acquire_lock(self):
        if self.busy:
            yield self.busy_event.wait()
        self.busy_event.clear()
        self.busy = True

    def _release_lock(self):
        self.busy = False
        self.busy_event.set()

    @coroutine
    def read(self, address):
        """
        Issue a request to the bus and block until this
        comes back. Simulation time still progresses
        but syntactically it blocks.
        See http://www.altera.com/literature/manual/mnl_avalon_spec_1_3.pdf
        """
        yield self._acquire_lock()

        # Apply values for next clock edge
        yield RisingEdge(self.clock)
        self.bus.address <= address
        self.bus.read <= 1

        # Wait for waitrequest to be low
        yield self._wait_for_nsignal(self.bus.waitrequest)

        # Assume readLatency = 1
        # FIXME need to configure this, should take a dictionary of Avalon properties.
        yield RisingEdge(self.clock)

        # Deassert read
        self.bus.read <= 0

        # Get the data
        yield ReadOnly()
        data = self.bus.readdata.value
        yield NextTimeStep()
        self._release_lock()
        raise ReturnValue(data)

    @coroutine
    def write(self, address, value):
        """
        Issue a write to the given address with the specified
        value.
        See http://www.altera.com/literature/manual/mnl_avalon_spec_1_3.pdf
        """
        yield self._acquire_lock()

        # Apply valuse to bus
        yield RisingEdge(self.clock)
        self.bus.address <= address
        self.bus.writedata <= value
        self.bus.write <= 1

        # Wait for waitrequest to be low
        count = yield self._wait_for_nsignal(self.bus.waitrequest)

        # Deassert write
        yield RisingEdge(self.clock)
        self.bus.write <= 0
        self._release_lock()
开发者ID:darylz,项目名称:cocotb,代码行数:76,代码来源:avalon.py

示例13: PCIe_host

# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import wait [as 别名]
class PCIe_host():
    def __init__(self):
        self.read_outstanding = 0
        self.rxdata = []
        self.requested = 0
        self.txqueue = Queue.Queue()
        self.completion_data = np.zeros(4*1048576, dtype = 'uint64')
        self.write_data = np.zeros(4*1048576, dtype = 'uint64')
        self.write_data_expected = np.zeros(4*1048576, dtype = 'uint64')
        self.errors = 0
        self.read_tag = 0
        self.read_data = 0
        self.command_start = 0 # address for commands
    def write(self, data, address):
        """32 bit address / 64 bit data write"""
        tlp = np.zeros(6, dtype='uint32')
        tlp[0] = 0x40000002
        tlp[1] = 0xbeef00ff
        tlp[2] = address
        tlp[3] = endianswap(data)
        tlp[4] = endianswap(data >> 32)
        self.txqueue.put(tlp)

    @cocotb.coroutine
    def read(self, address, tag=0):
        """ 32 bit read """
        tlp = np.zeros(4, dtype='uint32')
        tlp[0] = 0x00000001
        tlp[1] = 0xbaaa00ff | tag << 8
        tlp[2] = address
        self.read_wait = Event("rw")
        self.txqueue.put(tlp)
        yield self.read_wait.wait()
        raise ReturnValue(self.read_data)

    def complete(self, address, reqid_tag):
        address &= 0xFFFF8
        address = address >> 3
        complete_size = random.choice([16,32]) # DW
        cdata_64 = self.completion_data[address:address + 512/8]
        cdata_32 = np.fromstring(cdata_64.tostring(), dtype = 'uint32')
        cdata_32.byteswap(True)
        for i in range(128/complete_size):
            tlp = np.zeros(4 + complete_size, dtype='uint32')
            tlp[0] = 0x4A000000 | complete_size
            tlp[1] = 0xbeef0000 | (512-complete_size*4*i)
            tlp[2] = (reqid_tag << 8) | ((i & 1) << 6)
            tlp[3:3+complete_size] = cdata_32[i*complete_size: (i+1)*complete_size]
            address += complete_size/2
            self.txqueue.put(tlp)

    @cocotb.coroutine
    def do_tx(self, p):
        while True:
            try:
                tlp = self.txqueue.get(False)
                i_last = len(tlp)/2 - 1
                for i in range(len(tlp)/2):
                    while random.choice([0,0,0,1]):
                        p.m_axis_rx_tvalid = 0
                        yield RisingEdge(p.clock)
                    p.m_axis_rx_tvalid = 1
                    p.m_axis_rx_tdata = tlp[2*i] | (int(tlp[2*i+1]) << 32)
                    if i == i_last:
                        p.m_axis_rx_tlast = 1
                    else:
                        p.m_axis_rx_tlast = 0
                    yield RisingEdge(p.clock)
            except Queue.Empty:
                p.m_axis_rx_tvalid = 0
                yield RisingEdge(p.clock)

    @cocotb.coroutine
    def docycle(self, dut):
        p = dut
        p.m_axis_tx_tvalid = 0
        p.s_axis_tx_tready = 0
        p.pci_reset = 1
        for i in range(10):
            yield RisingEdge(p.clock)
        p.pci_reset = 0
        for i in range(10):
            yield RisingEdge(p.clock)
        cocotb.fork(self.do_tx(p))
        while True:
            # RX
            if (int(p.s_axis_tx_tvalid) == 1) and (int(p.s_axis_tx_tready == 1)):
                tdata = int(p.s_axis_tx_tdata)
                tlast = int(p.s_axis_tx_tlast)
                t_1dw = int(p.s_axis_tx_1dw)
                self.rxdata.append(tdata & 0xFFFFFFFF)
                self.rxdata.append(tdata >> 32)
                if (t_1dw == 1) and (tlast == 0):
                    raise TestFailure("RX: Error: 1dw and not tlast")
                if tlast == 1:
                    dw0 = self.rxdata[0]
                    dw1 = self.rxdata[1]
                    dw2 = self.rxdata[2]
                    dw3 = self.rxdata[3]
                    tlptype = (dw0 >> 24) & 0x5F
#.........这里部分代码省略.........
开发者ID:HarmonInstruments,项目名称:hififo,代码行数:103,代码来源:test.py

示例14: __init__

# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import wait [as 别名]
class I2CMasterModelHAL:


    def __init__(self, helperSlave, clockDivider):

        self.wr_scl   = helperSlave.io.scl_rd
        self.wr_sda   = helperSlave.io.sda_rd
        self.rd_scl   = helperSlave.io.scl_wr
        self.rd_sda   = helperSlave.io.sda_wr
        self.clk      = helperSlave.io.clk

        self.sda       = 1
        self.scl       = 1

        self.clockDivider = clockDivider

        self.scl_en       = 0

        self.trigger     = Event()
        self.sclRising   = Event()
        self.sclFalling  = Event()

        self.dataRead    = Event()

        self.freezeBus   = False


    ##########################################################################
    # Start the master
    @cocotb.coroutine
    def startMaster(self, listOperations):

        yield RisingEdge(self.clk)

        self.fork_scl    = cocotb.fork(self._genSCL())
        self.fork_drain  = cocotb.fork(self._manageOpenDrain())
        cocotb.fork(self._runMaster(listOperations))


    ##########################################################################
    # Stop all processes
    def stop(self):

        self.fork_scl.kill()
        self.fork_drain.kill()


    ##########################################################################
    # Execute all operation
    @cocotb.coroutine
    def _runMaster(self, listOperations):

        for index in range(0,len(listOperations)):

            operation = listOperations[index]

            # START -----------------------------------------------------------
            if isinstance(operation, START):
                if index != 0 :
                    yield self.sclRising.wait()

                yield self._genStart()

            # WRITE -----------------------------------------------------------
            elif isinstance(operation, WRITE):
                yield  self._writeData(operation.data)

            # READ ------------------------------------------------------------
            elif isinstance(operation, READ):
                yield self._readData()

            # ACK -------------------------------------------------------------
            elif isinstance(operation, ACK):
                prevOperation = listOperations[index-1]

                yield self.sclFalling.wait()
                self.sda = 1 if isinstance(prevOperation, WRITE) else 0
                yield self.sclRising.wait()
                yield self.sclFalling.wait()
                self.sda = 1

            # NACK ------------------------------------------------------------
            elif isinstance(operation, NACK):

                yield self.sclFalling.wait()
                self.sda  = 1
                yield self.sclRising.wait()
                yield self.sclFalling.wait()

            # STOP ------------------------------------------------------------
            elif isinstance(operation, STOP):
                yield self._genStop()




    ##########################################################################
    # Simulation of the openDrain
    @cocotb.coroutine
    def _manageOpenDrain(self):
#.........这里部分代码省略.........
开发者ID:svancau,项目名称:SpinalHDL,代码行数:103,代码来源:I2CMasterModelHAL.py


注:本文中的cocotb.triggers.Event.wait方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。