| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| """A collections of triggers which a testbench can await.""" |
|
|
| import abc |
| import inspect |
| import warnings |
| from collections.abc import Awaitable |
| from decimal import Decimal |
| from numbers import Real |
| from typing import Any, Coroutine, Optional, TypeVar, Union |
|
|
| import cocotb |
| import cocotb.task |
| from cocotb import _outcomes, simulator |
| from cocotb._py_compat import cached_property |
| from cocotb.handle import LogicObject, ModifiableObject |
| from cocotb.log import SimLog |
| from cocotb.utils import ( |
| ParametrizedSingleton, |
| get_sim_steps, |
| get_time_from_sim_steps, |
| remove_traceback_frames, |
| ) |
|
|
| T = TypeVar("T") |
|
|
|
|
| def _pointer_str(obj): |
| """ |
| Get the memory address of *obj* as used in :meth:`object.__repr__`. |
| |
| This is equivalent to ``sprintf("%p", id(obj))``, but python does not |
| support ``%p``. |
| """ |
| full_repr = object.__repr__(obj) |
| return full_repr.rsplit(" ", 1)[1][:-1] |
|
|
|
|
| class _TriggerException(Exception): |
| pass |
|
|
|
|
| class Trigger(Awaitable): |
| """Base class to derive from.""" |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| __slots__ = ("primed", "__weakref__", "__dict__") |
|
|
| def __init__(self): |
| self.primed = False |
|
|
| @cached_property |
| def log(self): |
| return SimLog("cocotb.%s" % (type(self).__qualname__), id(self)) |
|
|
| @abc.abstractmethod |
| def _prime(self, callback): |
| """Set a callback to be invoked when the trigger fires. |
| |
| The callback will be invoked with a single argument, `self`. |
| |
| Sub-classes must override this, but should end by calling the base class |
| method. |
| |
| .. warning:: |
| Do not call this directly within a :term:`task`. It is intended to be used |
| only by the scheduler. |
| """ |
| self.primed = True |
|
|
| def _unprime(self): |
| """Remove the callback, and perform cleanup if necessary. |
| |
| After being un-primed, a Trigger may be re-primed again in the future. |
| Calling `_unprime` multiple times is allowed, subsequent calls should be |
| a no-op. |
| |
| Sub-classes may override this, but should end by calling the base class |
| method. |
| |
| .. warning:: |
| Do not call this directly within a :term:`task`. It is intended to be used |
| only by the scheduler. |
| """ |
| self.primed = False |
|
|
| def __del__(self): |
| |
| self._unprime() |
|
|
| @property |
| def _outcome(self): |
| """The result that `await this_trigger` produces in a coroutine. |
| |
| The default is to produce the trigger itself, which is done for |
| ease of use with :class:`~cocotb.triggers.First`. |
| """ |
| return _outcomes.Value(self) |
|
|
| def __await__(self): |
| |
| return (yield self) |
|
|
|
|
| class PythonTrigger(Trigger): |
| """Python triggers don't use GPI at all. |
| |
| For example: notification of coroutine completion. |
| """ |
|
|
|
|
| class GPITrigger(Trigger): |
| """Base Trigger class for GPI triggers. |
| |
| Consumes simulation time. |
| """ |
|
|
| __slots__ = ("cbhdl",) |
|
|
| def __init__(self): |
| Trigger.__init__(self) |
|
|
| |
| |
| |
| |
| self.cbhdl = None |
|
|
| def _unprime(self): |
| """Disable a primed trigger, can be re-primed.""" |
| if self.cbhdl is not None: |
| self.cbhdl.deregister() |
| self.cbhdl = None |
| Trigger._unprime(self) |
|
|
|
|
| class Timer(GPITrigger): |
| """Fire after the specified simulation time period has elapsed.""" |
|
|
| round_mode: str = "error" |
|
|
| def __init__( |
| self, |
| time: Union[Real, Decimal], |
| units: str = "step", |
| *, |
| round_mode: Optional[str] = None, |
| ) -> None: |
| """ |
| Args: |
| time: The time value. |
| |
| .. versionchanged:: 1.5.0 |
| Previously this argument was misleadingly called `time_ps`. |
| |
| units: One of |
| ``'step'``, ``'fs'``, ``'ps'``, ``'ns'``, ``'us'``, ``'ms'``, ``'sec'``. |
| When *units* is ``'step'``, |
| the timestep is determined by the simulator (see :make:var:`COCOTB_HDL_TIMEPRECISION`). |
| |
| round_mode (str, optional): |
| String specifying how to handle time values that sit between time steps |
| (one of ``'error'``, ``'round'``, ``'ceil'``, ``'floor'``). |
| |
| Examples: |
| |
| >>> await Timer(100, units='ps') |
| |
| The time can also be a ``float``: |
| |
| >>> await Timer(100e-9, units='sec') |
| |
| which is particularly convenient when working with frequencies: |
| |
| >>> freq = 10e6 # 10 MHz |
| >>> await Timer(1 / freq, units='sec') |
| |
| Other builtin exact numeric types can be used too: |
| |
| >>> from fractions import Fraction |
| >>> await Timer(Fraction(1, 10), units='ns') |
| |
| >>> from decimal import Decimal |
| >>> await Timer(Decimal('100e-9'), units='sec') |
| |
| These are most useful when using computed durations while |
| avoiding floating point inaccuracies. |
| |
| See Also: |
| :func:`~cocotb.utils.get_sim_steps` |
| |
| Raises: |
| ValueError: If a negative value is passed for Timer setup. |
| |
| .. versionchanged:: 1.5 |
| Raise an exception when Timer uses a negative value as it is undefined behavior. |
| Warn for 0 as this will cause erratic behavior in some simulators as well. |
| |
| .. versionchanged:: 1.5 |
| Support ``'step'`` as the *units* argument to mean "simulator time step". |
| |
| .. versionchanged:: 1.6 |
| Support rounding modes. |
| |
| .. versionchanged:: 2.0 |
| Passing ``None`` as the *units* argument was removed, use ``'step'`` instead. |
| |
| .. versionchanged:: 2.0 |
| The ``time_ps`` parameter was removed, use the ``time`` parameter instead. |
| """ |
| GPITrigger.__init__(self) |
| if time <= 0: |
| if time == 0: |
| warnings.warn( |
| "Timer setup with value 0, which might exhibit undefined behavior in some simulators", |
| category=RuntimeWarning, |
| stacklevel=2, |
| ) |
| else: |
| raise ValueError("Timer argument time must not be negative") |
| if round_mode is None: |
| round_mode = type(self).round_mode |
| self.sim_steps = get_sim_steps(time, units, round_mode=round_mode) |
|
|
| def _prime(self, callback): |
| """Register for a timed callback.""" |
| if self.cbhdl is None: |
| self.cbhdl = simulator.register_timed_callback( |
| self.sim_steps, callback, self |
| ) |
| if self.cbhdl is None: |
| raise _TriggerException("Unable set up %s Trigger" % (str(self))) |
| GPITrigger._prime(self, callback) |
|
|
| def __repr__(self): |
| return "<{} of {:1.2f}ps at {}>".format( |
| type(self).__qualname__, |
| get_time_from_sim_steps(self.sim_steps, units="ps"), |
| _pointer_str(self), |
| ) |
|
|
|
|
| |
| |
| class _ParameterizedSingletonAndABC(ParametrizedSingleton, abc.ABCMeta): |
| pass |
|
|
|
|
| class ReadOnly(GPITrigger, metaclass=_ParameterizedSingletonAndABC): |
| """Fires when the current simulation timestep moves to the read-only phase. |
| |
| The read-only phase is entered when the current timestep no longer has any further delta steps. |
| This will be a point where all the signal values are stable as there are no more RTL events scheduled for the timestep. |
| The simulator will not allow scheduling of more events in this timestep. |
| Useful for monitors which need to wait for all processes to execute (both RTL and cocotb) to ensure sampled signal values are final. |
| """ |
|
|
| __slots__ = () |
|
|
| @classmethod |
| def __singleton_key__(cls): |
| return None |
|
|
| def __init__(self): |
| GPITrigger.__init__(self) |
|
|
| def _prime(self, callback): |
| if self.cbhdl is None: |
| self.cbhdl = simulator.register_readonly_callback(callback, self) |
| if self.cbhdl is None: |
| raise _TriggerException("Unable set up %s Trigger" % (str(self))) |
| GPITrigger._prime(self, callback) |
|
|
| def __repr__(self): |
| return f"{type(self).__qualname__}()" |
|
|
|
|
| class ReadWrite(GPITrigger, metaclass=_ParameterizedSingletonAndABC): |
| """Fires when the read-write portion of the simulation cycles is reached.""" |
|
|
| __slots__ = () |
|
|
| @classmethod |
| def __singleton_key__(cls): |
| return None |
|
|
| def __init__(self): |
| GPITrigger.__init__(self) |
|
|
| def _prime(self, callback): |
| if self.cbhdl is None: |
| self.cbhdl = simulator.register_rwsynch_callback(callback, self) |
| if self.cbhdl is None: |
| raise _TriggerException("Unable set up %s Trigger" % (str(self))) |
| GPITrigger._prime(self, callback) |
|
|
| def __repr__(self): |
| return f"{type(self).__qualname__}()" |
|
|
|
|
| class NextTimeStep(GPITrigger, metaclass=_ParameterizedSingletonAndABC): |
| """Fires when the next time step is started.""" |
|
|
| __slots__ = () |
|
|
| @classmethod |
| def __singleton_key__(cls): |
| return None |
|
|
| def __init__(self): |
| GPITrigger.__init__(self) |
|
|
| def _prime(self, callback): |
| if self.cbhdl is None: |
| self.cbhdl = simulator.register_nextstep_callback(callback, self) |
| if self.cbhdl is None: |
| raise _TriggerException("Unable set up %s Trigger" % (str(self))) |
| GPITrigger._prime(self, callback) |
|
|
| def __repr__(self): |
| return f"{type(self).__qualname__}()" |
|
|
|
|
| class _EdgeBase(GPITrigger, metaclass=_ParameterizedSingletonAndABC): |
| """Internal base class that fires on a given edge of a signal.""" |
|
|
| __slots__ = ("signal",) |
|
|
| @classmethod |
| @property |
| def _edge_type(self): |
| """The edge type, as understood by the C code. Must be set in sub-classes.""" |
| raise NotImplementedError |
|
|
| def __init__(self, signal): |
| super().__init__() |
| self.signal = signal |
|
|
| def _prime(self, callback): |
| """Register notification of a value change via a callback""" |
| if self.cbhdl is None: |
| self.cbhdl = simulator.register_value_change_callback( |
| self.signal._handle, callback, type(self)._edge_type, self |
| ) |
| if self.cbhdl is None: |
| raise _TriggerException("Unable set up %s Trigger" % (str(self))) |
| super()._prime(callback) |
|
|
| def __repr__(self): |
| return f"{type(self).__qualname__}({self.signal!r})" |
|
|
|
|
| class RisingEdge(_EdgeBase): |
| """Fires on the rising edge of *signal*, on a transition from ``0`` to ``1``.""" |
|
|
| __slots__ = () |
| _edge_type = 1 |
|
|
| @classmethod |
| def __singleton_key__(cls, signal): |
| if not (isinstance(signal, LogicObject) and len(signal) == 1): |
| raise TypeError("") |
| return signal |
|
|
|
|
| class FallingEdge(_EdgeBase): |
| """Fires on the falling edge of *signal*, on a transition from ``1`` to ``0``.""" |
|
|
| __slots__ = () |
| _edge_type = 2 |
|
|
| @classmethod |
| def __singleton_key__(cls, signal): |
| if not (isinstance(signal, LogicObject) and len(signal) == 1): |
| raise TypeError("") |
| return signal |
|
|
|
|
| class Edge(_EdgeBase): |
| """Fires on any value change of *signal*.""" |
|
|
| __slots__ = () |
| _edge_type = 3 |
|
|
| @classmethod |
| def __singleton_key__(cls, signal): |
| if not isinstance(signal, ModifiableObject): |
| raise TypeError("") |
| return signal |
|
|
|
|
| class _Event(PythonTrigger): |
| """Unique instance used by the Event object. |
| |
| One created for each attempt to wait on the event so that the scheduler |
| can maintain a dictionary of indexing each individual coroutine. |
| |
| FIXME: This will leak - need to use peers to ensure everything is removed |
| """ |
|
|
| def __init__(self, parent): |
| PythonTrigger.__init__(self) |
| self.parent = parent |
|
|
| def _prime(self, callback): |
| self._callback = callback |
| self.parent._prime_trigger(self, callback) |
| Trigger._prime(self, callback) |
|
|
| def __call__(self): |
| self._callback(self) |
|
|
| def __repr__(self): |
| return f"<{self.parent!r}.wait() at {_pointer_str(self)}>" |
|
|
|
|
| class Event: |
| """Event to permit synchronization between two coroutines. |
| |
| Awaiting :meth:`wait()` from one coroutine will block the coroutine until |
| :meth:`set()` is called somewhere else. |
| """ |
|
|
| def __init__(self, name=None): |
| self._pending = [] |
| self.name = name |
| self.fired = False |
| self.data = None |
|
|
| def _prime_trigger(self, trigger, callback): |
| self._pending.append(trigger) |
|
|
| def set(self, data=None): |
| """Wake up all coroutines blocked on this event.""" |
| self.fired = True |
| self.data = data |
|
|
| p = self._pending[:] |
|
|
| self._pending = [] |
|
|
| for trigger in p: |
| trigger() |
|
|
| def wait(self): |
| """Get a trigger which fires when another coroutine sets the event. |
| |
| If the event has already been set, the trigger will fire immediately. |
| |
| To reset the event (and enable the use of ``wait`` again), |
| :meth:`clear` should be called. |
| """ |
| if self.fired: |
| return NullTrigger(name=f"{str(self)}.wait()") |
| return _Event(self) |
|
|
| def clear(self): |
| """Clear this event that has fired. |
| |
| Subsequent calls to :meth:`~cocotb.triggers.Event.wait` will block until |
| :meth:`~cocotb.triggers.Event.set` is called again.""" |
| self.fired = False |
|
|
| def is_set(self) -> bool: |
| """Return true if event has been set""" |
| return self.fired |
|
|
| def __repr__(self): |
| if self.name is None: |
| fmt = "<{0} at {2}>" |
| else: |
| fmt = "<{0} for {1} at {2}>" |
| return fmt.format(type(self).__qualname__, self.name, _pointer_str(self)) |
|
|
|
|
| class _InternalEvent(PythonTrigger): |
| """Event used internally for triggers that need cross-coroutine synchronization. |
| |
| This Event can only be waited on once, by a single coroutine. |
| |
| Provides transparent __repr__ pass-through to the Trigger using this event, |
| providing a better debugging experience. |
| """ |
|
|
| def __init__(self, parent): |
| PythonTrigger.__init__(self) |
| self.parent = parent |
| self._callback = None |
| self.fired = False |
| self.data = None |
|
|
| def _prime(self, callback): |
| if self._callback is not None: |
| raise RuntimeError("This Trigger may only be awaited once") |
| self._callback = callback |
| Trigger._prime(self, callback) |
| if self.fired: |
| self._callback(self) |
|
|
| def set(self, data=None): |
| """Wake up coroutine blocked on this event.""" |
| self.fired = True |
| self.data = data |
|
|
| if self._callback is not None: |
| self._callback(self) |
|
|
| def is_set(self) -> bool: |
| """Return true if event has been set.""" |
| return self.fired |
|
|
| def __await__(self): |
| if self.primed: |
| raise RuntimeError("Only one coroutine may await this Trigger") |
| |
| return (yield self) |
|
|
| def __repr__(self): |
| return repr(self.parent) |
|
|
|
|
| class _Lock(PythonTrigger): |
| """Unique instance used by the Lock object. |
| |
| One created for each attempt to acquire the Lock so that the scheduler |
| can maintain a dictionary of indexing each individual coroutine. |
| |
| FIXME: This will leak - need to use peers to ensure everything is removed. |
| """ |
|
|
| def __init__(self, parent): |
| PythonTrigger.__init__(self) |
| self.parent = parent |
|
|
| def _prime(self, callback): |
| self._callback = callback |
| self.parent._prime_trigger(self, callback) |
| Trigger._prime(self, callback) |
|
|
| def __call__(self): |
| self._callback(self) |
|
|
| def __repr__(self): |
| return f"<{self.parent!r}.acquire() at {_pointer_str(self)}>" |
|
|
|
|
| class Lock: |
| """Lock primitive (not re-entrant). |
| |
| This can be used as:: |
| |
| await lock.acquire() |
| try: |
| # do some stuff |
| finally: |
| lock.release() |
| |
| .. versionchanged:: 1.4 |
| |
| The lock can be used as an asynchronous context manager in an |
| :keyword:`async with` statement:: |
| |
| async with lock: |
| # do some stuff |
| """ |
|
|
| def __init__(self, name=None): |
| self._pending_unprimed = [] |
| self._pending_primed = [] |
| self.name = name |
| self.locked = False |
|
|
| def _prime_trigger(self, trigger, callback): |
| self._pending_unprimed.remove(trigger) |
|
|
| if not self.locked: |
| self.locked = True |
| callback(trigger) |
| else: |
| self._pending_primed.append(trigger) |
|
|
| def acquire(self): |
| """Produce a trigger which fires when the lock is acquired.""" |
| trig = _Lock(self) |
| self._pending_unprimed.append(trig) |
| return trig |
|
|
| def release(self): |
| """Release the lock.""" |
| if not self.locked: |
| raise RuntimeError("Attempt to release an unacquired Lock %s" % (str(self))) |
|
|
| self.locked = False |
|
|
| |
| if not self._pending_primed: |
| return |
|
|
| trigger = self._pending_primed.pop(0) |
| self.locked = True |
| trigger() |
|
|
| def __repr__(self): |
| if self.name is None: |
| fmt = "<{0} [{2} waiting] at {3}>" |
| else: |
| fmt = "<{0} for {1} [{2} waiting] at {3}>" |
| return fmt.format( |
| type(self).__qualname__, |
| self.name, |
| len(self._pending_primed), |
| _pointer_str(self), |
| ) |
|
|
| def __bool__(self): |
| """Provide boolean of a Lock""" |
| return self.locked |
|
|
| async def __aenter__(self): |
| return await self.acquire() |
|
|
| async def __aexit__(self, exc_type, exc, tb): |
| self.release() |
|
|
|
|
| class NullTrigger(Trigger): |
| """Fires immediately. |
| |
| Primarily for internal scheduler use. |
| """ |
|
|
| def __init__(self, name=None, outcome=None): |
| super().__init__() |
| self._callback = None |
| self.name = name |
| self.__outcome = outcome |
|
|
| @property |
| def _outcome(self): |
| if self.__outcome is not None: |
| return self.__outcome |
| return super()._outcome |
|
|
| def _prime(self, callback): |
| callback(self) |
|
|
| def __repr__(self): |
| if self.name is None: |
| fmt = "<{0} at {2}>" |
| else: |
| fmt = "<{0} for {1} at {2}>" |
| return fmt.format(type(self).__qualname__, self.name, _pointer_str(self)) |
|
|
|
|
| class Join(PythonTrigger, metaclass=_ParameterizedSingletonAndABC): |
| r"""Fires when a task completes. |
| |
| The result of blocking on the trigger can be used to get the coroutine |
| result:: |
| |
| async def coro_inner(): |
| await Timer(1, units='ns') |
| return "Hello world" |
| |
| task = cocotb.start_soon(coro_inner()) |
| result = await Join(task) |
| assert result == "Hello world" |
| |
| If the coroutine threw an exception, the :keyword:`await` will re-raise it. |
| |
| """ |
|
|
| __slots__ = ("_coroutine",) |
|
|
| @classmethod |
| def __singleton_key__(cls, coroutine): |
| return coroutine |
|
|
| def __init__(self, coroutine): |
| super().__init__() |
| self._coroutine = coroutine |
|
|
| @property |
| def _outcome(self): |
| return self._coroutine._outcome |
|
|
| @property |
| def retval(self): |
| """The return value of the joined coroutine. |
| |
| .. note:: |
| Typically there is no need to use this attribute - the |
| following code samples are equivalent:: |
| |
| task = cocotb.start_soon(mycoro()) |
| j = Join(task) |
| await j |
| result = j.retval |
| |
| :: |
| |
| task = cocotb.start_soon(mycoro()) |
| result = await Join(task) |
| """ |
| return self._coroutine.result() |
|
|
| def _prime(self, callback): |
| if self._coroutine.done(): |
| callback(self) |
| else: |
| super()._prime(callback) |
|
|
| def __repr__(self): |
| return f"{type(self).__qualname__}({self._coroutine!s})" |
|
|
|
|
| class Waitable(Awaitable): |
| """ |
| Base class for trigger-like objects implemented using coroutines. |
| |
| This converts a `_wait` abstract method into a suitable `__await__`. |
| """ |
|
|
| __slots__ = () |
|
|
| async def _wait(self): |
| """ |
| Should be implemented by the sub-class. Called by `await self` to |
| convert the waitable object into a coroutine. |
| """ |
| raise NotImplementedError |
|
|
| def __await__(self): |
| return self._wait().__await__() |
|
|
|
|
| class _AggregateWaitable(Waitable): |
| """ |
| Base class for Waitables that take mutiple triggers in their constructor |
| """ |
|
|
| __slots__ = ("triggers",) |
|
|
| def __init__(self, *triggers): |
| self.triggers = triggers |
|
|
| |
| |
| allowed_types = (Trigger, Waitable, cocotb.task.Task) |
| for trigger in self.triggers: |
| if not isinstance(trigger, allowed_types): |
| raise TypeError( |
| "All triggers must be instances of Trigger! Got: {}".format( |
| type(trigger).__qualname__ |
| ) |
| ) |
|
|
| def __repr__(self): |
| |
| |
| return "{}({})".format( |
| type(self).__qualname__, |
| ", ".join( |
| repr(Join(t)) if isinstance(t, cocotb.task.Task) else repr(t) |
| for t in self.triggers |
| ), |
| ) |
|
|
|
|
| async def _wait_callback(trigger, callback): |
| """ |
| Wait for a trigger, and call `callback` with the outcome of the await. |
| """ |
| try: |
| ret = _outcomes.Value(await trigger) |
| except BaseException as exc: |
| |
| ret = _outcomes.Error(remove_traceback_frames(exc, ["_wait_callback"])) |
| callback(ret) |
|
|
|
|
| class Combine(_AggregateWaitable): |
| """ |
| Fires when all of *triggers* have fired. |
| |
| Like most triggers, this simply returns itself. |
| |
| This is similar to Verilog's ``join``. |
| """ |
|
|
| __slots__ = () |
|
|
| async def _wait(self): |
| waiters = [] |
| e = _InternalEvent(self) |
| triggers = list(self.triggers) |
|
|
| |
| for t in triggers: |
| |
| def on_done(ret, t=t): |
| triggers.remove(t) |
| if not triggers: |
| e.set() |
| ret.get() |
|
|
| waiters.append(cocotb.start_soon(_wait_callback(t, on_done))) |
|
|
| |
| await e |
| return self |
|
|
|
|
| class First(_AggregateWaitable): |
| """ |
| Fires when the first trigger in *triggers* fires. |
| |
| Returns the result of the trigger that fired. |
| |
| This is similar to Verilog's ``join_any``. |
| |
| .. note:: |
| The event loop is single threaded, so while events may be simultaneous |
| in simulation time, they can never be simultaneous in real time. |
| For this reason, the value of ``t_ret is t1`` in the following example |
| is implementation-defined, and will vary by simulator:: |
| |
| t1 = Timer(10, units='ps') |
| t2 = Timer(10, units='ps') |
| t_ret = await First(t1, t2) |
| |
| .. note:: |
| In the old-style :ref:`generator-based coroutines <yield-syntax>`, ``t = yield [a, b]`` was another spelling of |
| ``t = yield First(a, b)``. This spelling is no longer available when using :keyword:`await`-based |
| coroutines. |
| """ |
|
|
| __slots__ = () |
|
|
| async def _wait(self): |
| waiters = [] |
| e = _InternalEvent(self) |
| completed = [] |
| |
| for t in self.triggers: |
|
|
| def on_done(ret): |
| completed.append(ret) |
| e.set() |
|
|
| waiters.append(cocotb.start_soon(_wait_callback(t, on_done))) |
|
|
| |
| await e |
|
|
| |
| |
| |
| for w in waiters: |
| w.kill() |
|
|
| |
| |
| |
| |
| |
| first_trigger = NullTrigger(outcome=completed[0]) |
| return await first_trigger |
|
|
|
|
| class ClockCycles(Waitable): |
| """Fires after *num_cycles* transitions of *signal* from ``0`` to ``1``.""" |
|
|
| def __init__(self, signal, num_cycles, rising=True): |
| """ |
| Args: |
| signal: The signal to monitor. |
| num_cycles (int): The number of cycles to count. |
| rising (bool, optional): If ``True``, the default, count rising edges. |
| Otherwise, count falling edges. |
| """ |
| self.signal = signal |
| self.num_cycles = num_cycles |
| if rising is True: |
| self._type = RisingEdge |
| else: |
| self._type = FallingEdge |
|
|
| async def _wait(self): |
| trigger = self._type(self.signal) |
| for _ in range(self.num_cycles): |
| await trigger |
| return self |
|
|
| def __repr__(self): |
| |
| |
| if self._type is RisingEdge: |
| fmt = "{}({!r}, {!r})" |
| else: |
| fmt = "{}({!r}, {!r}, rising=False)" |
| return fmt.format(type(self).__qualname__, self.signal, self.num_cycles) |
|
|
|
|
| async def with_timeout( |
| trigger: Union[Trigger, Waitable, "cocotb.task.Task", Coroutine[Any, Any, T]], |
| timeout_time: Union[float, Decimal], |
| timeout_unit: str = "step", |
| round_mode: Optional[str] = None, |
| ) -> T: |
| r""" |
| Waits on triggers or coroutines, throws an exception if it waits longer than the given time. |
| |
| When a :term:`python:coroutine` is passed, |
| the callee coroutine is started, |
| the caller blocks until the callee completes, |
| and the callee's result is returned to the caller. |
| If timeout occurs, the callee is killed |
| and :exc:`SimTimeoutError` is raised. |
| |
| When an unstarted :class:`~cocotb.coroutine`\ is passed, |
| the callee coroutine is started, |
| the caller blocks until the callee completes, |
| and the callee's result is returned to the caller. |
| If timeout occurs, the callee `continues to run` |
| and :exc:`SimTimeoutError` is raised. |
| |
| When a :term:`task` is passed, |
| the caller blocks until the callee completes |
| and the callee's result is returned to the caller. |
| If timeout occurs, the callee `continues to run` |
| and :exc:`SimTimeoutError` is raised. |
| |
| If a :class:`~cocotb.triggers.Trigger` or :class:`~cocotb.triggers.Waitable` is passed, |
| the caller blocks until the trigger fires, |
| and the trigger is returned to the caller. |
| If timeout occurs, the trigger is cancelled |
| and :exc:`SimTimeoutError` is raised. |
| |
| Usage: |
| |
| .. code-block:: python |
| |
| await with_timeout(coro, 100, 'ns') |
| await with_timeout(First(coro, event.wait()), 100, 'ns') |
| |
| Args: |
| trigger (:class:`~cocotb.triggers.Trigger`, :class:`~cocotb.triggers.Waitable`, :class:`~cocotb.task.Task`, or :term:`python:coroutine`): |
| A single object that could be right of an :keyword:`await` expression in cocotb. |
| timeout_time (numbers.Real or decimal.Decimal): |
| Simulation time duration before timeout occurs. |
| timeout_unit (str, optional): |
| Units of timeout_time, accepts any units that :class:`~cocotb.triggers.Timer` does. |
| round_mode (str, optional): |
| String specifying how to handle time values that sit between time steps |
| (one of ``'error'``, ``'round'``, ``'ceil'``, ``'floor'``). |
| |
| Returns: |
| First trigger that completed if timeout did not occur. |
| |
| Raises: |
| :exc:`SimTimeoutError`: If timeout occurs. |
| |
| .. versionadded:: 1.3 |
| |
| .. versionchanged:: 1.7.0 |
| Support passing :term:`python:coroutine`\ s. |
| |
| .. versionchanged:: 2.0 |
| Passing ``None`` as the *timeout_unit* argument was removed, use ``'step'`` instead. |
| """ |
| if inspect.iscoroutine(trigger): |
| trigger = cocotb.start_soon(trigger) |
| shielded = False |
| else: |
| shielded = True |
| timeout_timer = cocotb.triggers.Timer( |
| timeout_time, timeout_unit, round_mode=round_mode |
| ) |
| res = await First(timeout_timer, trigger) |
| if res is timeout_timer: |
| if not shielded: |
| trigger.kill() |
| raise cocotb.result.SimTimeoutError |
| else: |
| return res |
|
|