本文整理汇总了Python中cocotb.triggers.Event.set方法的典型用法代码示例。如果您正苦于以下问题:Python Event.set方法的具体用法?Python Event.set怎么用?Python Event.set使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类cocotb.triggers.Event
的用法示例。
在下文中一共展示了Event.set方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_locker
# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import set [as 别名]
class test_locker(object):
def __init__(self):
self.in_event = None
self.out_event = Event()
self.result = None
def set_in(self):
self.in_event.set()
def set_out(self):
self.out_event.set()
示例2: test_drv
# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import set [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()
示例3: AvalonMaster
# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import set [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.
"""
#.........这里部分代码省略.........
示例4: Driver
# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import set [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()
#.........这里部分代码省略.........
示例5: AvalonMaster
# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import set [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)
#.........这里部分代码省略.........
示例6: Driver
# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import set [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
#.........这里部分代码省略.........
示例7: __init__
# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import set [as 别名]
class I2CSlaveModelHAL:
def __init__(self, helperMaster ): # initMemory = dict()):
self.startEvent = Event()
self.stopEvent = Event()
self.dataRxEvent = Event()
self.dataTXEvent = Event()
self.sda_rd = helperMaster.io.sda_wr
self.sda_wr = helperMaster.io.sda_rd
self.scl_rd = helperMaster.io.scl_wr
self.scl_wr = helperMaster.io.scl_rd
self.resetn = helperMaster.io.resetn
self.clk = helperMaster.io.clk
self.sda = 1
self.scl = 1
##########################################################################
# Launch all slave process
@cocotb.coroutine
def startSlave(self,listOperations):
yield RisingEdge(self.clk)
self.fork_drain = cocotb.fork(self._manageSDA())
self.fork_start = cocotb.fork(self._startDetection())
self.fork_stop = cocotb.fork(self._stopDetection())
cocotb.fork(self._runSlave(listOperations))
##########################################################################
# Stop all processes
def stop(self):
self.fork_drain.kill()
self.fork_start.kill()
self.fork_stop.kill()
##########################################################################
# Slave simulation
@cocotb.coroutine
def _runSlave(self, listOperations):
for index in range(0,len(listOperations)):
operation = listOperations[index]
if isinstance(operation, START):
if index != 0:
yield FallingEdge(self.scl_wr)
yield FallingEdge(self.scl_wr)
else:
yield FallingEdge(self.scl_wr)
elif isinstance(operation, WRITE):
yield self._writeData(operation.enCollision)
elif isinstance(operation, READ):
yield self._readData(operation.data)
elif isinstance(operation, ACK):
prevOperation = listOperations[index-1]
self.sda = 0 if isinstance(prevOperation, WRITE) else 1
yield FallingEdge(self.scl_rd)
self.sda = 1
elif isinstance(operation, ACK):
self.sda = 1
yield FallingEdge(self.scl_wr)
self.sda = 1
elif isinstance(operation, STOP):
pass
##########################################################################
# Simulate an open drain pin
@cocotb.coroutine
def _manageSDA(self):
while True:
yield RisingEdge(self.clk)
if int(self.sda_rd) == 0:
self.sda_wr <= 0
else:
self.sda_wr <= self.sda
if int(self.scl_rd) == 0 :
#.........这里部分代码省略.........
示例8: PCIe_host
# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import set [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
#.........这里部分代码省略.........
示例9: AD9361
# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import set [as 别名]
class AD9361(BusDriver):
'''
classdocs
'''
def __init__(self, dut, rx_channels=1, tx_channels=1,
tx_clock_half_period=16276, rx_clock_half_period=16276,
loopback_queue_maxlen=16):
'''
Constructor
'''
self.dut = dut
self.tx_clock_half_period = tx_clock_half_period
self.rx_clock_half_period = rx_clock_half_period
self.rx_frame_asserted = False
self.tx_frame_asserted = False
self.lbqi = deque()
self.lbqq = deque()
cocotb.fork(self._rx_clock())
self.got_tx = Event("Got tx event")
@cocotb.coroutine
def _rx_clock(self):
t = Timer(self.rx_clock_half_period)
while True:
self.dut.rx_clk_in_p <= 1
self.dut.rx_clk_in_n <= 0
yield t
self.dut.rx_clk_in_p <= 0
self.dut.rx_clk_in_n <= 1
yield t
def send_data(self, i_data, q_data, i_data2=None, q_data2=None,
binaryRepresentation=BinaryRepresentation.TWOS_COMPLEMENT):
print binaryRepresentation
cocotb.fork(self.rx_data_to_ad9361(i_data, q_data, i_data2, q_data2,
binaryRepresentation))
@cocotb.coroutine
def rx_data_to_ad9361(self, i_data, q_data, i_data2=None, q_data2=None,
binaryRepresentation=BinaryRepresentation.TWOS_COMPLEMENT):
i_bin_val = BinaryValue(bits=12, bigEndian=False,
binaryRepresentation=binaryRepresentation)
q_bin_val = BinaryValue(bits=12, bigEndian=False,
binaryRepresentation=binaryRepresentation)
index = 0
if i_data2 is None and q_data2 is None:
while True:
yield RisingEdge(self.dut.rx_clk_in_p)
if self.rx_frame_asserted:
self.dut.rx_data_in_p <= i_bin_val[5:0]
self.dut.rx_data_in_n <= ~i_bin_val[5:0]
self.rx_frame_asserted = False
self.dut.rx_frame_in_p <= 0
self.dut.rx_frame_in_n <= 1
else:
if index < len(i_data):
i_bin_val.set_value(i_data[index])
q_bin_val.set_value(q_data[index])
index += 1
else:
return
self.dut.rx_data_in_p <= i_bin_val[11:6]
self.dut.rx_data_in_n <= ~i_bin_val[11:6]
self.rx_frame_asserted = True
self.dut.rx_frame_in_p <= 1
self.dut.rx_frame_in_n <= 0
yield RisingEdge(self.dut.rx_clk_in_n)
if self.rx_frame_asserted:
self.dut.rx_data_in_p <= q_bin_val[11:6]
self.dut.rx_data_in_n <= ~q_bin_val[11:6]
else:
self.dut.rx_data_in_p <= q_bin_val[5:0]
self.dut.rx_data_in_n <= ~q_bin_val[5:0]
else:
I_SEND_HIGH = True
Q_SEND_HIGH = True
channel = 1
while True:
yield RisingEdge(self.dut.rx_clk_in_p)
if I_SEND_HIGH:
self.dut.rx_data_in_p <= i_bin_val[11:6]
self.dut.rx_data_in_n <= ~i_bin_val[11:6]
I_SEND_HIGH = False
if channel == 1:
self.dut.rx_frame_in_p <= 1
self.dut.rx_frame_in_n <= 0
elif channel == 2:
self.dut.rx_frame_in_p <= 0
self.dut.rx_frame_in_n <= 1
else:
self.dut.rx_data_in_p <= i_bin_val[5:0]
self.dut.rx_data_in_n <= ~i_bin_val[5:0]
I_SEND_HIGH = True
yield RisingEdge(self.dut.rx_clk_in_n)
if Q_SEND_HIGH:
self.dut.rx_data_in_p <= q_bin_val[5:0]
self.dut.rx_data_in_n <= ~q_bin_val[5:0]
Q_SEND_HIGH = False
else:
#.........这里部分代码省略.........
示例10: Scheduler
# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import set [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()
#.........这里部分代码省略.........
示例11: AD9361
# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import set [as 别名]
class AD9361(BusDriver):
"""Driver for the AD9361 RF Transceiver."""
def __init__(self, dut, rx_channels=1, tx_channels=1,
tx_clock_half_period=16276, rx_clock_half_period=16276,
loopback_queue_maxlen=16):
self.dut = dut
self.tx_clock_half_period = tx_clock_half_period
self.rx_clock_half_period = rx_clock_half_period
self.rx_frame_asserted = False
self.tx_frame_asserted = False
self.lbqi = deque()
self.lbqq = deque()
cocotb.fork(self._rx_clock())
self.got_tx = Event("Got tx event")
@cocotb.coroutine
def _rx_clock(self):
t = Timer(self.rx_clock_half_period)
while True:
self.dut.rx_clk_in_p <= 1
self.dut.rx_clk_in_n <= 0
yield t
self.dut.rx_clk_in_p <= 0
self.dut.rx_clk_in_n <= 1
yield t
def send_data(self, i_data, q_data, i_data2=None, q_data2=None,
binaryRepresentation=BinaryRepresentation.TWOS_COMPLEMENT):
"""Forks the ``rx_data_to_ad9361`` coroutine to send data.
Args:
i_data (int): Data of the I0 channel.
q_data (int): Data of the Q0 channel.
i_data2 (int, optional): Data of the I1 channel.
q_data2 (int, optional): Data of the Q1 channel.
binaryRepresentation (BinaryRepresentation): The representation of the binary value.
Default is :any:`TWOS_COMPLEMENT`.
"""
print(binaryRepresentation)
cocotb.fork(self.rx_data_to_ad9361(i_data, q_data, i_data2, q_data2,
binaryRepresentation))
@cocotb.coroutine
def rx_data_to_ad9361(self, i_data, q_data, i_data2=None, q_data2=None,
binaryRepresentation=BinaryRepresentation.TWOS_COMPLEMENT):
"""Receive data to AD9361.
This is a coroutine.
Args:
i_data (int): Data of the I0 channel.
q_data (int): Data of the Q0 channel.
i_data2 (int, optional): Data of the I1 channel.
q_data2 (int, optional): Data of the Q1 channel.
binaryRepresentation (BinaryRepresentation): The representation of the binary value.
Default is :any:`TWOS_COMPLEMENT`.
"""
i_bin_val = BinaryValue(n_bits=12, bigEndian=False,
binaryRepresentation=binaryRepresentation)
q_bin_val = BinaryValue(n_bits=12, bigEndian=False,
binaryRepresentation=binaryRepresentation)
index = 0
if i_data2 is None and q_data2 is None:
while True:
yield RisingEdge(self.dut.rx_clk_in_p)
if self.rx_frame_asserted:
self.dut.rx_data_in_p <= i_bin_val[5:0]
self.dut.rx_data_in_n <= ~i_bin_val[5:0]
self.rx_frame_asserted = False
self.dut.rx_frame_in_p <= 0
self.dut.rx_frame_in_n <= 1
else:
if index < len(i_data):
i_bin_val.set_value(i_data[index])
q_bin_val.set_value(q_data[index])
index += 1
else:
return
self.dut.rx_data_in_p <= i_bin_val[11:6]
self.dut.rx_data_in_n <= ~i_bin_val[11:6]
self.rx_frame_asserted = True
self.dut.rx_frame_in_p <= 1
self.dut.rx_frame_in_n <= 0
yield RisingEdge(self.dut.rx_clk_in_n)
if self.rx_frame_asserted:
self.dut.rx_data_in_p <= q_bin_val[11:6]
self.dut.rx_data_in_n <= ~q_bin_val[11:6]
else:
self.dut.rx_data_in_p <= q_bin_val[5:0]
self.dut.rx_data_in_n <= ~q_bin_val[5:0]
else:
I_SEND_HIGH = True
Q_SEND_HIGH = True
channel = 1
while True:
yield RisingEdge(self.dut.rx_clk_in_p)
if I_SEND_HIGH:
self.dut.rx_data_in_p <= i_bin_val[11:6]
self.dut.rx_data_in_n <= ~i_bin_val[11:6]
#.........这里部分代码省略.........
示例12: WishboneMaster
# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import set [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
#.........这里部分代码省略.........
示例13: __init__
# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import set [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
#.........这里部分代码省略.........
示例14: AvalonMaster
# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import set [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()
示例15: OPBMaster
# 需要导入模块: from cocotb.triggers import Event [as 别名]
# 或者: from cocotb.triggers.Event import set [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()