~ruther/vhdl-spi-2

ref: 5755b1cc51ec1b9660c5a76b0c30b2cab48caac5 vhdl-spi-2/hdl_spi/tests/test_spi_masterslave.py -rw-r--r-- 17.4 KiB
5755b1cc — Rutherther fix: divisors list had excess element 3 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
import os
import sys
from pathlib import Path
import logging
import random

from dataclasses import dataclass

import cocotb
import cocotb.handle
from cocotb.queue import Queue
from cocotb.clock import Clock
from cocotb.triggers import Trigger, First, Event, Timer, RisingEdge, Edge, FallingEdge
from cocotb_tools.runner import get_runner

if cocotb.simulator.is_running():
    from spi_models import SpiInterface, SpiConfig, SpiSlave

async def init(dut, master: int = 1, tx_en: int = 1):
    dut._log.info("Init started!")
    dut.miso_i.value = 0;
    dut.rst_in.value = 0;
    dut.lsbfirst_i.value = 0;
    dut.clock_polarity_i.value = 0;
    dut.clock_phase_i.value = 0;
    dut.size_sel_i.value = 0;
    dut.div_sel_i.value = 0;
    dut.pulse_csn_i.value = 0;
    dut.rx_block_on_full_i.value = 0;
    dut.rx_ready_i.value = 0;
    dut.tx_valid_i.value = 0;
    dut.clear_lost_rx_data_i.value = 0;

    dut.rx_en_i.value = 1;
    dut.tx_en_i.value = 1;

    dut.master_i.value = 1;
    dut.en_i.value = 1;

    await FallingEdge(dut.clk_i)
    await FallingEdge(dut.clk_i)

    # Release reset
    dut.rst_in.value = 1;

    await FallingEdge(dut.clk_i)
    await FallingEdge(dut.clk_i)

    dut._log.info("Init done!")

class DutDriver:
    def __init__(self, dut):
        self.dut = dut
        self._log = logging.getLogger("cocotb.DutDriver")
        self._received = Queue()
        self._sync = Event()
        self._auto_receive = False
        self._set_ready = False

    async def receive_data(self):
        if int(self.dut.rx_valid_o.value) != 1:
          self._log.error("RX is not valid when receiving data was requested")
          raise Exception("RX is not valid when receiving data was requested")
        await FallingEdge(self.dut.clk_i)
        self.dut.rx_ready_i.value = 1
        data = self.dut.rx_data_o.value

        await FallingEdge(self.dut.clk_i)
        if int(self.dut.rx_valid_o.value) != 0:
          self._log.error("RX data stayed valid after receiving!")
          raise Exception("RX data stayed valid after receiving!")
        self.dut.rx_ready_i.value = 0

        return data

    async def send_data(self, data):
        if int(self.dut.tx_ready_o.value) != 1:
          self._log.error("TX is not ready when sending data was requested")
        await FallingEdge(self.dut.clk_i)
        self.dut.tx_valid_i.value = 1
        self.dut.tx_data_i.value = data
        await FallingEdge(self.dut.clk_i)
        self.dut.tx_valid_i.value = 0
        if int(self.dut.tx_ready_o.value) != 0:
          self._log.error("TX stayed ready after requesting send of data!")

    async def send_data_wait(self, data):
        await FallingEdge(self.dut.clk_i)
        self.dut.tx_valid_i.value = 1
        self.dut.tx_data_i.value = data
        clk_falling = FallingEdge(self.dut.clk_i)
        tx_ready_falling = FallingEdge(self.dut.tx_ready_o)
        res = await First(clk_falling, tx_ready_falling)

        if res == clk_falling:
            # TODO timeout
            await RisingEdge(self.dut.tx_ready_o)

        await RisingEdge(self.dut.clk_i)
            # now the data were registered
            # (note that it's ready, not confirmation
            # so data are sampled only after it actually is ready
            # that means the next clock cycle from when ready went to 1)

        self.dut.tx_valid_i.value = 0

    async def auto_receive(self, receive: bool = True, set_ready: bool = True, waiting_clocks: int = 0):
        self._auto_receive = receive
        self._set_ready = set_ready
        self._waiting_clocks = waiting_clocks
        self._sync.set()

    async def received_data(self):
        if self._received.empty():
            return None

        return await self._received.get()

    async def coroutine(self):
        while True:
            if not self._auto_receive:
                self.dut.rx_ready_i.value = 0
                await self._sync.wait()
                self._sync.clear()
                if not self._auto_receive:
                    continue

            if self._set_ready and self._waiting_clocks == 0:
                self.dut.rx_ready_i.value = 1

            await RisingEdge(self.dut.rx_valid_o)
            if int(self.dut.rx_valid_o.value) == 1:
                await self._received.put(self.dut.rx_data_o.value)

            if self._waiting_clocks > 0:
                for i in range(self._waiting_clocks):
                    await FallingEdge(self.dut.clk_i)
                self.dut.rx_ready_i.value = 1
                await FallingEdge(self.dut.clk_i)
                self.dut.rx_ready_i.value = 0

            should_lose_data = not self._set_ready and self.dut.tx_valid_i.value == 1
            await RisingEdge(self.dut.clk_i)
            await RisingEdge(self.dut.clk_i)
            if should_lose_data and int(self.dut.err_lost_rx_data_o.value) != 1:
                self._log.error("Didn't get err lost rx data after rx valid")

            if should_lose_data:
                self.dut.clear_lost_rx_data_i.value = 1
                await RisingEdge(self.dut.clk_i)
                await FallingEdge(self.dut.clk_i)
                self.dut.clear_lost_rx_data_i.value = 0
                if int(self.dut.err_lost_rx_data_o.value) != 0:
                    self._log.error("Could not clear err lost rx data")


@cocotb.test()
async def single_transmit(dut):
    clk = Clock(dut.clk_i, 5, "ns")
    interface = SpiInterface(dut.csn_o, dut.sck_o, dut.miso_i, dut.mosi_o)
    config = SpiConfig(8, RisingEdge, FallingEdge, 10, "ns")
    slave = SpiSlave(interface, config)
    driver = DutDriver(dut)

    await cocotb.start(clk.start())

    await init(dut)

    await cocotb.start(slave.coroutine())
    await cocotb.start(driver.coroutine())

    # From slave point of view
    rx = random.randint(0, 255)
    tx = random.randint(0, 255)

    await slave.send_data(tx, 8)
    await slave.expect_transaction_in(15, "ns")

    await driver.send_data(rx)

    await slave.wait_all()

    dut_received = await driver.receive_data()
    assert int(dut_received) & 0xFF == tx

    # Wait a few clocks, rx data should still stay valid!
    await FallingEdge(dut.clk_i)
    await FallingEdge(dut.clk_i)
    await FallingEdge(dut.clk_i)
    await FallingEdge(dut.clk_i)

    received = await slave.received_data()
    assert received & 0xFF == rx

    await Timer(100, "ns")

@cocotb.test()
async def lsbfirst(dut):
    clk = Clock(dut.clk_i, 5, "ns")
    interface = SpiInterface(dut.csn_o, dut.sck_o, dut.miso_i, dut.mosi_o)
    config = SpiConfig(8, RisingEdge, FallingEdge, 10, "ns")
    slave = SpiSlave(interface, config)
    driver = DutDriver(dut)

    await cocotb.start(clk.start())

    await init(dut)
    dut.lsbfirst_i.value = 1
    await FallingEdge(dut.clk_i)

    await cocotb.start(slave.coroutine())
    await cocotb.start(driver.coroutine())

    # From slave point of view
    rx = random.randint(0, 255)
    tx = random.randint(0, 255)


    def reverse_bits(num, bits):
        result = 0
        for i in range(bits):
            result = (result << 1) | (num & 1)
            num >>= 1
        return result

    rx_reversed = reverse_bits(rx, 8)
    tx_reversed = reverse_bits(tx, 8)

    await slave.send_data(tx, 8)
    await slave.expect_transaction_in(15, "ns")

    await driver.send_data(rx)

    await slave.wait_all()

    dut_received = await driver.receive_data()
    assert (int(dut_received) >> 8) & 0xFF == tx_reversed

    # Wait a few clocks, rx data should still stay valid!
    await FallingEdge(dut.clk_i)
    await FallingEdge(dut.clk_i)
    await FallingEdge(dut.clk_i)
    await FallingEdge(dut.clk_i)

    received = await slave.received_data()
    assert received & 0xFF == rx_reversed

    await Timer(100, "ns")

@cocotb.test()
async def rx_tx_disabled(dut):
    clk = Clock(dut.clk_i, 5, "ns")
    interface = SpiInterface(dut.csn_o, dut.sck_o, dut.miso_i, dut.mosi_o)
    config = SpiConfig(8, RisingEdge, FallingEdge, 10, "ns")
    slave = SpiSlave(interface, config)
    driver = DutDriver(dut)

    await cocotb.start(clk.start())

    await init(dut)
    dut.rx_en_i.value = 0
    dut.tx_en_i.value = 1
    # Try with rx blocking, it should not matter.
    dut.rx_block_on_full_i.value = 1
    await FallingEdge(dut.clk_i)

    await cocotb.start(slave.coroutine())
    await cocotb.start(driver.coroutine())

    # From slave point of view
    rx = random.randint(0, 255)
    tx = random.randint(0, 255)

    await slave.send_data(tx, 8)
    await slave.expect_transaction_in(15, "ns")

    await driver.send_data(rx)

    await slave.wait_all()

    # RX should be idle
    assert int(dut.rx_valid_o.value) == 0

    # TX should be working
    received = await slave.received_data()
    assert received & 0xFF == rx

    # Second transaction should be fine.
    await slave.send_data(tx, 8)
    await slave.expect_transaction_in(15, "ns")
    await driver.send_data(rx)
    await slave.wait_all()

    # RX should be idle
    assert int(dut.rx_valid_o.value) == 0

    # TX should be working
    received = await slave.received_data()
    assert received & 0xFF == rx

    # Now switch to tx disabled. mosi should stay 'Z'
    await FallingEdge(dut.clk_i)
    dut.rx_en_i.value = 1
    dut.tx_en_i.value = 0
    await FallingEdge(dut.clk_i)
    await FallingEdge(dut.clk_i)

    assert int(dut.mosi_t.value) == 0

    await slave.send_data(tx, 8)
    await slave.expect_transaction_in(15, "ns")
    # Although nothing is actually transmitted, still
    # tx valid should be asserted for reception to begin
    await driver.send_data(rx)

    timeout = Timer(10 * (8 + 5), "ns")
    mosi_event = Edge(dut.mosi_t)

    res = await First(timeout, mosi_event)
    if res == mosi_event:
        raise Exception("Mosi has changed even though tx is disabled!")

    await slave.wait_all()

    # RX should have the data
    data = await driver.receive_data()
    assert int(data) & 0xFF == tx

    await Timer(100, "ns")

async def perform_multiple_transmits(count, dut, slave, driver, size = 8):
    tx_data = [random.randint(0, 2**size - 1) for i in range(count)]
    rx_data = [random.randint(0, 2**size - 1) for i in range(count)]

    for tx in tx_data:
        await slave.send_data(tx, size)
        dut._log.info(f"Sending Data from slave: {tx}")

    dut._log.info("To expect transaction")
    await slave.expect_transaction_in(30, "ns")

    for rx in rx_data:
        dut._log.info(f"Sending Data from master: {rx}")
        await driver.send_data_wait(rx)

    await slave.wait_all()

    mask = 0
    for i in range(size):
        mask |= 1 << i

    # Checks
    for tx in tx_data:
        dut_received = await driver.received_data()
        assert int(dut_received) & mask == tx

    for rx in rx_data:
        received = await slave.received_data()
        assert received & mask == rx

@cocotb.test()
async def multiple_transmits(dut):
    clk = Clock(dut.clk_i, 5, "ns")
    interface = SpiInterface(dut.csn_o, dut.sck_o, dut.miso_i, dut.mosi_o)
    config = SpiConfig(8, RisingEdge, FallingEdge, 10, "ns")
    slave = SpiSlave(interface, config)
    driver = DutDriver(dut)

    await cocotb.start(clk.start())

    await init(dut)

    await cocotb.start(slave.coroutine())
    await cocotb.start(driver.coroutine())

    await driver.auto_receive()

    count = 5
    await perform_multiple_transmits(count, dut, slave, driver)

    await Timer(100, "ns")

@cocotb.test()
async def lost_rx_data(dut):
    clk = Clock(dut.clk_i, 5, "ns")
    interface = SpiInterface(dut.csn_o, dut.sck_o, dut.miso_i, dut.mosi_o)
    config = SpiConfig(8, RisingEdge, FallingEdge, 10, "ns")
    slave = SpiSlave(interface, config)
    driver = DutDriver(dut)

    await cocotb.start(clk.start())

    await init(dut)

    await cocotb.start(slave.coroutine())
    await cocotb.start(driver.coroutine())

    # Do not confirm reception of data. That will auto check
    # if lost is asserted and cleared appropriately.
    await driver.auto_receive(True, False)

    count = 5
    await perform_multiple_transmits(count, dut, slave, driver)

    await Timer(100, "ns")

@cocotb.test()
async def different_clock(dut):
    clk = Clock(dut.clk_i, 5, "ns")
    interface = SpiInterface(dut.csn_o, dut.sck_o, dut.miso_i, dut.mosi_o)
    config = SpiConfig(8, RisingEdge, FallingEdge, 20, "ns")
    slave = SpiSlave(interface, config)
    driver = DutDriver(dut)

    await cocotb.start(clk.start())

    await init(dut)
    dut.div_sel_i.value = 1 # divide by 4

    await cocotb.start(slave.coroutine())
    await cocotb.start(driver.coroutine())

    await driver.auto_receive()

    count = 5
    await perform_multiple_transmits(count, dut, slave, driver)

    await Timer(100, "ns")

@cocotb.test()
async def inverted_clock(dut):
    clk = Clock(dut.clk_i, 5, "ns")
    interface = SpiInterface(dut.csn_o, dut.sck_o, dut.miso_i, dut.mosi_o)
    config = SpiConfig(8, RisingEdge, FallingEdge, 20, "ns")
    slave = SpiSlave(interface, config)
    driver = DutDriver(dut)

    await cocotb.start(clk.start())

    await init(dut)
    dut.clock_phase_i.value = 1
    dut.clock_polarity_i.value = 1

    await cocotb.start(slave.coroutine())
    await cocotb.start(driver.coroutine())

    await driver.auto_receive()

    count = 5
    await perform_multiple_transmits(count, dut, slave, driver)

    await Timer(100, "ns")

@cocotb.test()
async def shifted_inverted_clock(dut):
    clk = Clock(dut.clk_i, 5, "ns")
    interface = SpiInterface(dut.csn_o, dut.sck_o, dut.miso_i, dut.mosi_o)
    config = SpiConfig(8, FallingEdge, RisingEdge, 20, "ns")
    slave = SpiSlave(interface, config)
    driver = DutDriver(dut)

    await cocotb.start(clk.start())

    await init(dut)
    dut.clock_phase_i.value = 0
    dut.clock_polarity_i.value = 1
    await FallingEdge(dut.clk_i)

    await cocotb.start(slave.coroutine())
    await cocotb.start(driver.coroutine())

    await driver.auto_receive()

    count = 3
    await perform_multiple_transmits(count, dut, slave, driver)

    dut.clock_phase_i.value = 1
    dut.clock_polarity_i.value = 0
    await FallingEdge(dut.clk_i)

    await perform_multiple_transmits(count, dut, slave, driver)

    await Timer(100, "ns")

@cocotb.test()
async def sixteen_bits(dut):
    clk = Clock(dut.clk_i, 5, "ns")
    interface = SpiInterface(dut.csn_o, dut.sck_o, dut.miso_i, dut.mosi_o)
    config = SpiConfig(16, FallingEdge, RisingEdge, 20, "ns")
    slave = SpiSlave(interface, config)
    driver = DutDriver(dut)

    await cocotb.start(clk.start())

    await init(dut)
    dut.clock_phase_i.value = 0
    dut.clock_polarity_i.value = 1
    dut.size_sel_i.value = 1
    await FallingEdge(dut.clk_i)

    await cocotb.start(slave.coroutine())
    await cocotb.start(driver.coroutine())

    await driver.auto_receive()

    count = 5
    await perform_multiple_transmits(count, dut, slave, driver, 16)

    await Timer(100, "ns")


@cocotb.test()
async def rx_blocking_tx(dut):
    clk = Clock(dut.clk_i, 5, "ns")
    interface = SpiInterface(dut.csn_o, dut.sck_o, dut.miso_i, dut.mosi_o)
    config = SpiConfig(16, RisingEdge, FallingEdge, 10, "ns", csn_pulse = True)
    slave = SpiSlave(interface, config)
    driver = DutDriver(dut)

    await cocotb.start(clk.start())

    await init(dut)
    dut.size_sel_i.value = 1
    dut.rx_block_on_full_i.value = 1
    await FallingEdge(dut.clk_i)

    await cocotb.start(slave.coroutine())
    await cocotb.start(driver.coroutine())

    await driver.auto_receive(waiting_clocks = 5)

    count = 5
    await perform_multiple_transmits(count, dut, slave, driver, 16)

    await Timer(100, "ns")

@cocotb.test()
async def csn_pulse(dut):
    clk = Clock(dut.clk_i, 5, "ns")
    interface = SpiInterface(dut.csn_o, dut.sck_o, dut.miso_i, dut.mosi_o)
    config = SpiConfig(16, RisingEdge, FallingEdge, 20, "ns", csn_pulse = True)
    slave = SpiSlave(interface, config)
    driver = DutDriver(dut)

    await cocotb.start(clk.start())

    await init(dut)
    dut.pulse_csn_i.value = 1
    dut.size_sel_i.value = 1
    await FallingEdge(dut.clk_i)

    await cocotb.start(slave.coroutine())
    await cocotb.start(driver.coroutine())

    await driver.auto_receive()

    count = 5
    await perform_multiple_transmits(count, dut, slave, driver, 16)

    await Timer(100, "ns")

def spi_tests_runner():
    hdl_toplevel_lang = "vhdl"
    sim = os.getenv("SIM", "questa")

    proj_path = Path(__file__).resolve().parent.parent
    # equivalent to setting the PYTHONPATH environment variable
    sys.path.append(str(proj_path / "models"))

    sources = [
        proj_path / "src" / "spi_pkg.vhd",
        proj_path / "src" / "rs_latch.vhd",
        proj_path / "src" / "register.vhd",
        proj_path / "src" / "shift_register.vhd",
        proj_path / "src" / "spi_clkgen.vhd",
        proj_path / "src" / "spi_clkmon.vhd",
        proj_path / "src" / "spi_slave_ctrl.vhd",
        proj_path / "src" / "spi_master_ctrl.vhd",
        proj_path / "src" / "spi_master.vhd",
        proj_path / "src" / "spi_masterslave.vhd",
        proj_path / "src" / "spi_peripheral.vhd"
    ]

    build_args = []
    extra_args = []
    if sim == "ghdl":
        extra_args = ["--std=08"]
    elif sim == "questa" or sim == "modelsim":
        build_args = ["-2008"]

    # equivalent to setting the PYTHONPATH environment variable
    sys.path.append(str(proj_path / "tests"))

    runner = get_runner(sim)
    runner.build(
        sources=sources,
        hdl_toplevel="spi_masterslave",
        always=True,
        build_args=build_args + extra_args,
    )
    runner.test(
        hdl_toplevel="spi_masterslave", hdl_toplevel_lang=hdl_toplevel_lang,
        test_module="test_spi_masterslave", test_args = extra_args
    )


if __name__ == "__main__":
    spi_tests_runner()
Do not follow this link