Exemple #1
0
class TestSimS2C(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run([os.path.dirname(__file__) + '/test_SimI2c.v'])

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    def test_i2c(self):
        data = [0x85, 0x81, 0xa5, 0x91]
        self.chip['i2c'].write(0x92, data)

        ret = self.chip['i2c'].get_data(4)
        self.assertEqual(ret.tolist(), data)

        self.chip['i2c'].write(0x92, data[0:1])

        self.chip['i2c'].set_data([0, 1, 2, 3])

        ret = self.chip['i2c'].read(0x92, 3)
        self.assertEqual(ret.tolist(), data[1:])

        # no ack/no such device
        exept = False
        try:
            self.chip['i2c'].write(0x55, data)
        except IOError:
            exept = True

        self.assertEqual(exept, True)

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #2
0
class TestSimS2C(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run([os.getcwd() + '/test_SimI2c.v'])

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    def test_i2c(self):
        data = [0x85, 0x81, 0xa5, 0x91]
        self.chip['i2c'].write(0x92, data)

        ret = self.chip['i2c'].get_data(4)
        self.assertEqual(ret.tolist(), data)

        self.chip['i2c'].write(0x92, data[0:1])

        self.chip['i2c'].set_data([0, 1, 2, 3])

        ret = self.chip['i2c'].read(0x92, 3)
        self.assertEqual(ret.tolist(), data[1:])

        # no ack/no such device
        exept = False
        try:
            self.chip['i2c'].write(0x55, data)
        except IOError:
            exept = True

        self.assertEqual(exept, True)

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #3
0
class TestSimGpio(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run(
            [os.path.join(os.path.dirname(__file__), 'test_SimGpio.v')])

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    def test_io(self):
        self.chip['GPIO'].set_output_en([0xff, 0,
                                         0])  # to remove 'z in simulation

        ret = self.chip['GPIO'].get_data()
        self.assertEqual([0, 0, 0], ret)

        self.chip['GPIO'].set_output_en([0x0f, 0, 0])
        self.chip['GPIO'].set_data([0xe3, 0xfa, 0x5a])
        ret = self.chip['GPIO'].get_data()
        self.assertEqual([0x33, 0x5a, 0x5a], ret)
        ret = self.chip['GPIO2'].get_data()
        self.assertEqual([0xa5, 0xcd], ret)

    def test_io_register(self):
        self.chip['GPIO'].set_output_en([0xff, 0,
                                         0])  # to remove 'z in simulation

        self.chip['GPIO']['OUT'] = 0xa5
        self.chip['GPIO'].write()
        ret = self.chip['GPIO'].get_data()
        self.assertEqual([0, 0xa5, 0xa5], ret)
        # TODO: Add register readback and comparison

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #4
0
class TestSimGpio(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run([os.getcwd() + '/test_SimGpio.v'])

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    def test_io(self):
        ret = self.chip['gpio'].get_data()
        self.assertEqual([0, 0, 0], ret)

        self.chip['gpio'].set_data([0xe3, 0xfa, 0x5a])
        ret = self.chip['gpio'].get_data()
        self.assertEqual([0, 0x5a, 0x5a], ret)

        self.chip['gpio'].set_output_en([0x0f, 0, 0])
        ret = self.chip['gpio'].get_data()
        self.assertEqual([0x33, 0x5a, 0x5a], ret)

    def test_io_register(self):
        self.chip['GPIO']['OUT'] = 0xa5
        self.chip['GPIO'].write()
        ret = self.chip['gpio'].get_data()
        self.assertEqual([0, 0xa5, 0xa5], ret)
        # TODO: Add register readback and comparison

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #5
0
class TestSimGpio(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run([os.getcwd() + '/test_SimGpio.v'])

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    def test_io(self):
        ret = self.chip['gpio'].get_data()
        self.assertEqual([0, 0, 0], ret)

        self.chip['gpio'].set_data([0xe3, 0xfa, 0x5a])
        ret = self.chip['gpio'].get_data()
        self.assertEqual([0, 0x5a, 0x5a], ret)

        self.chip['gpio'].set_output_en([0x0f, 0, 0])
        ret = self.chip['gpio'].get_data()
        self.assertEqual([0x33, 0x5a, 0x5a], ret)

    def test_io_register(self):
        self.chip['GPIO']['OUT'] = 0xa5
        self.chip['GPIO'].write()
        ret = self.chip['gpio'].get_data()
        self.assertEqual([0, 0xa5, 0xa5], ret)
        # TODO: Add register readback and comparison

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #6
0
class TestSimTlu(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run(
            [os.path.join(os.path.dirname(__file__), 'test_SimTdc.v')])

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    def test_tdc(self):
        self.chip['TDC'].ENABLE = 1
        self.chip['SEQ'].REPEAT = 1

        for index, i in enumerate(range(0, 10)):
            length = i + 1
            self.chip['SEQ'].SIZE = length + 1
            self.chip['SEQ']['TDC_IN'][0:length] = True
            self.chip['SEQ'].write(length)
            self.chip['SEQ'].START
            while (not self.chip['SEQ'].is_ready):
                pass
            self.assertEqual(self.chip['FIFO'].get_FIFO_INT_SIZE(), 1)

            data = self.chip['FIFO'].get_data()
            self.assertEqual(data[0], (index << 12) + length)

    def test_tdc_overflow(self):
        self.chip['TDC'].ENABLE = 1
        self.chip['SEQ'].REPEAT = 1

        for index, i in enumerate(range(4094, 4097)):
            length = i + 1
            self.chip['SEQ_GEN'].SIZE = length + 1
            self.chip['SEQ']['TDC_IN'][0:length] = True
            self.chip['SEQ'].write(length)
            self.chip['SEQ'].START
            while (not self.chip['SEQ_GEN'].is_ready):
                pass
            self.assertEqual(self.chip['FIFO'].get_FIFO_INT_SIZE(), 1)

            data = self.chip['FIFO'].get_data()
            self.assertEqual(data[0], (index << 12) +
                             min(length, 4095))  # overflow 12bit


#     def test_tdc_delay(self):
#         pass
#
#     def test_tdc_delay_overflow(self):
#         pass
#
#     def test_tdc_delay_late_trigger(self):
#         pass
#
#     def test_tdc_arm(self):
#         pass

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #7
0
class TestSimGpio(unittest.TestCase):
    def setUp(self):

        cocotb_compile_and_run([os.getcwd() + '/test_SimSpi.v'])

        cnfg = yaml.load(cnfg_yaml)
        self.chip = Dut(cnfg)

        self.chip.init()

    def test_io(self):
        size = self.chip['spi'].get_size()
        self.chip['gpio'].reset()
        self.assertEqual(size, 16 * 8)

        self.chip['spi'].set_data(range(16))
        ret = self.chip['spi'].get_data(size=16,
                                        addr=0)  #to read back what was written
        self.assertEqual(ret.tolist(), range(16))

        self.chip['spi'].set_data(range(16))
        ret = self.chip['spi'].get_data(addr=0)  #to read back what was written
        self.assertEqual(ret.tolist(), range(16))

        self.chip['spi'].start()
        while (not self.chip['spi'].is_done()):
            time.sleep(0.1)

        ret = self.chip['spi'].get_data(
        )  # read back what was received (looped)
        self.assertEqual(ret.tolist(), range(16))

        #spi_rx
        ret = self.chip['spi_rx'].get_en()
        self.assertEqual(ret, False)

        self.chip['spi_rx'].set_en(True)
        ret = self.chip['spi_rx'].get_en()
        self.assertEqual(ret, True)

        self.chip['spi'].start()
        while (not self.chip['spi'].is_done()):
            time.sleep(0.1)

        ret = self.chip['fifo'].get_fifo_size()
        self.assertEqual(ret, 32)

        ret = self.chip['fifo'].get_data()

        data0 = ret.astype(np.uint8)
        data1 = np.right_shift(ret, 8).astype(np.uint8)
        data = np.reshape(np.vstack((data1, data0)), -1, order='F')
        self.assertEqual(data.tolist(), range(16))

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #8
0
class TestSimTimestamp(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run(
            [os.path.join(os.path.dirname(__file__), 'test_SimTimestamp.v')])

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    def test_io(self):
        self.chip['timestamp'].reset()
        self.chip['timestamp']["ENABLE"] = 1
        self.chip['gpio'].reset()

        self.chip['fifo'].reset()
        ret = self.chip['fifo'].get_fifo_size()
        self.assertEqual(ret, 0)

        # trigger timestamp
        self.chip['PULSE_GEN'].set_delay(0x105)
        self.chip['PULSE_GEN'].set_width(10)
        self.chip['PULSE_GEN'].set_repeat(1)
        self.assertEqual(self.chip['PULSE_GEN'].get_delay(), 0x105)
        self.assertEqual(self.chip['PULSE_GEN'].get_width(), 10)
        self.assertEqual(self.chip['PULSE_GEN'].get_repeat(), 1)

        self.chip['PULSE_GEN'].start()
        while (not self.chip['PULSE_GEN'].is_done()):
            pass

        # get data from fifo
        ret = self.chip['fifo'].get_fifo_size()
        self.assertEqual(ret, 3 * 4)

        ret = self.chip['fifo'].get_data()
        self.assertEqual(len(ret), 3)

        # check with gpio
        ret2 = self.chip['gpio'].get_data()
        self.assertEqual(len(ret2), 8)

        for i, r in enumerate(ret):
            self.assertEqual(r & 0xF0000000, 0x50000000)
            self.assertEqual(r & 0xF000000, 0x1000000 * (3 - i))

        self.assertEqual(ret[2] & 0xFFFFFF,
                         0x10000 * ret2[5] + 0x100 * ret2[6] + ret2[7])
        self.assertEqual(ret[1] & 0xFFFFFF,
                         0x10000 * ret2[2] + 0x100 * ret2[3] + ret2[4])
        self.assertEqual(ret[1] & 0xFFFFFF, 0x100 * ret2[0] + ret2[1])

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #9
0
class TestSimGpio(unittest.TestCase):
    def setUp(self):

        cocotb_compile_and_run([os.getcwd() + '/test_SimAdcRx.v'])

        cnfg = yaml.load(cnfg_yaml)
        self.chip = Dut(cnfg)

        self.chip.init()

    def test_io(self):

        pattern = [1, 0, 1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7]
        self.chip['SEQ_GEN'].set_data(pattern)

        self.chip['PULSE_GEN'].set_delay(1)
        self.chip['PULSE_GEN'].set_width(1)

        self.chip['SEQ_GEN'].set_en_ext_start(True)
        self.chip['SEQ_GEN'].set_size(8)
        self.chip['SEQ_GEN'].set_repeat(1)

        #this is to have something in memory and not X
        self.chip['PULSE_GEN'].start()
        self.chip['SEQ_GEN'].is_done()
        self.chip['SEQ_GEN'].is_done()

        while (not self.chip['SEQ_GEN'].is_done()):
            pass

        #take some data
        self.chip['FADC'].set_align_to_sync(True)
        self.chip['FADC'].set_data_count(16)
        self.chip['FADC'].set_single_data(True)
        self.chip['FADC'].start()

        self.chip['PULSE_GEN'].start()
        self.chip['SEQ_GEN'].is_done()
        self.chip['SEQ_GEN'].is_done()

        while (not self.chip['FADC'].is_done()):
            pass

        ret = self.chip['fifo'].get_data()
        self.assertEqual(
            ret[2:2 + 8].tolist(),
            [0x0100, 0x0101, 0x0102, 0x0103, 0x0104, 0x0105, 0x0106, 0x0107])

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #10
0
class TestExampleMIO(unittest.TestCase):
    def setUp(self):

        fw_path = get_basil_dir() + "/firmware/modules"
        cocotb_compile_and_run(
            [
                fw_path + "/gpio/gpio.v",
                fw_path + "/utils/reset_gen.v",
                fw_path + "/utils/bus_to_ip.v",
                fw_path + "/utils/fx2_to_bus.v",
                os.path.dirname(__file__) + "/../src/example.v",
            ],
            top_level="example",
            sim_bus="basil.utils.sim.SiLibUsbBusDriver",
        )

        with open(os.path.dirname(__file__) + "/example.yaml", "r") as f:
            cnfg = yaml.load(f)

        # change to simulation interface
        cnfg["transfer_layer"][0]["type"] = "SiSim"

        self.chip = Dut(cnfg)
        self.chip.init()

    def test(self):

        ret = self.chip["GPIO_LED"].get_data()
        self.assertEqual([0], ret)

        self.chip["GPIO_LED"]["LED"] = 0x01
        self.chip["GPIO_LED"].write()

        ret = self.chip["GPIO_LED"].get_data()
        self.assertEqual([0x21], ret)

        self.chip["GPIO_LED"]["LED"] = 0x02
        self.chip["GPIO_LED"].write()

        ret = self.chip["GPIO_LED"].get_data()
        self.assertEqual([0x42], ret)

        self.chip["GPIO_LED"]["LED"] = 0x03
        self.chip["GPIO_LED"].write()

        ret = self.chip["GPIO_LED"].get_data()
        self.assertEqual([0x63], ret)

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #11
0
class TestSimM26(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run(
            [os.path.join(os.path.dirname(__file__), 'test_SimFifo8to32.v')])

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    def test_io(self):
        for i in range(4):
            self.chip['INTF'].write(0x1000, [i])

        data = []
        iterations = 1000
        i = 0
        while not len(data) == 1:
            if i >= iterations:
                break
            data.extend(self.chip['FIFO'].get_data())
            i += 1
        assert data[0] == 50462976

        self.chip['INTF'].write(0x1000, [4, 5, 6, 7])

        data = []
        iterations = 1000
        i = 0
        while not len(data) == 1:
            if i >= iterations:
                break
            data.extend(self.chip['FIFO'].get_data())
            i += 1
        assert data[0] == 117835012

        self.chip['INTF'].write(0x1000, range(8))

        data = []
        iterations = 1000
        i = 0
        while not len(data) == 2:
            if i >= iterations:
                break
            data.extend(self.chip['FIFO'].get_data())
            i += 1
        assert data[0] == 50462976
        assert data[1] == 117835012

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #12
0
class TestExampleMIO(unittest.TestCase):
    def setUp(self):
        fw_path = os.path.join(get_basil_dir(), 'firmware/modules')
        cocotb_compile_and_run([
            os.path.join(fw_path, 'gpio/gpio.v'),
            os.path.join(fw_path, 'gpio/gpio_core.v'),
            os.path.join(fw_path, 'utils/reset_gen.v'),
            os.path.join(fw_path, 'utils/bus_to_ip.v'),
            os.path.join(fw_path, 'utils/fx2_to_bus.v'),
            os.path.join(os.path.dirname(__file__), '../src/example.v')
        ],
                               top_level='example',
                               sim_bus='basil.utils.sim.SiLibUsbBusDriver')

        with open(os.path.join(os.path.dirname(__file__), 'example.yaml'),
                  'r') as f:
            cnfg = yaml.safe_load(f)

        # change to simulation interface
        cnfg['transfer_layer'][0]['type'] = 'SiSim'

        self.chip = Dut(cnfg)
        self.chip.init()

    def test_gpio(self):
        ret = self.chip['GPIO_LED'].get_data()
        self.assertEqual([0], ret)

        self.chip['GPIO_LED']['LED'] = 0x01
        self.chip['GPIO_LED'].write()

        ret = self.chip['GPIO_LED'].get_data()
        self.assertEqual([0x21], ret)

        self.chip['GPIO_LED']['LED'] = 0x02
        self.chip['GPIO_LED'].write()

        ret = self.chip['GPIO_LED'].get_data()
        self.assertEqual([0x42], ret)

        self.chip['GPIO_LED']['LED'] = 0x03
        self.chip['GPIO_LED'].write()

        ret = self.chip['GPIO_LED'].get_data()
        self.assertEqual([0x63], ret)

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #13
0
class TestExampleMIO(unittest.TestCase):
    def setUp(self):
        fw_path = os.path.join(get_basil_dir(), 'firmware/modules')
        cocotb_compile_and_run([
            os.path.join(fw_path, 'gpio/gpio.v'),
            os.path.join(fw_path, 'utils/reset_gen.v'),
            os.path.join(fw_path, 'utils/bus_to_ip.v'),
            os.path.join(fw_path, 'utils/fx2_to_bus.v'),
            os.path.join(os.path.dirname(__file__), '../src/example.v')],
            top_level='example',
            sim_bus='basil.utils.sim.SiLibUsbBusDriver'
        )

        with open(os.path.join(os.path.dirname(__file__), 'example.yaml'), 'r') as f:
            cnfg = yaml.load(f)

        # change to simulation interface
        cnfg['transfer_layer'][0]['type'] = 'SiSim'

        self.chip = Dut(cnfg)
        self.chip.init()

    def test_gpio(self):
        ret = self.chip['GPIO_LED'].get_data()
        self.assertEqual([0], ret)

        self.chip['GPIO_LED']['LED'] = 0x01
        self.chip['GPIO_LED'].write()

        ret = self.chip['GPIO_LED'].get_data()
        self.assertEqual([0x21], ret)

        self.chip['GPIO_LED']['LED'] = 0x02
        self.chip['GPIO_LED'].write()

        ret = self.chip['GPIO_LED'].get_data()
        self.assertEqual([0x42], ret)

        self.chip['GPIO_LED']['LED'] = 0x03
        self.chip['GPIO_LED'].write()

        ret = self.chip['GPIO_LED'].get_data()
        self.assertEqual([0x63], ret)

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #14
0
class TestSimTlu(unittest.TestCase):
    def setUp(self):
    
        cocotb_compile_and_run(['test_SimTlu.v'])
        
        cnfg = yaml.load(cnfg_yaml)
        self.chip = Dut(cnfg)
        self.chip.init()
        
    def test_version(self):
        self.assertEqual(self.chip['tlu'].VERSION, 1)
    
    def tearDown(self):
        self.chip.close() # let it close connection and stop simulator
        time.sleep(1)
        subprocess.call('make clean', shell=True)
        subprocess.call('rm -f Makefile', shell=True)
Exemple #15
0
class TestSimGpio(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run([os.getcwd() + '/test_SimAdcRx.v'])

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    def test_io(self):
        pattern = [1, 0, 1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7]
        self.chip['SEQ_GEN'].set_data(pattern)

        self.chip['PULSE_GEN'].set_delay(1)
        self.chip['PULSE_GEN'].set_width(1)

        self.chip['SEQ_GEN'].set_en_ext_start(True)
        self.chip['SEQ_GEN'].set_size(8)
        self.chip['SEQ_GEN'].set_repeat(1)

        # this is to have something in memory and not X
        self.chip['PULSE_GEN'].start()
        self.chip['SEQ_GEN'].is_done()
        self.chip['SEQ_GEN'].is_done()

        while(not self.chip['SEQ_GEN'].is_done()):
            pass

        # take some data
        self.chip['FADC'].set_align_to_sync(True)
        self.chip['FADC'].set_data_count(16)
        self.chip['FADC'].set_single_data(True)
        self.chip['FADC'].start()

        self.chip['PULSE_GEN'].start()
        self.chip['SEQ_GEN'].is_done()
        self.chip['SEQ_GEN'].is_done()

        while(not self.chip['FADC'].is_done()):
            pass

        ret = self.chip['fifo'].get_data()
        self.assertEqual(ret[2:2 + 8].tolist(), [0x0100, 0x0101, 0x0102, 0x0103, 0x0104, 0x0105, 0x0106, 0x0107])

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #16
0
class TestSimGpio(unittest.TestCase):
    def __init__(self, testname, tb='test_SimGpio.v', bus_drv='basil.utils.sim.BasilBusDriver', bus_split=False):
        super(TestSimGpio, self).__init__(testname)
        self._test_tb = tb
        self._sim_bus = bus_drv
        self._bus_split_def = ()
        if bus_split is not False:
            if bus_split == 'sbus':
                self._bus_split_def = ("BASIL_SBUS",)
            elif bus_split == 'top':
                self._bus_split_def = ("BASIL_TOPSBUS",)

    def setUp(self):
        cocotb_compile_and_run(sim_files=[os.path.join(os.path.dirname(__file__), self._test_tb)], sim_bus=self._sim_bus, extra_defines=self._bus_split_def)

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    def test_io(self):
        self.chip['GPIO'].set_output_en([0xff, 0, 0])  # to remove 'z in simulation

        ret = self.chip['GPIO'].get_data()
        self.assertEqual([0, 0, 0], ret)

        self.chip['GPIO'].set_output_en([0x0f, 0, 0])
        self.chip['GPIO'].set_data([0xe3, 0xfa, 0x5a])
        ret = self.chip['GPIO'].get_data()
        self.assertEqual([0x33, 0x5a, 0x5a], ret)
        ret = self.chip['GPIO2'].get_data()
        self.assertEqual([0xa5, 0xcd], ret)

    def test_io_register(self):

        self.chip['GPIO'].set_output_en([0xff, 0, 0])  # to remove 'z in simulation

        self.chip['GPIO']['OUT'] = 0xa5

        self.chip['GPIO'].write()
        ret = self.chip['GPIO'].get_data()
        self.assertEqual([0, 0xa5, 0xa5], ret)
        # TODO: Add register readback and comparison

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #17
0
class TestSimScpi(unittest.TestCase):
    def setUp(self):
        cfg = yaml.load(cnfg_yaml)
        self.device = Dut(cfg)
        self.device.init()

    def test_read(self):
        self.assertEqual(self.device['Pulser'].get_frequency(), u'100.00')

    def test_write(self):
        self.device['Pulser'].set_on()
        self.assertEqual(self.device['Pulser'].get_on(), u'0')

    def test_exception(self):
        with self.assertRaises(ValueError):
            self.device['Pulser'].unknown_function()

    def tearDown(self):
        self.device.close()
Exemple #18
0
class TestSimScpi(unittest.TestCase):

    def setUp(self):
        cfg = yaml.load(cnfg_yaml)
        self.device = Dut(cfg)
        self.device.init()

    def test_read(self):
        self.assertEqual(self.device['Pulser'].get_frequency(), u'100.00')

    def test_write(self):
        self.device['Pulser'].set_on()
        self.assertEqual(self.device['Pulser'].get_on(), u'0')

    def test_exception(self):
        with self.assertRaises(ValueError):
            self.device['Pulser'].unknown_function()

    def tearDown(self):
        self.device.close()
Exemple #19
0
class TestSimSpi(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run([os.path.join(os.path.dirname(__file__), 'test_SimSpi.v')])

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    def test_io(self):
        size = self.chip['SPI'].get_SIZE()
        self.chip['GPIO'].reset()
        self.assertEqual(size, 16 * 8)

        self.chip['SPI'].set_data(range(16))
        ret = self.chip['SPI'].get_data(size=16, addr=0)  # to read back what was written
        self.assertEqual(ret.tolist(), range(16))

        self.chip['SPI'].set_data(range(16))
        ret = self.chip['SPI'].get_data(addr=0)  # to read back what was written
        self.assertEqual(ret.tolist(), range(16))

        self.chip['SPI'].start()
        while(not self.chip['SPI'].is_ready):
            pass

        ret = self.chip['SPI'].get_data()  # read back what was received (looped)
        self.assertEqual(ret.tolist(), range(16))

        # ext_start
        self.chip['SPI'].set_en(1)
        self.assertEqual(self.chip['SPI'].get_en(), 1)

        self.chip['PULSE_GEN'].set_DELAY(1)
        self.chip['PULSE_GEN'].set_WIDTH(1 + size)
        self.chip['PULSE_GEN'].set_REPEAT(1)
        self.assertEqual(self.chip['PULSE_GEN'].get_DELAY(), 1)
        self.assertEqual(self.chip['PULSE_GEN'].get_WIDTH(), 1 + size)
        self.assertEqual(self.chip['PULSE_GEN'].get_REPEAT(), 1)

        self.chip['PULSE_GEN'].start()
        while(not self.chip['PULSE_GEN'].is_ready):
            pass

        ret = self.chip['SPI'].get_data()  # read back what was received (looped)
        self.assertEqual(ret.tolist(), range(16))

        # SPI_RX
        ret = self.chip['SPI_RX'].get_en()
        self.assertEqual(ret, False)

        self.chip['SPI_RX'].set_en(True)
        ret = self.chip['SPI_RX'].get_en()
        self.assertEqual(ret, True)

        self.chip['SPI'].start()
        while(not self.chip['SPI'].is_ready):
            pass

        ret = self.chip['FIFO'].get_FIFO_SIZE()
        self.assertEqual(ret, 32)

        ret = self.chip['FIFO'].get_data()

        data0 = ret.astype(np.uint8)
        data1 = np.right_shift(ret, 8).astype(np.uint8)
        data = np.reshape(np.vstack((data1, data0)), -1, order='F')
        self.assertEqual(data.tolist(), range(16))

    def test_dut_iter(self):
        conf = yaml.safe_load(cnfg_yaml)

        def iter_conf():
            for item in conf['registers']:
                yield item
            for item in conf['hw_drivers']:
                yield item
            for item in conf['transfer_layer']:
                yield item

        for mod, mcnf in zip(self.chip, iter_conf()):
            self.assertEqual(mod.name, mcnf['name'])
            self.assertEqual(mod.__class__.__name__, mcnf['type'])

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #20
0
class TestSimTlu(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run([os.path.dirname(__file__) + '/test_SimTlu.v'])

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    def test_simple_trigger_veto(self):
        self.chip['tlu'].TRIGGER_COUNTER = 0
        self.chip['tlu'].TRIGGER_MODE = 0
        self.chip['tlu'].TRIGGER_SELECT = 2
        self.chip['tlu'].TRIGGER_VETO_SELECT = 2
#         self.chip['CONTROL']['ENABLE'] = 1
        self.chip['gpio'].set_data([0x01])

        self.chip['gpio'].set_data([0x07])  # trigger + veto
        self.chip['gpio'].set_data([0x01])

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])

#         self.chip['CONTROL']['ENABLE'] = 0
        self.chip['gpio'].set_data([0x00])

        self.assertEqual(self.chip['sram'].get_fifo_int_size(), 1)
        self.assertEqual(self.chip['tlu'].TRIGGER_COUNTER, 1)

        data = self.chip['sram'].get_data()
        self.assertEqual(data[0], 0x80000000 + 0)

    def test_simple_trigger_veto_disabled(self):
        self.chip['tlu'].TRIGGER_COUNTER = 0
        self.chip['tlu'].TRIGGER_MODE = 0
        self.chip['tlu'].TRIGGER_SELECT = 2
        self.chip['tlu'].TRIGGER_VETO_SELECT = 252
#         self.chip['CONTROL']['ENABLE'] = 1
        self.chip['gpio'].set_data([0x01])

        self.chip['gpio'].set_data([0x07])  # trigger + veto
        self.chip['gpio'].set_data([0x01])

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])

#         self.chip['CONTROL']['ENABLE'] = 0
        self.chip['gpio'].set_data([0x00])

        self.assertEqual(self.chip['sram'].get_fifo_int_size(), 2)
        self.assertEqual(self.chip['tlu'].TRIGGER_COUNTER, 2)

        data = self.chip['sram'].get_data()
        self.assertEqual(data[0], 0x80000000 + 0)
        self.assertEqual(data[1], 0x80000000 + 1)

    def test_simple_trigger_max_triggers(self):
        self.chip['tlu'].TRIGGER_COUNTER = 0
        self.chip['tlu'].MAX_TRIGGERS = 2
        self.chip['tlu'].TRIGGER_MODE = 0
        self.chip['tlu'].TRIGGER_SELECT = 2
        self.chip['tlu'].TRIGGER_VETO_SELECT = 252
#         self.chip['CONTROL']['ENABLE'] = 1
        self.chip['gpio'].set_data([0x01])

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])

#         self.chip['CONTROL']['ENABLE'] = 0
        self.chip['gpio'].set_data([0x00])

        self.assertEqual(self.chip['sram'].get_fifo_int_size(), 2)
        self.assertEqual(self.chip['tlu'].TRIGGER_COUNTER, 2)

        data = self.chip['sram'].get_data()
        self.assertEqual(data[0], 0x80000000 + 0)
        self.assertEqual(data[1], 0x80000000 + 1)

    def test_simple_trigger(self):
        self.chip['tlu'].TRIGGER_COUNTER = 10
        self.chip['tlu'].TRIGGER_MODE = 0
        self.chip['tlu'].TRIGGER_SELECT = 1
        self.chip['tlu'].TRIGGER_VETO_SELECT = 0
#         self.chip['CONTROL']['ENABLE'] = 1
        self.chip['gpio'].set_data([0x01])

        readings = 0
        while(self.chip['sram'].get_fifo_int_size() < 4 and readings < 1000):
            readings += 1

#         self.chip['CONTROL']['ENABLE'] = 0
        self.chip['gpio'].set_data([0x00])

        self.assertGreaterEqual(self.chip['sram'].get_fifo_int_size(), 4)
        self.assertGreaterEqual(self.chip['tlu'].TRIGGER_COUNTER, 14)

        data = self.chip['sram'].get_data()
        self.assertEqual(data[0], 0x80000000 + 10)
        self.assertEqual(data[1], 0x80000000 + 11)
        self.assertEqual(data[2], 0x80000000 + 12)
        self.assertEqual(data[3], 0x80000000 + 13)

    def test_tlu_trigger_handshake(self):
        self.chip['tlu'].TRIGGER_COUNTER = 0
        self.chip['tlu'].TRIGGER_MODE = 3
        self.chip['tlu'].TRIGGER_VETO_SELECT = 255
        self.chip['tlu'].EN_TLU_VETO = 0
#         self.chip['CONTROL']['ENABLE'] = 1
        self.chip['gpio'].set_data([0x01])

        readings = 0
        while(self.chip['sram'].get_fifo_int_size() < 4 and readings < 1000):
            readings += 1

#         self.chip['CONTROL']['ENABLE'] = 0
        self.chip['gpio'].set_data([0x00])

        self.assertGreaterEqual(self.chip['sram'].get_fifo_int_size(), 4)
        self.assertGreaterEqual(self.chip['tlu'].TRIGGER_COUNTER, 4)
        self.assertGreaterEqual(self.chip['tlu'].CURRENT_TLU_TRIGGER_NUMBER, 3)

        data = self.chip['sram'].get_data()
        self.assertEqual(data[0], 0x80000000)
        self.assertEqual(data[1], 0x80000001)
        self.assertEqual(data[2], 0x80000002)
        self.assertEqual(data[3], 0x80000003)

    def test_tlu_trigger_handshake_veto(self):
        self.chip['tlu'].TRIGGER_COUNTER = 0
        self.chip['tlu'].TRIGGER_MODE = 3
        self.chip['tlu'].TRIGGER_VETO_SELECT = 1
        self.chip['tlu'].EN_TLU_VETO = 1
#         self.chip['CONTROL']['ENABLE'] = 1
        self.chip['gpio'].set_data([0x01])

        readings = 0
        while(self.chip['sram'].get_fifo_int_size() == 0 and readings < 1000):
            readings += 1

        self.assertEqual(self.chip['sram'].get_fifo_int_size(), 0)
        self.assertEqual(self.chip['tlu'].TRIGGER_COUNTER, 0)
        self.assertEqual(self.chip['tlu'].CURRENT_TLU_TRIGGER_NUMBER, 0)

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #21
0
class TestSimSeq(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run([os.getcwd() + '/test_SimSeq.v'])

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    def test_io(self):
        self.assertEqual(self.chip['SEQ_GEN'].get_mem_size(), 8 * 1024)

        self.chip['SEQ']['S0'][0] = 1
        self.chip['SEQ']['S1'][1] = 1
        self.chip['SEQ']['S2'][2] = 1
        self.chip['SEQ']['S3'][3] = 1

        self.chip['SEQ']['S4'][12] = 1
        self.chip['SEQ']['S5'][13] = 1
        self.chip['SEQ']['S6'][14] = 1
        self.chip['SEQ']['S7'][15] = 1

        pattern = [0x01, 0x02, 0x04, 0x08, 0, 0, 0, 0, 0, 0, 0, 0, 0x10, 0x20, 0x40, 0x80]

        self.chip['SEQ'].write(16)

        ret = self.chip['SEQ'].get_data(size=16)
        self.assertEqual(ret.tolist(), pattern)

        rec_size = 16 * 4 + 8
        self.chip['SEQ_REC'].set_en_ext_start(True)
        self.chip['SEQ_REC'].set_size(rec_size)

        self.chip['PULSE_GEN'].set_delay(1)
        self.chip['PULSE_GEN'].set_width(1)

        self.assertEqual(self.chip['PULSE_GEN'].get_delay(), 1)
        self.assertEqual(self.chip['PULSE_GEN'].get_width(), 1)

        self.chip['SEQ'].set_repeat(4)
        self.chip['SEQ'].set_en_ext_start(True)
        self.chip['SEQ'].set_size(16)
        # self.chip['SEQ'].start()

        self.chip['PULSE_GEN'].start()

        while(not self.chip['SEQ'].is_done()):
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        self.assertEqual(ret.tolist(), [0x0] * 2 + pattern * 4 + [0x80] * 6)  # 2 clk delay + pattern x4 + 6 x last pattern

        #
        self.chip['SEQ'].set_repeat_start(12)
        self.chip['PULSE_GEN'].start()

        while(not self.chip['SEQ'].is_done()):
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        self.assertEqual(ret.tolist(), [0x80] * 2 + pattern + pattern[12:] * 3 + [0x80] * 3 * 12 + [0x80] * 6)  # 2 clk delay 0x80 > from last pattern + ...

        self.chip['SEQ'].set_wait(4)
        self.chip['PULSE_GEN'].start()

        while(not self.chip['SEQ'].is_done()):
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        lpat = pattern[12:] + [0x80] * 4
        self.assertEqual(ret.tolist(), [0x80] * 2 + pattern + [0x80] * 4 + lpat * 3 + [0x80] * (3 * 12 - 4 * 4) + [0x80] * 6)

        #
        rec_size = rec_size * 3
        self.chip['SEQ_REC'].set_size(rec_size)
        self.chip['SEQ'].set_clk_divide(3)
        self.chip['SEQ'].set_wait(3)
        self.chip['PULSE_GEN'].start()

        while(not self.chip['SEQ'].is_done()):
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        lpat = pattern[12:] + [0x80] * 3
        mu_pat = pattern + [0x80] * 3 + lpat * 3
        fm = []
        for i in mu_pat:
            fm += [i, i, i]
        self.assertEqual(ret.tolist(), [0x80] * 2 + fm + [0x80] * 94)

        #
        self.chip['SEQ'].set_wait(0)
        self.chip['PULSE_GEN'].start()

        while(not self.chip['SEQ'].is_done()):
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        lpat = pattern[12:]
        mu_pat = pattern + lpat * 3
        fm = []
        for i in mu_pat:
            fm += [i, i, i]
        self.assertEqual(ret.tolist(), [0x80] * 2 + fm + [0x80] * (94 + 4 * 3 * 3))

        # nested loop test
        pattern = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
        self.chip['SEQ'].set_data(pattern)
        self.chip['SEQ'].set_repeat(4)
        self.chip['SEQ'].set_repeat_start(2)
        self.chip['SEQ'].set_nested_start(8)
        self.chip['SEQ'].set_nested_stop(12)
        self.chip['SEQ'].set_nested_repeat(3)
        self.chip['SEQ'].set_clk_divide(1)
        self.chip['PULSE_GEN'].start()

        while(not self.chip['SEQ'].is_done()):
            pass

        exp_pattern = [0x10, 0x10]
        exp_pattern += pattern[0:2]
        rep = pattern[2:8]
        rep += pattern[8:12] * 3
        rep += pattern[12:16]
        exp_pattern += rep * 4
        exp_pattern += [16] * 124

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        self.assertEqual(ret.tolist(), exp_pattern)

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #22
0
class TestSimMMC3Eth(unittest.TestCase):
    def setUp(self):
        sys.path = [os.path.dirname(os.getcwd())] + sys.path
        proj_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

        cocotb_compile_and_run(sim_files=[proj_dir + '/test/mmc3_eth_tb.v'],
                               top_level='tb',
                               include_dirs=(proj_dir, proj_dir + '/src'))
        '''
        with open("test_mmc3_eth.yaml") as conf_file:
            try:
                conf = yaml.load(conf_file)
            except yaml.YAMLError as exception:
                print(exception)

        conf['transfer_layer'][0]['type']

        self.chip = Dut(conf)
        self.chip.init()
        '''

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    def test(self):
        testduration = 10
        total_len = 0
        tick = 0
        tick_old = 0
        start_time = time.time()

        self.chip['GPIO_LED']['LED'] = 0x01  #start data source
        self.chip['GPIO_LED'].write()

        while time.time() - start_time < testduration:
            data = self.chip['FIFO'].get_data()
            total_len += len(data)
            time.sleep(0.01)
            tick = int(time.time() - start_time)
            if tick != tick_old:
                print tick
                tick_old = tick

            if doprint == True:
                print data

            for i in data:
                if i < (len(data) - 1):
                    assert data[i] == data[
                        i +
                        1] - 1  #Check, if received integers are increasing numbers

            if total_len >= IntsToReceive:
                break

        total_len_bits = total_len * 32  #32-bit ints to bits
        print('Bits received:', total_len_bits, '  data rate:',
              round((total_len_bits / 1e6 / testduration), 2), ' Mbit/s')

        self.chip['GPIO_LED']['LED'] = 0x00  #stop data source
        self.chip['GPIO_LED'].write()

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #23
0
class TestSimJtagMaster(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run(
            [
                os.path.join(os.path.dirname(__file__), "jtag_tap.v"),
                os.path.join(os.path.dirname(__file__), "test_SimJtagMaster.v"),
            ]
        )

        self.chip = Dut(cnfg_yaml)
        self.chip.init(init_yaml)

    def test_sequence(self):
        self.jtag_master_FSM_tests()
        self.jtag_tests()

    def jtag_master_FSM_tests(self):
        # Make sure register are set to default values
        self.chip["JTAG"].reset()

        size = self.chip["JTAG"].SIZE
        self.assertEqual(size, 2000 * 8)

        byte_size = self.chip["JTAG"].MEM_BYTES
        self.assertEqual(byte_size, 2000)

        word_cnt = self.chip["JTAG"].WORD_COUNT
        self.assertEqual(word_cnt, 1)

        op = self.chip["JTAG"].get_command()
        self.assertEqual(op, "INSTRUCTION")

        wait = self.chip["JTAG"].WAIT
        self.assertEqual(wait, 0)

        # Test reset
        self.chip["JTAG"].reset()

        # Write 1 word test
        self.chip["JTAG"].set_data([0xFF] + list(range(15)))
        ret = self.chip["JTAG"].get_data(size=16, addr=0)  # to read back what was written
        self.assertEqual(ret.tolist(), [0xFF] + list(range(15)))

        self.chip["JTAG"].SIZE = 16
        self.chip["JTAG"].start()
        while not self.chip["JTAG"].READY:
            pass

        # Write 2 word test
        self.chip["JTAG"].WORD_COUNT = 2
        word_cnt = self.chip["JTAG"].WORD_COUNT
        self.assertEqual(word_cnt, 2)

        self.chip["JTAG"].start()
        while not self.chip["JTAG"].READY:
            pass

        # Write 5 word test
        self.chip["JTAG"].WORD_COUNT = 5
        word_cnt = self.chip["JTAG"].WORD_COUNT
        self.assertEqual(word_cnt, 5)

        self.chip["JTAG"].start()
        while not self.chip["JTAG"].READY:
            pass

    def jtag_tests(self):

        ID_CODE_STR = "0010"
        ID_CODE = BitLogic(ID_CODE_STR)
        BYPASS = BitLogic("1111")
        DEBUG = BitLogic("1000")
        ret_ir = BitLogic("0101")

        # TEST REG INIT
        dev1ret = StdRegister(driver=None, conf=yaml.safe_load(gpio_yaml))
        dev1ret.init()
        dev1ret["F1"] = 0x1
        dev1ret["F2"] = 0x2F
        dev1ret["F3"] = 0x2
        dev1ret["F4"] = 0x17CF4
        self.assertEqual(dev1ret[:], self.chip["DEV1"][:])

        self.chip["DEV1"]["F2"] = 0
        self.assertFalse(dev1ret[:] == self.chip["DEV1"][:])

        self.chip.set_configuration(init_yaml)
        self.assertEqual(dev1ret[:], self.chip["DEV1"][:])

        self.chip["JTAG"].reset()

        # IR CODE
        with self.assertRaises(ValueError):
            self.chip["JTAG"].scan_ir(ID_CODE_STR + ID_CODE_STR)

        ret = self.chip["JTAG"].scan_ir([ID_CODE] * 2, readback=False)
        self.assertEqual(ret, None)

        ret = self.chip["JTAG"].scan_ir([ID_CODE] * 2)
        self.assertEqual(ret, [ret_ir] * 2)

        # ID CODE
        with self.assertRaises(ValueError):
            self.chip["JTAG"].scan_dr("0" * 32 * 2)

        ret = self.chip["JTAG"].scan_dr(["0" * 32] * 2, readback=False)
        self.assertEqual(ret, None)

        id_code = BitLogic.from_value(0x149B51C3, fmt="I")
        ret = self.chip["JTAG"].scan_dr(["0" * 32] * 2)
        self.assertEqual(ret, [id_code] * 2)

        # BYPASS + ID CODE
        bypass_code = BitLogic("0")
        ret = self.chip["JTAG"].scan_ir([ID_CODE, BYPASS])
        self.assertEqual(ret, [ret_ir] * 2)
        ret = self.chip["JTAG"].scan_dr(["0" * 32, "1"])
        self.assertEqual(ret, [id_code, bypass_code])

        ret = self.chip["JTAG"].scan_ir([BYPASS, ID_CODE])
        self.assertEqual(ret, [ret_ir] * 2)
        ret = self.chip["JTAG"].scan_dr(["1", "0" * 32])
        self.assertEqual(ret, [bypass_code, id_code])

        # DEBUG
        ret = self.chip["JTAG"].scan_ir([DEBUG, DEBUG])
        self.assertEqual(ret, [ret_ir] * 2)

        self.chip["JTAG"].scan_dr(["1" * 32, "0" * 1 + "1" * 30 + "0" * 1])
        ret = self.chip["JTAG"].scan_dr(["0" * 32, "1" * 32])
        self.assertEqual(ret, [BitLogic("1" * 32), BitLogic("0" * 1 + "1" * 30 + "0" * 1)])
        ret = self.chip["JTAG"].scan_dr(["0" * 32, "0" * 32])
        self.assertEqual(ret, [BitLogic("0" * 32), BitLogic("1" * 32)])

        # SHIT IN DEV REG/DEBUG
        self.chip["JTAG"].scan_dr([self.chip["DEV1"][:], self.chip["DEV2"][:]])

        # GPIO RETURN
        dev1ret.frombytes(self.chip["GPIO_DEV1"].get_data())
        self.assertEqual(dev1ret[:], self.chip["DEV1"][:])

        self.assertFalse(dev1ret[:] == self.chip["DEV2"][:])
        dev1ret.frombytes(self.chip["GPIO_DEV2"].get_data())
        self.assertEqual(dev1ret[:], self.chip["DEV2"][:])

        # JTAG RETURN
        ret = self.chip["JTAG"].scan_dr(["0" * 32, "0" * 32])
        dev1ret.set(ret[0])
        self.assertEqual(dev1ret[:], self.chip["DEV1"][:])

        dev1ret.set(ret[1])
        self.assertEqual(dev1ret[:], self.chip["DEV2"][:])

        # REPEATING REGISTER
        self.chip["JTAG"].scan_dr([self.chip["DEV"][:]], word_size=len(self.chip["DEV"][:]))
        ret1 = self.chip["JTAG"].scan_dr([self.chip["DEV"][:]], word_size=len(self.chip["DEV"][:]))
        self.chip["JTAG"].scan_dr([self.chip["DEV1"][:], self.chip["DEV2"][:]])
        ret2 = self.chip["JTAG"].scan_dr(
            [self.chip["DEV1"][:] + self.chip["DEV2"][:]],
            word_size=len(self.chip["DEV1"][:]),
        )
        ret3 = self.chip["JTAG"].scan_dr(
            [self.chip["DEV1"][:] + self.chip["DEV2"][:]],
            word_size=len(self.chip["DEV1"][:]),
        )
        self.assertEqual(ret1[:], ret2[:])
        self.assertEqual(ret2[:], ret3[:])

        # REPEATING SETTING
        self.chip["JTAG"].scan_dr(["1" * 32 + "0" * 32])
        ret = self.chip["JTAG"].scan_dr(["0" * 32 + "0" * 32])

        self.chip["DEV"].set(ret[0])
        self.assertEqual(self.chip["DEV"][:], BitLogic("1" * 32 + "0" * 32))

        self.chip["JTAG"].scan_dr(
            [self.chip["DEV1"][:] + self.chip["DEV2"][:]],
            word_size=len(self.chip["DEV1"][:]),
        )
        ret = self.chip["JTAG"].scan_dr(
            [self.chip["DEV1"][:] + self.chip["DEV2"][:]],
            word_size=len(self.chip["DEV1"][:]),
        )

        self.chip["DEV"].set(ret[0])
        self.assertEqual(self.chip["DEV"][:], self.chip["DEV1"][:] + self.chip["DEV2"][:])

        # BYPASS AND DEBUG REGISTER
        self.chip["fifo1"].reset()
        self.chip["fifo2"].reset()
        fifo_size = self.chip["fifo1"].get_fifo_size()
        self.assertEqual(fifo_size, 0)

        # Generate some data
        data_string = []
        data = np.power(range(20), 6)
        for i in range(len(data)):
            s = str(bin(data[i]))[2:]
            data_string.append("0" * (32 - len(s)) + s)

        # Bypass first device, put data in the debug register of the second device
        self.chip["JTAG"].scan_ir([DEBUG, BYPASS])
        for i in range(len(data_string)):
            self.chip["JTAG"].scan_dr([data_string[i], "1"])

        fifo_size = self.chip["fifo1"].get_fifo_size()
        self.assertEqual(fifo_size, len(data_string) * 4)
        fifo_tap1_content = self.chip["fifo1"].get_data()
        fifo_tap2_content = self.chip["fifo2"].get_data()
        self.assertListEqual(list(data), list(fifo_tap1_content))
        self.assertNotEqual(list(data), list(fifo_tap2_content))

        # empty fifos
        fifo_tap1_content = self.chip["fifo1"].get_data()
        fifo_tap2_content = self.chip["fifo2"].get_data()

        # Bypass second device, put data in the debug register of the first device
        self.chip["JTAG"].scan_ir([BYPASS, DEBUG])
        for i in range(len(data_string)):
            self.chip["JTAG"].scan_dr(["1", data_string[i]])

        fifo_size = self.chip["fifo1"].get_fifo_size()
        self.assertEqual(fifo_size, len(data_string) * 4)
        fifo_tap1_content = self.chip["fifo1"].get_data()
        fifo_tap2_content = self.chip["fifo2"].get_data()
        self.assertNotEqual(list(data), list(fifo_tap1_content))
        self.assertListEqual(list(data), list(fifo_tap2_content))

        # TEST OF SENDING MULTIPLE WORDS WITH SCAN_DR FUNCTION
        self.chip["JTAG"].scan_ir([DEBUG, DEBUG])
        self.chip["JTAG"].set_data([0x00] * 100)
        self.chip["JTAG"].set_command("DATA")
        self.chip["JTAG"].SIZE = 100 * 8
        self.chip["JTAG"].start()
        while not self.chip["JTAG"].READY:
            pass

        # empty fifos
        fifo_tap1_content = self.chip["fifo1"].get_data()
        fifo_tap2_content = self.chip["fifo2"].get_data()

        self.chip["JTAG"].scan_ir([DEBUG, BYPASS])
        self.chip["JTAG"].scan_dr([BitLogic("0" * 24 + "10101101"), BitLogic("1")] * 15, word_size=33)

        fifo_tap1_content = self.chip["fifo1"].get_data()
        fifo_tap2_content = self.chip["fifo2"].get_data()
        self.assertListEqual([int("0" * 24 + "10101101", 2)] * 15, list(fifo_tap1_content))
        self.assertNotEqual([int("0" * 24 + "10101101", 2)] * 15, list(fifo_tap2_content))

        # change value of debug registers
        self.chip["JTAG"].scan_ir([DEBUG, DEBUG])
        self.chip["JTAG"].scan_dr(["0" * 32, "0" * 32])

        # empty fifos
        fifo_tap1_content = self.chip["fifo1"].get_data()
        fifo_tap2_content = self.chip["fifo2"].get_data()

        self.chip["JTAG"].scan_ir([BYPASS, DEBUG])
        self.chip["JTAG"].scan_dr([BitLogic("1"), BitLogic("0" * 24 + "10101101")] * 15, word_size=33)

        fifo_tap1_content = self.chip["fifo1"].get_data()
        fifo_tap2_content = self.chip["fifo2"].get_data()

        self.assertNotEqual([int("0" * 24 + "10101101", 2)] * 15, list(fifo_tap1_content))
        self.assertListEqual([int("0" * 24 + "10101101", 2)] * 15, list(fifo_tap2_content))

        # TEST OF SENDING MULTIPLE WORDS BY WRITING DIRECTLY IN JTAG MODULE MEMORY

        # The ring register (DEBUG register) is 32 bits long, so the data have to be arranged like this :
        # [WORD1(dev1) WORD1(dev2) WORD2(dev1) WORD2(dev2) ...]
        data = np.byte(
            [
                0x01,
                0x02,
                0x03,
                0x04,
                0x02,
                0x04,
                0x06,
                0x08,
                0x11,
                0x12,
                0x13,
                0x14,
                0x12,
                0x14,
                0x16,
                0x18,
                0x21,
                0x22,
                0x23,
                0x24,
                0x22,
                0x24,
                0x26,
                0x28,
                0x31,
                0x32,
                0x33,
                0x34,
                0x32,
                0x34,
                0x36,
                0x38,
                0x41,
                0x42,
                0x43,
                0x44,
                0x42,
                0x44,
                0x46,
                0x48,
            ]
        )

        device_number = 2
        word_size_bit = 32
        word_count = 5

        self.chip["JTAG"].scan_ir([DEBUG, DEBUG])

        # empty fifo
        self.chip["fifo1"].get_data()
        self.chip["fifo2"].get_data()

        self.chip["JTAG"].set_data(data)
        self.chip["JTAG"].SIZE = word_size_bit * device_number
        self.chip["JTAG"].set_command("DATA")
        self.chip["JTAG"].WORD_COUNT = word_count

        self.chip["JTAG"].start()
        while not self.chip["JTAG"].READY:
            pass

        fifo_tap1_content = self.chip["fifo1"].get_data()
        fifo_tap2_content = self.chip["fifo2"].get_data()

        expected_result_tap1 = [
            int("0x01020304", 16),
            int("0x11121314", 16),
            int("0x21222324", 16),
            int("0x31323334", 16),
            int("41424344", 16),
        ]
        expected_result_tap2 = [
            int("0x02040608", 16),
            int("0x12141618", 16),
            int("0x22242628", 16),
            int("0x32343638", 16),
            int("42444648", 16),
        ]
        self.assertListEqual(expected_result_tap1, list(fifo_tap1_content))
        self.assertListEqual(expected_result_tap2, list(fifo_tap2_content))

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #24
0
class TestSimJtagGpio(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run([
            os.path.join(os.path.dirname(__file__), 'jtag_tap.v'),
            os.path.join(os.path.dirname(__file__), 'test_SimJtagGpio.v')]
        )

        self.chip = Dut(cnfg_yaml)
        self.chip.init(init_yaml)

    def test_gpio(self):

        ID_CODE = BitLogic('0010')
        BYPASS = BitLogic('1111')
        DEBUG = BitLogic('1000')

        ret_ir = BitLogic('0101')

        # TEST REG INIT
        dev1ret = StdRegister(driver=None, conf=yaml.load(gpio_yaml))
        dev1ret.init()
        dev1ret['F1'] = 0x1
        dev1ret['F2'] = 0x2f
        dev1ret['F3'] = 0x2
        dev1ret['F4'] = 0x17cf4
        self.assertEqual(dev1ret[:], self.chip['DEV1'][:])

        self.chip['DEV1']['F2'] = 0
        self.assertFalse(dev1ret[:] == self.chip['DEV1'][:])

        self.chip.set_configuration(init_yaml)
        self.assertEqual(dev1ret[:], self.chip['DEV1'][:])

        self.chip['jtag'].reset()

        # IR CODE
        ret = self.chip['jtag'].scan_ir([ID_CODE] * 2)
        self.assertEqual(ret, [ret_ir] * 2)

        # ID CODE
        id_code = BitLogic.from_value(0x149B51C3, fmt='I')
        ret = self.chip['jtag'].scan_dr(['0' * 32] * 2)
        self.assertEqual(ret, [id_code] * 2)

        # BYPASS + ID CODE
        bypass_code = BitLogic('0')
        ret = self.chip['jtag'].scan_ir([ID_CODE, BYPASS])
        self.assertEqual(ret, [ret_ir] * 2)
        ret = self.chip['jtag'].scan_dr(['0' * 32, '1'])
        self.assertEqual(ret, [id_code, bypass_code])

        ret = self.chip['jtag'].scan_ir([BYPASS, ID_CODE])
        self.assertEqual(ret, [ret_ir] * 2)
        ret = self.chip['jtag'].scan_dr(['1', '0' * 32])
        self.assertEqual(ret, [bypass_code, id_code])

        # DEBUG
        ret = self.chip['jtag'].scan_ir([DEBUG, DEBUG])
        self.assertEqual(ret, [ret_ir] * 2)

        self.chip['jtag'].scan_dr(['1' * 32, '0' * 1 + '1' * 30 + '0' * 1])
        ret = self.chip['jtag'].scan_dr(['0' * 32, '1' * 32])
        self.assertEqual(ret, [BitLogic('1' * 32), BitLogic('0' * 1 + '1' * 30 + '0' * 1)])
        ret = self.chip['jtag'].scan_dr(['0' * 32, '0' * 32])
        self.assertEqual(ret, [BitLogic('0' * 32), BitLogic('1' * 32)])

        # SHIT IN DEV REG/DEBUG
        self.chip['jtag'].scan_dr([self.chip['DEV1'][:], self.chip['DEV2'][:]])

        # GPIO RETURN
        dev1ret.frombytes(self.chip['gpio_dev1'].get_data())
        self.assertEqual(dev1ret[:], self.chip['DEV1'][:])

        self.assertFalse(dev1ret[:] == self.chip['DEV2'][:])
        dev1ret.frombytes(self.chip['gpio_dev2'].get_data())
        self.assertEqual(dev1ret[:], self.chip['DEV2'][:])

        # JTAG RETURN
        ret = self.chip['jtag'].scan_dr(['0' * 32, '0' * 32])
        dev1ret.set(ret[0])
        self.assertEqual(dev1ret[:], self.chip['DEV1'][:])

        dev1ret.set(ret[1])
        self.assertEqual(dev1ret[:], self.chip['DEV2'][:])

        # REPEATING REGISTER
        self.chip['jtag'].scan_dr([self.chip['DEV'][:]])
        ret1 = self.chip['jtag'].scan_dr([self.chip['DEV'][:]])
        self.chip['jtag'].scan_dr([self.chip['DEV1'][:], self.chip['DEV2'][:]])
        ret2 = self.chip['jtag'].scan_dr([self.chip['DEV1'][:] + self.chip['DEV2'][:]])
        ret3 = self.chip['jtag'].scan_dr([self.chip['DEV1'][:] + self.chip['DEV2'][:]])
        self.assertEqual(ret1[:], ret2[:])
        self.assertEqual(ret2[:], ret3[:])

        # REPEATING SETTING
        self.chip['jtag'].scan_dr(['1' * 32 + '0' * 32])
        ret = self.chip['jtag'].scan_dr(['0' * 32 + '0' * 32])

        self.chip['DEV'].set(ret[0])
        self.assertEqual(self.chip['DEV'][:], BitLogic('0' * 32 + '1' * 32))

        self.chip['jtag'].scan_dr([self.chip['DEV1'][:] + self.chip['DEV2'][:]])
        ret = self.chip['jtag'].scan_dr([self.chip['DEV1'][:] + self.chip['DEV2'][:]])

        self.chip['DEV'].set(ret[0])
        self.assertEqual(self.chip['DEV'][:], self.chip['DEV1'][:] + self.chip['DEV2'][:])

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #25
0
class TestSimJtagGpio(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run([
            os.path.join(os.path.dirname(__file__), 'jtag_tap.v'),
            os.path.join(os.path.dirname(__file__), 'test_SimJtagGpio.v')
        ])

        self.chip = Dut(cnfg_yaml)
        self.chip.init(init_yaml)

    def test_gpio(self):

        ID_CODE = BitLogic('0010')
        BYPASS = BitLogic('1111')
        DEBUG = BitLogic('1000')

        ret_ir = BitLogic('0101')

        # TEST REG INIT
        dev1ret = StdRegister(driver=None, conf=yaml.safe_load(gpio_yaml))
        dev1ret.init()
        dev1ret['F1'] = 0x1
        dev1ret['F2'] = 0x2f
        dev1ret['F3'] = 0x2
        dev1ret['F4'] = 0x17cf4
        self.assertEqual(dev1ret[:], self.chip['DEV1'][:])

        self.chip['DEV1']['F2'] = 0
        self.assertFalse(dev1ret[:] == self.chip['DEV1'][:])

        self.chip.set_configuration(init_yaml)
        self.assertEqual(dev1ret[:], self.chip['DEV1'][:])

        self.chip['JTAG'].reset()

        # IR CODE
        ret = self.chip['JTAG'].scan_ir([ID_CODE] * 2)
        self.assertEqual(ret, [ret_ir] * 2)

        # ID CODE
        id_code = BitLogic.from_value(0x149B51C3, fmt='I')
        ret = self.chip['JTAG'].scan_dr(['0' * 32] * 2)
        self.assertEqual(ret, [id_code] * 2)

        # BYPASS + ID CODE
        bypass_code = BitLogic('0')
        ret = self.chip['JTAG'].scan_ir([ID_CODE, BYPASS])
        self.assertEqual(ret, [ret_ir] * 2)
        ret = self.chip['JTAG'].scan_dr(['0' * 32, '1'])
        self.assertEqual(ret, [id_code, bypass_code])

        ret = self.chip['JTAG'].scan_ir([BYPASS, ID_CODE])
        self.assertEqual(ret, [ret_ir] * 2)
        ret = self.chip['JTAG'].scan_dr(['1', '0' * 32])
        self.assertEqual(ret, [bypass_code, id_code])

        # DEBUG
        ret = self.chip['JTAG'].scan_ir([DEBUG, DEBUG])
        self.assertEqual(ret, [ret_ir] * 2)

        self.chip['JTAG'].scan_dr(['1' * 32, '0' * 1 + '1' * 30 + '0' * 1])
        ret = self.chip['JTAG'].scan_dr(['0' * 32, '1' * 32])
        self.assertEqual(
            ret, [BitLogic('1' * 32),
                  BitLogic('0' * 1 + '1' * 30 + '0' * 1)])
        ret = self.chip['JTAG'].scan_dr(['0' * 32, '0' * 32])
        self.assertEqual(ret, [BitLogic('0' * 32), BitLogic('1' * 32)])

        # SHIT IN DEV REG/DEBUG
        self.chip['JTAG'].scan_dr([self.chip['DEV1'][:], self.chip['DEV2'][:]])

        # GPIO RETURN
        dev1ret.frombytes(self.chip['GPIO_DEV1'].get_data())
        self.assertEqual(dev1ret[:], self.chip['DEV1'][:])

        self.assertFalse(dev1ret[:] == self.chip['DEV2'][:])
        dev1ret.frombytes(self.chip['GPIO_DEV2'].get_data())
        self.assertEqual(dev1ret[:], self.chip['DEV2'][:])

        # JTAG RETURN
        ret = self.chip['JTAG'].scan_dr(['0' * 32, '0' * 32])
        dev1ret.set(ret[0])
        self.assertEqual(dev1ret[:], self.chip['DEV1'][:])

        dev1ret.set(ret[1])
        self.assertEqual(dev1ret[:], self.chip['DEV2'][:])

        # REPEATING REGISTER
        self.chip['JTAG'].scan_dr([self.chip['DEV'][:]])
        ret1 = self.chip['JTAG'].scan_dr([self.chip['DEV'][:]])
        self.chip['JTAG'].scan_dr([self.chip['DEV1'][:], self.chip['DEV2'][:]])
        ret2 = self.chip['JTAG'].scan_dr(
            [self.chip['DEV1'][:] + self.chip['DEV2'][:]])
        ret3 = self.chip['JTAG'].scan_dr(
            [self.chip['DEV1'][:] + self.chip['DEV2'][:]])
        self.assertEqual(ret1[:], ret2[:])
        self.assertEqual(ret2[:], ret3[:])

        # REPEATING SETTING
        self.chip['JTAG'].scan_dr(['1' * 32 + '0' * 32])
        ret = self.chip['JTAG'].scan_dr(['0' * 32 + '0' * 32])

        self.chip['DEV'].set(ret[0])
        self.assertEqual(self.chip['DEV'][:], BitLogic('0' * 32 + '1' * 32))

        self.chip['JTAG'].scan_dr(
            [self.chip['DEV1'][:] + self.chip['DEV2'][:]])
        ret = self.chip['JTAG'].scan_dr(
            [self.chip['DEV1'][:] + self.chip['DEV2'][:]])

        self.chip['DEV'].set(ret[0])
        self.assertEqual(self.chip['DEV'][:],
                         self.chip['DEV1'][:] + self.chip['DEV2'][:])

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #26
0
class TestSimFifo8to32(unittest.TestCase):
    def __init__(self,
                 testname,
                 tb='test_SimFifo8to32.v',
                 bus_drv='basil.utils.sim.BasilBusDriver',
                 bus_split=False):
        super(TestSimFifo8to32, self).__init__(testname)
        self._test_tb = tb
        self._sim_bus = bus_drv
        self._bus_split_def = ()
        if bus_split is not False:
            if bus_split == 'sbus':
                self._bus_split_def = ("BASIL_SBUS", )
            elif bus_split == 'top':
                self._bus_split_def = ("BASIL_TOPSBUS", )

    def setUp(self):
        cocotb_compile_and_run(
            sim_files=[os.path.join(os.path.dirname(__file__), self._test_tb)],
            sim_bus=self._sim_bus,
            extra_defines=self._bus_split_def)

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    def test_io(self):
        for i in range(4):
            self.chip['INTF'].write(0x1000, [i])

        data = []
        iterations = 1000
        i = 0
        while not len(data) == 1:
            if i >= iterations:
                break
            data.extend(self.chip['FIFO'].get_data())
            i += 1
        assert data[0] == 50462976

        self.chip['INTF'].write(0x1000, [4, 5, 6, 7])

        data = []
        iterations = 1000
        i = 0
        while not len(data) == 1:
            if i >= iterations:
                break
            data.extend(self.chip['FIFO'].get_data())
            i += 1
        assert data[0] == 117835012

        self.chip['INTF'].write(0x1000, range(8))

        data = []
        iterations = 1000
        i = 0
        while not len(data) == 2:
            if i >= iterations:
                break
            data.extend(self.chip['FIFO'].get_data())
            i += 1
        assert data[0] == 50462976
        assert data[1] == 117835012

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #27
0
class m26(object):
    ''' Mimosa26 telescope readout with MMC3 hardware.

    Note:
    - Remove not used Mimosa26 planes by commenting out the drivers in the DUT file (i.e. m26.yaml).
    - Set up trigger in DUT configuration file (i.e. m26_configuration.yaml).
    '''
    def __init__(self, conf=None):
        if conf is None:
            conf = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                "m26.yaml")
        logger.info("Loading DUT configuration from file %s" % conf)

        # initialize class
        self.dut = Dut(conf=conf)

    def init(self, init_conf=None, configure_m26=True):
        # initialize hardware
        logging.info("Initializing Telescope...")
        self.dut.init(init_conf=init_conf)
        self.telescope_conf = init_conf

        # check firmware version
        fw_version = self.dut['ETH'].read(0x0000, 1)[0]
        logging.info("Pymosa MMC3 firmware version: %s" % (fw_version))
        if int(self.dut.version) != fw_version:
            raise Exception(
                "Pymosa MMC3 firmware version does not match DUT configuration file (read: %s, require: %s)"
                % (fw_version, int(self.dut.version)))

        # default configuration
        # use self.telescope_conf to store conf dict to telescope data file
        self.telescope_conf["fw_version"] = fw_version
        self.run_id = self.telescope_conf.get('run_id', 'M26_TELESCOPE')
        self.working_dir = self.telescope_conf.get("output_folder", None)
        if not self.working_dir:
            self.working_dir = os.path.join(os.getcwd(), "telescope_data")
        self.working_dir = os.path.normpath(self.working_dir.replace(
            '\\', '/'))
        self.output_filename = self.telescope_conf.get(
            'filename', None)  # default None: filename is generated
        if self.output_filename:
            self.output_filename = os.path.basename(self.output_filename)
        self.run_number = self.telescope_conf.get('run_number', None)
        self.m26_configuration_file = self.telescope_conf.get(
            'm26_configuration_file', None)
        if not self.m26_configuration_file:
            self.m26_configuration_file = 'm26_config/m26_threshold_8.yaml'
        self.m26_jtag_configuration = self.telescope_conf.get(
            'm26_jtag_configuration', True)  # default True
        self.no_data_timeout = self.telescope_conf.get(
            'no_data_timeout', 0)  # default None: no data timeout
        self.scan_timeout = self.telescope_conf.get(
            'scan_timeout', 0)  # default 0: no scan timeout
        self.max_triggers = self.telescope_conf.get(
            'max_triggers', 0)  # default 0: infinity triggers
        self.send_data = self.telescope_conf.get(
            'send_data',
            None)  # default None: do not send data to online monitor
        self.enabled_m26_channels = self.telescope_conf.get(
            'enabled_m26_channels', None)  # default None: all channels enabled

        if not os.path.exists(self.working_dir):
            os.makedirs(self.working_dir)
        logger.info("Storing telescope data in %s" % self.working_dir)

        # configure Mimosa26 sensors
        if configure_m26:
            self.configure_m26()

        # FIFO readout
        self.m26_readout = M26Readout(dut=self.dut)

    def close(self):
        self.dut.close()

    def configure_m26(self,
                      m26_configuration_file=None,
                      m26_jtag_configuration=None):
        '''Configure Mimosa26 sensors via JTAG.
        '''
        if m26_configuration_file:
            self.m26_configuration_file = m26_configuration_file
        else:
            m26_configuration_file = os.path.join(
                os.path.dirname(pymosa.__file__), self.m26_configuration_file)
        if not self.m26_configuration_file:
            raise ValueError('M26 configuration file not provided')
        logger.info('Loading M26 configuration file %s',
                    m26_configuration_file)

        def write_jtag(irs, IR):
            for ir in irs:
                logger.info('Programming M26 JTAG configuration reg %s', ir)
                logger.debug(self.dut[ir][:])
                self.dut['JTAG'].scan_ir([BitLogic(IR[ir])] * 6)
                self.dut['JTAG'].scan_dr([self.dut[ir][:]])[0]

        def check_jtag(irs, IR):
            # read first registers
            ret = {}
            for ir in irs:
                logger.info('Reading M26 JTAG configuration reg %s', ir)
                self.dut['JTAG'].scan_ir([BitLogic(IR[ir])] * 6)
                ret[ir] = self.dut['JTAG'].scan_dr([self.dut[ir][:]])[0]
            # check registers
            for k, v in ret.items():
                if k == "CTRL_8b10b_REG1_ALL":
                    pass
                elif k == "BSR_ALL":
                    pass  # TODO mask clock bits and check others
                elif self.dut[k][:] != v:
                    logger.error("JTAG data does not match %s get=%s set=%s" %
                                 (k, v, self.dut[k][:]))
                else:
                    logger.info("Checking M26 JTAG %s ok" % k)

        # set the clock distributer inputs in correct states.
        self.set_clock_distributer()

        # set M26 configuration file
        self.dut.set_configuration(m26_configuration_file)

        if m26_jtag_configuration is not None:
            self.m26_jtag_configuration = m26_jtag_configuration
        else:
            m26_jtag_configuration = self.m26_jtag_configuration
        if m26_jtag_configuration:
            # reset JTAG; this is important otherwise JTAG programming works not properly.
            self.dut['JTAG'].reset()

            IR = {
                "BSR_ALL": '00101',
                "DEV_ID_ALL": '01110',
                "BIAS_DAC_ALL": '01111',
                "LINEPAT0_REG_ALL": '10000',
                "DIS_DISCRI_ALL": '10001',
                "SEQUENCER_PIX_REG_ALL": '10010',
                "CONTROL_PIX_REG_ALL": '10011',
                "LINEPAT1_REG_ALL": '10100',
                "SEQUENCER_SUZE_REG_ALL": '10101',
                "HEADER_REG_ALL": '10110',
                "CONTROL_SUZE_REG_ALL": '10111',
                "CTRL_8b10b_REG0_ALL": '11000',
                "CTRL_8b10b_REG1_ALL": '11001',
                "RO_MODE1_ALL": '11101',
                "RO_MODE0_ALL": '11110',
                "BYPASS_ALL": '11111'
            }

            irs = [
                "DEV_ID_ALL", "BIAS_DAC_ALL", "BYPASS_ALL", "BSR_ALL",
                "RO_MODE0_ALL", "RO_MODE1_ALL", "DIS_DISCRI_ALL",
                "LINEPAT0_REG_ALL", "LINEPAT1_REG_ALL", "CONTROL_PIX_REG_ALL",
                "SEQUENCER_PIX_REG_ALL", "HEADER_REG_ALL",
                "CONTROL_SUZE_REG_ALL", "SEQUENCER_SUZE_REG_ALL",
                "CTRL_8b10b_REG0_ALL", "CTRL_8b10b_REG1_ALL"
            ]

            # write JTAG configuration
            write_jtag(irs, IR)

            # check if registers are properly programmed by reading them and comparing to settings.
            check_jtag(irs, IR)

            # START procedure
            logger.info('Starting M26')
            temp = self.dut['RO_MODE0_ALL'][:]
            # disable extstart
            for reg in self.dut["RO_MODE0_ALL"]["RO_MODE0"]:
                reg['En_ExtStart'] = 0
                reg['JTAG_Start'] = 0
            self.dut['JTAG'].scan_ir([BitLogic(IR['RO_MODE0_ALL'])] * 6)
            self.dut['JTAG'].scan_dr([self.dut['RO_MODE0_ALL'][:]])
            # JTAG start
            for reg in self.dut["RO_MODE0_ALL"]["RO_MODE0"]:
                reg['JTAG_Start'] = 1
            self.dut['JTAG'].scan_ir([BitLogic(IR['RO_MODE0_ALL'])] * 6)
            self.dut['JTAG'].scan_dr([self.dut['RO_MODE0_ALL'][:]])
            for reg in self.dut["RO_MODE0_ALL"]["RO_MODE0"]:
                reg['JTAG_Start'] = 0
            self.dut['JTAG'].scan_ir([BitLogic(IR['RO_MODE0_ALL'])] * 6)
            self.dut['JTAG'].scan_dr([self.dut['RO_MODE0_ALL'][:]])
            # write original configuration
            self.dut['RO_MODE0_ALL'][:] = temp
            self.dut['JTAG'].scan_ir([BitLogic(IR['RO_MODE0_ALL'])] * 6)
            self.dut['JTAG'].scan_dr([self.dut['RO_MODE0_ALL'][:]])
            # readback?
            self.dut['JTAG'].scan_ir([BitLogic(IR['RO_MODE0_ALL'])] * 6)
            self.dut['JTAG'].scan_dr([self.dut['RO_MODE0_ALL'][:]] * 6)
        else:
            logger.info("Skipping M26 JTAG configuration")

    def set_clock_distributer(self, clk=0, start=1, reset=0, speak=1):
        # Default values -same as in GUI- (self, clk=0, start=1, reset=0, speak=1)
        self.dut["START_RESET"]["CLK"] = clk
        self.dut["START_RESET"]["START"] = start
        self.dut["START_RESET"]["RESET"] = reset
        self.dut["START_RESET"]["SPEAK"] = speak
        self.dut["START_RESET"].write()

    def reset(self, reset_time=2):
        self.dut["START_RESET"]["RESET"] = 1
        self.dut["START_RESET"].write()
        sleep(reset_time)
        self.dut["START_RESET"]["RESET"] = 0
        self.dut["START_RESET"].write()

    def scan(self):
        '''Scan Mimosa26 telescope loop.
        '''
        with self.readout(enabled_m26_channels=self.enabled_m26_channels):
            got_data = False
            start = time()
            while not self.stop_scan:
                sleep(1.0)
                if not got_data:
                    if self.m26_readout.data_words_per_second()[0] > 0:
                        got_data = True
                        logging.info('Taking data...')
                        if self.max_triggers:
                            self.pbar = tqdm(total=self.max_triggers, ncols=80)
                        else:
                            self.pbar = tqdm(total=self.scan_timeout, ncols=80)
                else:
                    triggers = self.dut['TLU']['TRIGGER_COUNTER']
                    try:
                        if self.max_triggers:
                            self.pbar.update(triggers - self.pbar.n)
                        else:
                            self.pbar.update(time() - start - self.pbar.n)
                    except ValueError:
                        pass
                    if self.max_triggers and triggers >= self.max_triggers:
                        self.stop_scan = True
                        self.pbar.close()
                        logging.info('Trigger limit was reached: %i' %
                                     self.max_triggers)

        logging.info('Total amount of triggers collected: %d',
                     self.dut['TLU']['TRIGGER_COUNTER'])

    def analyze(self):
        pass

    def start(self):
        '''Start Mimosa26 telescope scan.
        '''
        self.stop_scan = False
        signal.signal(signal.SIGINT, self._signal_handler)
        logging.info('Press Ctrl-C to stop run')

        # check for filename that is not in use
        while True:
            if not self.output_filename and self.run_number:
                filename = 'run_' + str(self.run_number) + '_' + self.run_id

            else:
                if self.output_filename:
                    filename = self.output_filename
                else:
                    filename = strftime("%Y%m%d-%H%M%S") + '_' + self.run_id
            if filename in [
                    os.path.splitext(f)[0]
                    for f in os.listdir(self.working_dir)
                    if os.path.isfile(os.path.join(self.working_dir, f))
            ]:
                if not self.output_filename and self.run_number:
                    self.run_number += 1  # increase run number and try again
                    continue
                else:
                    raise IOError("Filename %s already exists." % filename)
            else:
                self.run_filename = os.path.join(self.working_dir, filename)
                break

        # set up logger
        self.fh = logging.FileHandler(self.run_filename + '.log')
        self.fh.setLevel(logging.DEBUG)
        self.fh.setFormatter(logging.Formatter(FORMAT))
        self.logger = logging.getLogger()
        self.logger.addHandler(self.fh)

        with self.access_file():
            save_configuration_dict(self.raw_data_file.h5_file,
                                    'configuration', self.telescope_conf)
            self.scan()

        self.logger.removeHandler(self.fh)

        logging.info('Data Output Filename: %s', self.run_filename + '.h5')
        self.analyze()

    @contextmanager
    def readout(self, *args, **kwargs):
        try:
            self.start_readout(*args, **kwargs)
            yield
        finally:
            try:
                self.stop_readout(timeout=10.0)
            except Exception:
                # in case something fails, call this on last resort
                if self.m26_readout.is_running:
                    self.m26_readout.stop(timeout=0.0)

    def start_readout(self, *args, **kwargs):
        '''Start readout of Mimosa26 sensors.
        '''
        enabled_m26_channels = kwargs.get(
            'enabled_m26_channels',
            None)  # None will enable all existing Mimosa26 channels
        self.m26_readout.start(fifos="SITCP_FIFO",
                               callback=self.handle_data,
                               errback=self.handle_err,
                               reset_rx=True,
                               reset_fifo=True,
                               no_data_timeout=self.no_data_timeout,
                               enabled_m26_channels=enabled_m26_channels)

        self.dut['TLU']['MAX_TRIGGERS'] = self.max_triggers
        self.dut['TLU']['TRIGGER_ENABLE'] = True
        self.m26_readout.print_readout_status()

        def timeout():
            self.stop_scan = True
            logging.info('Scan timeout was reached')

        self.scan_timeout_timer = Timer(self.scan_timeout, timeout)
        if self.scan_timeout:
            self.scan_timeout_timer.start()

    def stop_readout(self, timeout=10.0):
        '''Stop readout of Mimosa26 sensors.
        '''
        self.scan_timeout_timer.cancel()
        self.dut['TLU']['TRIGGER_ENABLE'] = False
        self.m26_readout.stop(timeout=timeout)
        self.m26_readout.print_readout_status()

    @contextmanager
    def access_file(self):
        try:
            self.open_file()
            yield
        finally:
            try:
                self.close_file()
            except Exception:
                # in case something fails, call this on last resort
                self.raw_data_file = None

    def open_file(self):
        self.raw_data_file = open_raw_data_file(filename=self.run_filename,
                                                mode='w',
                                                title=os.path.basename(
                                                    self.run_filename),
                                                socket_address=self.send_data)
        if self.raw_data_file.socket:
            # send reset to indicate a new scan for the online monitor
            send_meta_data(self.raw_data_file.socket, None, name='Reset')

    def close_file(self):
        # close file object
        self.raw_data_file.close()
        # delete file object
        self.raw_data_file = None

    def handle_data(self, data, new_file=False, flush=True):
        '''Handling of raw data and meta data during readout.
        '''
        for data_tuple in data:
            if data_tuple is None:
                continue
            self.raw_data_file.append(data_iterable=data_tuple,
                                      new_file=new_file,
                                      flush=flush)

    def handle_err(self, exc):
        '''Handling of error messages during readout.
        '''
        msg = '%s' % exc[1]
        if msg:
            logging.error('%s%s Aborting run...', msg, msg[-1])
        else:
            logging.error('Aborting run...')
        self.stop_scan = True

    def _signal_handler(self, signum, frame):
        signal.signal(
            signal.SIGINT, signal.SIG_DFL
        )  # setting default handler... pressing Ctrl-C a second time will kill application
        logging.info('Pressed Ctrl-C')
        self.stop_scan = True
Exemple #28
0
class TestSimSpi(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run([os.getcwd() + '/test_SimSpi.v'])

        self.chip = Dut(cnfg_yaml)
        self.chip.init()
    
    def test_io(self):
        size = self.chip['spi'].get_size()
        self.chip['gpio'].reset()
        self.assertEqual(size, 16 * 8)

        self.chip['spi'].set_data(range(16))
        ret = self.chip['spi'].get_data(size=16, addr=0)  # to read back what was written
        self.assertEqual(ret.tolist(), range(16))

        self.chip['spi'].set_data(range(16))
        ret = self.chip['spi'].get_data(addr=0)  # to read back what was written
        self.assertEqual(ret.tolist(), range(16))

        self.chip['spi'].start()
        while(not self.chip['spi'].is_done()):
            pass

        ret = self.chip['spi'].get_data()  # read back what was received (looped)
        self.assertEqual(ret.tolist(), range(16))
        
        # ext_start
        self.chip['spi'].set_en(1)
        self.assertEqual(self.chip['spi'].get_en(), 1)
        
        self.chip['PULSE_GEN'].set_delay(1)
        self.chip['PULSE_GEN'].set_width(1+size)
        self.chip['PULSE_GEN'].set_repeat(1)
        self.assertEqual(self.chip['PULSE_GEN'].get_delay(), 1)
        self.assertEqual(self.chip['PULSE_GEN'].get_width(), 1+size)
        self.assertEqual(self.chip['PULSE_GEN'].get_repeat(), 1)
        
        self.chip['PULSE_GEN'].start()
        while(not self.chip['PULSE_GEN'].is_done()):
            pass
            
        ret = self.chip['spi'].get_data()  # read back what was received (looped)
        self.assertEqual(ret.tolist(), range(16))
        
        # spi_rx
        ret = self.chip['spi_rx'].get_en()
        self.assertEqual(ret, False)

        self.chip['spi_rx'].set_en(True)
        ret = self.chip['spi_rx'].get_en()
        self.assertEqual(ret, True)

        self.chip['spi'].start()
        while(not self.chip['spi'].is_done()):
            pass

        ret = self.chip['fifo'].get_fifo_size()
        self.assertEqual(ret, 32)

        ret = self.chip['fifo'].get_data()

        data0 = ret.astype(np.uint8)
        data1 = np.right_shift(ret, 8).astype(np.uint8)
        data = np.reshape(np.vstack((data1, data0)), -1, order='F')
        self.assertEqual(data.tolist(), range(16))
    
    def test_dut_iter(self):
        
        conf = yaml.safe_load(cnfg_yaml)
        def iter_conf():
            for item in conf['registers']:
                yield item
            for item in conf['hw_drivers']:
                yield item
            for item in conf['transfer_layer']:
                yield item
            
        
        for mod, mcnf in zip(self.chip, iter_conf()):
            self.assertEqual(mod.name, mcnf['name'])
            self.assertEqual(mod.__class__.__name__, mcnf['type'])
    
    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #29
0
class TestSimSeq(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run([os.getcwd() + '/test_SimSeq.v'])

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    def test_io(self):
        self.assertEqual(self.chip['SEQ_GEN'].get_mem_size(), 8 * 1024)

        self.chip['SEQ']['S0'][0] = 1
        self.chip['SEQ']['S1'][1] = 1
        self.chip['SEQ']['S2'][2] = 1
        self.chip['SEQ']['S3'][3] = 1

        self.chip['SEQ']['S4'][12] = 1
        self.chip['SEQ']['S5'][13] = 1
        self.chip['SEQ']['S6'][14] = 1
        self.chip['SEQ']['S7'][15] = 1

        pattern = [
            0x01, 0x02, 0x04, 0x08, 0, 0, 0, 0, 0, 0, 0, 0, 0x10, 0x20, 0x40,
            0x80
        ]

        self.chip['SEQ'].write(16)

        ret = self.chip['SEQ'].get_data(size=16)
        self.assertEqual(ret.tolist(), pattern)

        rec_size = 16 * 4 + 8
        self.chip['SEQ_REC'].set_en_ext_start(True)
        self.chip['SEQ_REC'].set_size(rec_size)

        self.chip['PULSE_GEN'].set_delay(1)
        self.chip['PULSE_GEN'].set_width(1)

        self.assertEqual(self.chip['PULSE_GEN'].get_delay(), 1)
        self.assertEqual(self.chip['PULSE_GEN'].get_width(), 1)

        self.chip['SEQ'].set_repeat(4)
        self.chip['SEQ'].set_en_ext_start(True)
        self.chip['SEQ'].set_size(16)
        # self.chip['SEQ'].start()

        self.chip['PULSE_GEN'].start()

        while (not self.chip['SEQ'].is_done()):
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        self.assertEqual(
            ret.tolist(), [0x0] * 2 + pattern * 4 +
            [0x80] * 6)  # 2 clk delay + pattern x4 + 6 x last pattern

        #
        self.chip['SEQ'].set_repeat_start(12)
        self.chip['PULSE_GEN'].start()

        while (not self.chip['SEQ'].is_done()):
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        self.assertEqual(
            ret.tolist(),
            [0x80] * 2 + pattern + pattern[12:] * 3 + [0x80] * 3 * 12 +
            [0x80] * 6)  # 2 clk delay 0x80 > from last pattern + ...

        self.chip['SEQ'].set_wait(4)
        self.chip['PULSE_GEN'].start()

        while (not self.chip['SEQ'].is_done()):
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        lpat = pattern[12:] + [0x80] * 4
        self.assertEqual(ret.tolist(), [0x80] * 2 + pattern + [0x80] * 4 +
                         lpat * 3 + [0x80] * (3 * 12 - 4 * 4) + [0x80] * 6)

        #
        rec_size = rec_size * 3
        self.chip['SEQ_REC'].set_size(rec_size)
        self.chip['SEQ'].set_clk_divide(3)
        self.chip['SEQ'].set_wait(3)
        self.chip['PULSE_GEN'].start()

        while (not self.chip['SEQ'].is_done()):
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        lpat = pattern[12:] + [0x80] * 3
        mu_pat = pattern + [0x80] * 3 + lpat * 3
        fm = []
        for i in mu_pat:
            fm += [i, i, i]
        self.assertEqual(ret.tolist(), [0x80] * 2 + fm + [0x80] * 94)

        #
        self.chip['SEQ'].set_wait(0)
        self.chip['PULSE_GEN'].start()

        while (not self.chip['SEQ'].is_done()):
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        lpat = pattern[12:]
        mu_pat = pattern + lpat * 3
        fm = []
        for i in mu_pat:
            fm += [i, i, i]
        self.assertEqual(ret.tolist(),
                         [0x80] * 2 + fm + [0x80] * (94 + 4 * 3 * 3))

        # nested loop test
        pattern = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
        self.chip['SEQ'].set_data(pattern)
        self.chip['SEQ'].set_repeat(4)
        self.chip['SEQ'].set_repeat_start(2)
        self.chip['SEQ'].set_nested_start(8)
        self.chip['SEQ'].set_nested_stop(12)
        self.chip['SEQ'].set_nested_repeat(3)
        self.chip['SEQ'].set_clk_divide(1)
        self.chip['PULSE_GEN'].start()

        while (not self.chip['SEQ'].is_done()):
            pass

        exp_pattern = [0x10, 0x10]
        exp_pattern += pattern[0:2]
        rep = pattern[2:8]
        rep += pattern[8:12] * 3
        rep += pattern[12:16]
        exp_pattern += rep * 4
        exp_pattern += [16] * 124

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        self.assertEqual(ret.tolist(), exp_pattern)

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #30
0
class SensorIVScan(object):
    scan_id = 'sensor_iv_scan'

    def __init__(self, scan_config, device_config=None):
        self.config = scan_config
        self.run_name = time.strftime("%Y%m%d_%H%M%S") + '_' + self.scan_id
        self.output_filename = os.path.join(OUTPUT_DIR,
                                            self.config['module_name'],
                                            self.run_name)
        self.log = logging.getLogger(self.__class__.__name__)

        if device_config is None:
            device_config = os.path.join(
                os.path.abspath(os.path.dirname(__file__)), 'sensor_iv.yaml')
        self.devices = Dut(device_config)

    def init(self):
        self.devices.init()

        self.devices['Sourcemeter'].source_volt()
        self.devices['Sourcemeter'].set_voltage_range(1000)

        if not os.path.isdir(OUTPUT_DIR):
            os.mkdir(OUTPUT_DIR)
        if not os.path.isdir(os.path.dirname(self.output_filename)):
            os.mkdir(os.path.dirname(self.output_filename))

        self.h5_file = tb.open_file(self.output_filename + '.h5',
                                    mode='w',
                                    title=self.scan_id)
        self.h5_file.create_group(self.h5_file.root, 'configuration',
                                  'Configuration')
        run_config_table = self.h5_file.create_table(
            self.h5_file.root.configuration,
            name='run_config',
            title='Run config',
            description=RunConfigTable)

        for key, value in {
                'scan_id': self.scan_id,
                'run_name': self.run_name,
                'module': self.config['module_name'],
                'chip_type': self.config['chip_type']
        }.items():
            row = run_config_table.row
            row['attribute'] = key
            row['value'] = value
            row.append()
        scan_cfg_table = self.h5_file.create_table(
            self.h5_file.root.configuration,
            name='scan_config',
            title='Scan configuration',
            description=RunConfigTable)
        for key, value in self.config.items():
            row = scan_cfg_table.row
            row['attribute'] = key
            row['value'] = value
            row.append()
        self.raw_data_table = self.h5_file.create_table(
            self.h5_file.root,
            name='raw_data',
            title='Raw data',
            description=RawDataTable)

    def __enter__(self):
        self.init()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.devices.close()

    def start(self):
        try:
            self._scan()
        except KeyboardInterrupt:
            pass
        finally:
            self._ramp_hv_to(self.devices['Sourcemeter'], 0)
            self.devices['Sourcemeter'].off()
            self.h5_file.close()
            self.devices.close()
        invert = self.config['VBIAS_stop'] < 0
        plot(self.output_filename + '.h5', invert_x=invert)

    def _get_voltage(self):
        ret = self.devices['Sourcemeter'].get_voltage()
        if ',' in ret:
            return float(ret.split(',')[0])
        else:
            return float(ret)

    def _get_current(self):
        ret = self.devices['Sourcemeter'].get_current()
        if ',' in ret:
            return float(ret.split(',')[1])
        else:
            return float(ret)

    def _ramp_hv_to(self, dev, target, verbose=True):
        if not dev.get_on():
            dev.set_voltage(0)
            dev.on()

        start = int(self._get_voltage())
        target = int(target)

        if abs(start - target) > 10:
            stepsize = 2
        elif abs(start - target) > 100:
            stepsize = 10
        else:
            dev.set_voltage(target)
            return

        dev.source_volt()
        if abs(target) < 0.2:
            dev.set_voltage_range(0.2)
        elif abs(target) < 2:
            dev.set_voltage_range(2)
        elif abs(target) < 20:
            dev.set_voltage_range(20)
        elif abs(target) < 200:
            dev.set_voltage_range(200)
        else:
            dev.set_voltage_range(1000)

        voltage_step = stepsize if target > start else -1 * stepsize
        add = 1 if target > start else -1

        if verbose:
            self.log.info('Ramping bias voltage to {} V...'.format(target))
            pbar = tqdm(total=len(range(start, target + add, voltage_step)),
                        unit=' V')
        for v in range(start, target + add, voltage_step):
            dev.set_voltage(v)
            if verbose:
                pbar.update(1)
            time.sleep(0.5)
        if verbose:
            pbar.close()
        dev.set_voltage(target)

    def _scan(self):
        '''
        Sensor IV scan main loop

        Parameters
        ----------
        VBIAS_start : int
            First bias voltage to scan
        VBIAS_stop : int
            Last bias voltage to scan. This value is included in the scan.
        VBIAS_step : int
            Stepsize to increase the bias voltage by in every step.
        '''

        module_name = self.config.get('module_name', 'module_0')
        VBIAS_start = self.config.get('VBIAS_start', 0)
        VBIAS_stop = self.config.get('VBIAS_stop', -5)
        VBIAS_step = self.config.get('VBIAS_step', -1)
        hv_current_limit = self.config.get('hv_current_limit', 1e-6)
        samples = self.config.get('samples', 1)

        try:
            self.devices['Sourcemeter'].off()
            self.devices['Sourcemeter'].set_voltage(0)
            self.devices['Sourcemeter'].set_current_limit(hv_current_limit)
            self.devices['Sourcemeter'].on()

            add = 1 if VBIAS_stop > 0 else -1
            pbar = tqdm(total=abs(VBIAS_stop), unit='Volt')

            last_v = 0
            for v_bias in range(VBIAS_start, VBIAS_stop + add, VBIAS_step):
                self.devices['Sourcemeter'].set_voltage(v_bias)

                # Wait until stable
                last_val = 0
                for _ in range(100):
                    val = self._get_current()
                    if abs(last_val - val) < abs(0.1 * val):
                        break
                    last_val = val
                else:
                    self.log.warning('Current is not stabilizing!')
                    break

                # Take 'samples' measurements and use mean as value
                c_arr = []
                for _ in range(samples):
                    c_arr.append(self._get_current())
                    time.sleep(0.1)
                current = np.mean(c_arr)
                row = self.raw_data_table.row
                row['voltage'] = v_bias
                row['current'] = current
                row['current_error'] = np.std(c_arr)
                row.append()
                self.raw_data_table.flush()
                pbar.update(abs(v_bias) - last_v)
                last_v = abs(v_bias)

                # Abort scan if in current limit
                if abs(current) >= hv_current_limit * 0.98:
                    self.log.error('Current limit reached. Aborting scan!')
                    break

            pbar.close()
            self.log.info('Scan finished')
        except Exception as e:
            self.log.error('An error occurred: %s' % e)
        finally:
            self._ramp_hv_to(self.devices['Sourcemeter'], 0)
Exemple #31
0
class TestSram(unittest.TestCase):
    def setUp(self):

        fw_path = get_basil_dir() + "/firmware/modules"
        cocotb_compile_and_run(
            [
                fw_path + "/gpio/gpio.v",
                fw_path + "/utils/reset_gen.v",
                fw_path + "/utils/bus_to_ip.v",
                fw_path + "/rrp_arbiter/rrp_arbiter.v",
                fw_path + "/utils/ODDR_sim.v",
                fw_path + "/utils/generic_fifo.v",
                fw_path + "/utils/cdc_pulse_sync.v",
                fw_path + "/utils/fx2_to_bus.v",
                fw_path + "/pulse_gen/pulse_gen.v",
                fw_path + "/pulse_gen/pulse_gen_core.v",
                fw_path + "/sram_fifo/sram_fifo_core.v",
                fw_path + "/sram_fifo/sram_fifo.v",
                os.path.dirname(__file__) + "/../firmware/src/sram_test.v",
                os.path.dirname(__file__) + "/../tests/tb.v",
            ],
            top_level="tb",
            sim_bus="basil.utils.sim.SiLibUsbBusDriver",
        )

        with open(os.path.dirname(__file__) + "/../sram_test.yaml", "r") as f:
            cnfg = yaml.load(f)

        # change to simulation interface
        cnfg["transfer_layer"][0]["type"] = "SiSim"

        self.chip = Dut(cnfg)
        self.chip.init()

    def test_simple(self):
        self.chip["CONTROL"]["COUNTER_EN"] = 1
        self.chip["CONTROL"].write()
        self.chip["CONTROL"].write()
        self.chip["CONTROL"]["COUNTER_EN"] = 0
        self.chip["CONTROL"].write()
        for _ in range(10):
            self.chip["CONTROL"].write()

        ret = self.chip["fifo"].get_data()

        self.chip["CONTROL"]["COUNTER_EN"] = 1
        self.chip["CONTROL"].write()
        self.chip["CONTROL"].write()
        self.chip["CONTROL"].write()
        self.chip["CONTROL"]["COUNTER_EN"] = 0
        for _ in range(10):
            self.chip["CONTROL"].write()

        ret = np.hstack((ret, self.chip["fifo"].get_data()))

        x = np.arange(175 * 4, dtype=np.uint8)
        x.dtype = np.uint32

        self.assertTrue(np.alltrue(ret == x))

        self.chip["fifo"].reset()

        self.chip["CONTROL"]["COUNTER_EN"] = 1
        self.chip["CONTROL"].write()
        self.chip["CONTROL"].write()

        self.chip["CONTROL"]["COUNTER_EN"] = 0
        self.chip["CONTROL"].write()
        self.chip["CONTROL"].write()
        self.chip["CONTROL"].write()

        ret = np.hstack((ret, self.chip["fifo"].get_data()))

        x = np.arange(245 * 4, dtype=np.uint8)
        x.dtype = np.uint32

        self.assertEqual(ret.tolist(), x.tolist())

    def test_full(self):
        self.chip["CONTROL"]["COUNTER_EN"] = 1
        self.chip["CONTROL"].write()

        for _ in range(2):
            self.chip["fifo"].get_fifo_size()

        self.chip["CONTROL"]["COUNTER_EN"] = 0
        self.chip["CONTROL"].write()

        for _ in range(10):
            self.chip["CONTROL"].write()

        size = self.chip["fifo"].get_fifo_size()
        self.assertEqual(size, 512)

        ret = self.chip["fifo"].get_data()
        ret = np.hstack((ret, self.chip["fifo"].get_data()))

        x = np.arange(203 * 4, dtype=np.uint8)
        x.dtype = np.uint32

        self.assertTrue(np.alltrue(ret == x))

    def test_overflow(self):
        self.chip["CONTROL"]["COUNTER_EN"] = 1
        self.chip["CONTROL"].write()

        for _ in range(20):
            self.chip["fifo"].get_fifo_size()

        self.chip["CONTROL"]["COUNTER_EN"] = 0
        self.chip["CONTROL"].write()

        for _ in range(10):
            self.chip["CONTROL"].write()

        ret = self.chip["fifo"].get_data()
        while self.chip["fifo"].get_fifo_size():
            ret = np.hstack((ret, self.chip["fifo"].get_data()))

        x = np.arange((128 + 1023) * 4, dtype=np.uint8)
        x.dtype = np.uint32

        self.assertTrue(np.alltrue(ret == x))

        self.chip["pulse"].set_delay(1)
        self.chip["pulse"].set_width(1)
        self.chip["pulse"].start()

        ret = self.chip["fifo"].get_data()
        x = np.arange((128 + 1023) * 4, (128 + 1023 + 1) * 4, dtype=np.uint8)
        x.dtype = np.uint32

        self.assertEqual(ret, x)

    def test_single(self):

        self.chip["pulse"].set_delay(1)
        self.chip["pulse"].set_width(1)
        self.chip["pulse"].start()

        self.assertEqual(self.chip["fifo"].get_data().tolist(), [0x03020100])

        self.chip["pulse"].start()

        self.assertEqual(self.chip["fifo"].get_data().tolist(), [0x07060504])

    def test_pattern(self):
        self.chip["PATTERN"] = 0xAA5555AA
        self.chip["PATTERN"].write()

        self.chip["CONTROL"]["PATTERN_EN"] = 1
        self.chip["CONTROL"].write()
        self.chip["CONTROL"]["PATTERN_EN"] = 0
        self.chip["CONTROL"].write()
        for _ in range(5):
            self.chip["CONTROL"].write()

        self.assertEqual(self.chip["fifo"].get_data().tolist(), [0xAA5555AA] * 35)

    def test_direct(self):
        self.chip["CONTROL"]["COUNTER_DIRECT"] = 1
        self.chip["CONTROL"].write()

        size = 648
        base_data_addr = self.chip["fifo"]._conf["base_data_addr"]

        ret = self.chip["intf"].read(base_data_addr, size=size)
        ret = np.hstack((ret, self.chip["intf"].read(base_data_addr, size=size)))

        x = np.arange(size * 2, dtype=np.uint8)
        self.assertEqual(ret.tolist(), x.tolist())

    def test_continouse(self):
        self.chip["pulse"].set_delay(35)
        self.chip["pulse"].set_width(3)
        self.chip["pulse"].set_repeat(0)
        self.chip["pulse"].start()

        i = 0
        error = False
        for _ in range(100):
            ret = self.chip["fifo"].get_data()

            x = np.arange(i * 4, (i + ret.shape[0]) * 4, dtype=np.uint8)
            x.dtype = np.uint32

            i += ret.shape[0]

            ok = np.alltrue(ret == x)
            # print 'OK?', ok, ret.shape[0], i, k
            if not ok:
                error = True
                break

        self.assertFalse(error)

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #32
0
class TestSimTlu(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run(
            [os.path.join(os.path.dirname(__file__), 'test_SimTlu.v')])

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    def test_simple_trigger_veto(self):
        self.chip['tlu'].TRIGGER_COUNTER = 0
        self.chip['tlu'].TRIGGER_MODE = 0
        self.chip['tlu'].TRIGGER_SELECT = 2
        self.chip['tlu'].TRIGGER_VETO_SELECT = 2
        #         self.chip['CONTROL']['ENABLE'] = 1
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        self.chip['gpio'].set_data([0x07])  # trigger + veto
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        #         self.chip['CONTROL']['ENABLE'] = 0
        self.chip['gpio'].set_data([0x00])

        self.assertEqual(self.chip['sram'].get_fifo_int_size(), 1)
        self.assertEqual(self.chip['tlu'].TRIGGER_COUNTER, 1)

        data = self.chip['sram'].get_data()
        self.assertEqual(data[0], 0x80000000 + 0)

    def test_simple_trigger_veto_disabled(self):
        self.chip['tlu'].TRIGGER_COUNTER = 0
        self.chip['tlu'].TRIGGER_MODE = 0
        self.chip['tlu'].TRIGGER_SELECT = 2
        self.chip['tlu'].TRIGGER_VETO_SELECT = 252
        #         self.chip['CONTROL']['ENABLE'] = 1
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU
        self.chip['gpio'].set_data([0x01
                                    ])  # issue a second time, wait for reset

        self.chip['gpio'].set_data([0x07])  # trigger + veto
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        #         self.chip['CONTROL']['ENABLE'] = 0
        self.chip['gpio'].set_data([0x00])

        self.assertEqual(self.chip['sram'].get_fifo_int_size(), 2)
        self.assertEqual(self.chip['tlu'].TRIGGER_COUNTER, 2)

        data = self.chip['sram'].get_data()
        self.assertEqual(data[0], 0x80000000 + 0)
        self.assertEqual(data[1], 0x80000000 + 1)

    def test_simple_trigger_threshold(self):
        self.chip['tlu'].TRIGGER_COUNTER = 0
        self.chip['tlu'].TRIGGER_MODE = 0
        self.chip['tlu'].TRIGGER_SELECT = 4  # select single pulse trigger
        self.chip['tlu'].TRIGGER_THRESHOLD = 1  # at least two clock cycles
        #         self.chip['CONTROL']['ENABLE'] = 1
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU
        self.chip['gpio'].set_data([0x01
                                    ])  # issue a second time, wait for reset

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        #         self.chip['CONTROL']['ENABLE'] = 0
        self.chip['gpio'].set_data([0x00])

        self.assertEqual(self.chip['sram'].get_fifo_int_size(), 2)
        self.assertEqual(self.chip['tlu'].TRIGGER_COUNTER, 2)

        data = self.chip['sram'].get_data()
        self.assertEqual(data[0], 0x80000000 + 0)
        self.assertEqual(data[1], 0x80000000 + 1)

        self.chip['tlu'].TRIGGER_COUNTER = 0
        self.chip['tlu'].TRIGGER_THRESHOLD = 2  # at least two clock cycles

        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        #         self.chip['CONTROL']['ENABLE'] = 0
        self.chip['gpio'].set_data([0x00])

        self.assertEqual(self.chip['sram'].get_fifo_int_size(), 0)
        self.assertEqual(self.chip['tlu'].TRIGGER_COUNTER, 0)

    def test_simple_trigger_max_triggers(self):
        self.chip['tlu'].TRIGGER_COUNTER = 0
        self.chip['tlu'].MAX_TRIGGERS = 2
        self.chip['tlu'].TRIGGER_MODE = 0
        self.chip['tlu'].TRIGGER_SELECT = 2
        self.chip['tlu'].TRIGGER_VETO_SELECT = 252
        #         self.chip['CONTROL']['ENABLE'] = 1
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        #         self.chip['CONTROL']['ENABLE'] = 0
        self.chip['gpio'].set_data([0x00])

        self.assertEqual(self.chip['sram'].get_fifo_int_size(), 2)
        self.assertEqual(self.chip['tlu'].TRIGGER_COUNTER, 2)

        data = self.chip['sram'].get_data()
        self.assertEqual(data[0], 0x80000000 + 0)
        self.assertEqual(data[1], 0x80000000 + 1)

    def test_simple_trigger(self):
        self.chip['tlu'].TRIGGER_COUNTER = 10
        self.chip['tlu'].TRIGGER_MODE = 0
        self.chip['tlu'].TRIGGER_SELECT = 1
        self.chip['tlu'].TRIGGER_VETO_SELECT = 0
        #         self.chip['CONTROL']['ENABLE'] = 1
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        readings = 0
        while (self.chip['sram'].get_fifo_int_size() < 4 and readings < 1000):
            readings += 1

#         self.chip['CONTROL']['ENABLE'] = 0
        self.chip['gpio'].set_data([0x00])

        self.assertGreaterEqual(self.chip['sram'].get_fifo_int_size(), 4)
        self.assertGreaterEqual(self.chip['tlu'].TRIGGER_COUNTER, 14)

        data = self.chip['sram'].get_data()
        self.assertEqual(data[0], 0x80000000 + 10)
        self.assertEqual(data[1], 0x80000000 + 11)
        self.assertEqual(data[2], 0x80000000 + 12)
        self.assertEqual(data[3], 0x80000000 + 13)

    def test_tlu_trigger_handshake(self):
        self.chip['tlu'].TRIGGER_COUNTER = 0
        self.chip['tlu'].TRIGGER_MODE = 3
        self.chip['tlu'].TRIGGER_VETO_SELECT = 255
        self.chip['tlu'].EN_TLU_VETO = 0
        #         self.chip['tlu'].DATA_FORMAT = 2
        #         self.chip['tlu'].TRIGGER_LOW_TIMEOUT = 5
        #         self.chip['tlu'].TRIGGER_HANDSHAKE_ACCEPT_WAIT_CYCLES = 0
        #         self.chip['tlu'].HANDSHAKE_BUSY_VETO_WAIT_CYCLES = 0
        #         self.chip['CONTROL']['ENABLE'] = 1
        self.chip['gpio'].set_data([0x01])

        readings = 0
        while (self.chip['sram'].get_fifo_int_size() < 4 and readings < 1000):
            readings += 1


#         self.chip['CONTROL']['ENABLE'] = 0
        self.chip['gpio'].set_data([0x00])

        self.assertGreaterEqual(self.chip['sram'].get_fifo_int_size(), 4)
        self.assertGreaterEqual(self.chip['tlu'].TRIGGER_COUNTER, 4)
        self.assertGreaterEqual(self.chip['tlu'].CURRENT_TLU_TRIGGER_NUMBER, 3)

        data = self.chip['sram'].get_data()
        self.assertEqual(data[0], 0x80000000)
        self.assertEqual(data[1], 0x80000001)
        self.assertEqual(data[2], 0x80000002)
        self.assertEqual(data[3], 0x80000003)

    def test_tlu_trigger_handshake_veto(self):
        self.chip['tlu'].TRIGGER_COUNTER = 0
        self.chip['tlu'].TRIGGER_MODE = 3
        self.chip['tlu'].TRIGGER_VETO_SELECT = 1
        self.chip['tlu'].EN_TLU_VETO = 1
        #         self.chip['CONTROL']['ENABLE'] = 1
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        readings = 0
        while (self.chip['sram'].get_fifo_int_size() == 0 and readings < 1000):
            readings += 1

        self.assertEqual(self.chip['sram'].get_fifo_int_size(), 0)
        self.assertEqual(self.chip['tlu'].TRIGGER_COUNTER, 0)
        self.assertEqual(self.chip['tlu'].CURRENT_TLU_TRIGGER_NUMBER, 0)

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #33
0
class TestSimTlu(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run(
            [os.path.join(os.path.dirname(__file__), 'test_SimTlu.v')])

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    def test_simple_trigger_veto(self):
        self.chip['TLU'].TRIGGER_COUNTER = 0
        self.chip['TLU'].TRIGGER_MODE = 0
        self.chip['TLU'].TRIGGER_SELECT = 2
        self.chip['TLU'].TRIGGER_VETO_SELECT = 2
        self.chip['TLU'].TRIGGER_ENABLE = True

        self.chip['GPIO'].set_data([0x06])  # assert trigger and veto signal
        self.chip['GPIO'].set_data([0x00])  # de-assert trigger and veto signal

        self.chip['GPIO'].set_data([0x02])  # assert trigger signal
        self.chip['GPIO'].set_data([0x00])  # de-assert trigger signal

        self.chip['TLU'].TRIGGER_ENABLE = False

        self.assertEqual(self.chip['FIFO'].get_FIFO_INT_SIZE(), 1)
        self.assertEqual(self.chip['TLU'].TRIGGER_COUNTER, 1)

        data = self.chip['FIFO'].get_data()
        self.assertEqual(data[0], 0x80000000 + 0)

    def test_simple_trigger_veto_disabled(self):
        self.chip['TLU'].TRIGGER_COUNTER = 0
        self.chip['TLU'].TRIGGER_MODE = 0
        self.chip['TLU'].TRIGGER_SELECT = 2
        self.chip['TLU'].TRIGGER_VETO_SELECT = 252
        self.chip['TLU'].TRIGGER_ENABLE = True

        self.chip['GPIO'].set_data([0x06])  # assert trigger and veto signal
        self.chip['GPIO'].set_data([0x00])  # de-assert trigger and veto signal

        self.chip['GPIO'].set_data([0x02])  # assert trigger signal
        self.chip['GPIO'].set_data([0x00])  # de-assert trigger signal

        self.chip['TLU'].TRIGGER_ENABLE = False

        self.assertEqual(self.chip['FIFO'].get_FIFO_INT_SIZE(), 2)
        self.assertEqual(self.chip['TLU'].TRIGGER_COUNTER, 2)

        data = self.chip['FIFO'].get_data()
        self.assertEqual(data[0], 0x80000000 + 0)
        self.assertEqual(data[1], 0x80000000 + 1)

    def test_simple_trigger_threshold(self):
        self.chip['TLU'].TRIGGER_COUNTER = 0
        self.chip['TLU'].TRIGGER_MODE = 0
        # select short trigger (one clock cycle)
        self.chip['TLU'].TRIGGER_SELECT = 4
        self.chip['TLU'].TRIGGER_THRESHOLD = 1  # at least one clock cycle
        self.chip['TLU'].TRIGGER_ENABLE = True

        self.chip['GPIO'].set_data([0x02])  # assert trigger signal
        self.chip['GPIO'].set_data([0x00])  # de-assert trigger signal

        self.chip['GPIO'].set_data([0x02])  # assert trigger signal
        self.chip['GPIO'].set_data([0x00])  # de-assert trigger signal

        self.chip['TLU'].TRIGGER_ENABLE = False

        self.assertEqual(self.chip['FIFO'].get_FIFO_INT_SIZE(), 2)
        self.assertEqual(self.chip['TLU'].TRIGGER_COUNTER, 2)

        data = self.chip['FIFO'].get_data()
        self.assertEqual(data[0], 0x80000000 + 0)
        self.assertEqual(data[1], 0x80000000 + 1)

        self.chip['TLU'].TRIGGER_COUNTER = 0
        self.chip['TLU'].TRIGGER_THRESHOLD = 2  # at least two clock cycles
        self.chip['TLU'].TRIGGER_ENABLE = True

        self.chip['GPIO'].set_data([0x02])  # assert trigger signal
        self.chip['GPIO'].set_data([0x00])  # de-assert trigger signal

        self.chip['GPIO'].set_data([0x02])  # assert trigger signal
        self.chip['GPIO'].set_data([0x00])  # de-assert trigger signal

        self.chip['TLU'].TRIGGER_ENABLE = False

        self.assertEqual(self.chip['FIFO'].get_FIFO_INT_SIZE(), 0)
        self.assertEqual(self.chip['TLU'].TRIGGER_COUNTER, 0)

    def test_simple_trigger_max_triggers(self):
        self.chip['TLU'].TRIGGER_COUNTER = 0
        self.chip['TLU'].MAX_TRIGGERS = 2  # max. 2 triggers
        self.chip['TLU'].TRIGGER_MODE = 0
        self.chip['TLU'].TRIGGER_SELECT = 2
        self.chip['TLU'].TRIGGER_VETO_SELECT = 252
        self.chip['TLU'].TRIGGER_ENABLE = True

        self.chip['GPIO'].set_data([0x02])  # assert trigger signal
        self.chip['GPIO'].set_data([0x00])  # de-assert trigger signal

        self.chip['GPIO'].set_data([0x02])  # assert trigger signal
        self.chip['GPIO'].set_data([0x00])  # de-assert trigger signal

        self.chip['GPIO'].set_data([0x02])  # assert trigger signal
        self.chip['GPIO'].set_data([0x00])  # de-assert trigger signal

        self.chip['GPIO'].set_data([0x02])  # assert trigger signal
        self.chip['GPIO'].set_data([0x00])  # de-assert trigger signal

        self.chip['TLU'].TRIGGER_ENABLE = False

        self.assertEqual(self.chip['FIFO'].get_FIFO_INT_SIZE(), 2)
        self.assertEqual(self.chip['TLU'].TRIGGER_COUNTER, 2)

        data = self.chip['FIFO'].get_data()
        self.assertEqual(data[0], 0x80000000 + 0)
        self.assertEqual(data[1], 0x80000000 + 1)

    def test_simple_trigger(self):
        self.chip['TLU'].TRIGGER_COUNTER = 10
        self.chip['TLU'].TRIGGER_MODE = 0
        self.chip['TLU'].TRIGGER_SELECT = 1
        self.chip['TLU'].TRIGGER_VETO_SELECT = 0
        self.chip['TLU'].TRIGGER_ENABLE = True
        self.chip['GPIO'].set_data([0x01])  # enable trigger/TLU FSM

        readings = 0
        while (self.chip['FIFO'].get_FIFO_INT_SIZE() < 4 and readings < 10000):
            readings += 1

        self.chip['GPIO'].set_data([0x00])  # disable trigger/TLU FSM
        self.chip['TLU'].TRIGGER_ENABLE = False

        self.assertGreaterEqual(self.chip['FIFO'].get_FIFO_INT_SIZE(), 4)
        self.assertGreaterEqual(self.chip['TLU'].TRIGGER_COUNTER, 14)

        data = self.chip['FIFO'].get_data()
        self.assertEqual(data[0], 0x80000000 + 10)
        self.assertEqual(data[1], 0x80000000 + 11)
        self.assertEqual(data[2], 0x80000000 + 12)
        self.assertEqual(data[3], 0x80000000 + 13)

    def test_manual_soft_trigger(self):
        self.chip['TLU'].TRIGGER_COUNTER = 10
        self.chip['TLU'].TRIGGER_MODE = 0
        self.chip['TLU'].TRIGGER_SELECT = 0
        self.chip['TLU'].TRIGGER_VETO_SELECT = 0
        self.chip['TLU'].TRIGGER_ENABLE = True

        for i in range(4):
            self.chip['TLU'].SOFT_TRIGGER = 1

            readings = 0
            while (self.chip['FIFO'].get_FIFO_INT_SIZE() <= i
                   and readings < 10000):
                readings += 1

        self.chip['TLU'].TRIGGER_ENABLE = False
        self.assertGreaterEqual(self.chip['FIFO'].get_FIFO_INT_SIZE(), 4)
        self.assertGreaterEqual(self.chip['TLU'].TRIGGER_COUNTER, 14)

        data = self.chip['FIFO'].get_data()
        self.assertEqual(data[0], 0x80000000 + 10)
        self.assertEqual(data[1], 0x80000000 + 11)
        self.assertEqual(data[2], 0x80000000 + 12)
        self.assertEqual(data[3], 0x80000000 + 13)

    def test_tlu_trigger_handshake(self):
        self.chip['TLU'].TRIGGER_COUNTER = 0
        self.chip['TLU'].TRIGGER_MODE = 3
        # not used when EN_TLU_VETO is False
        self.chip['TLU'].TRIGGER_VETO_SELECT = 255
        self.chip['TLU'].EN_TLU_VETO = 0
        #         self.chip['TLU'].DATA_FORMAT = 2
        #         self.chip['TLU'].TRIGGER_LOW_TIMEOUT = 5
        #         self.chip['TLU'].TRIGGER_HANDSHAKE_ACCEPT_WAIT_CYCLES = 0
        #         self.chip['TLU'].HANDSHAKE_BUSY_VETO_WAIT_CYCLES = 0
        self.chip['TLU'].TRIGGER_ENABLE = True
        self.chip['GPIO'].set_data([0x01])

        readings = 0
        while (self.chip['FIFO'].get_FIFO_INT_SIZE() < 4 and readings < 1000):
            readings += 1

        self.chip['GPIO'].set_data([0x00])  # disable trigger/TLU FSM
        self.chip['TLU'].TRIGGER_ENABLE = False

        self.assertGreaterEqual(self.chip['FIFO'].get_FIFO_INT_SIZE(), 4)
        self.assertGreaterEqual(self.chip['TLU'].TRIGGER_COUNTER, 4)
        self.assertGreaterEqual(self.chip['TLU'].CURRENT_TLU_TRIGGER_NUMBER, 3)

        data = self.chip['FIFO'].get_data()
        self.assertEqual(data[0], 0x80000000)
        self.assertEqual(data[1], 0x80000001)
        self.assertEqual(data[2], 0x80000002)
        self.assertEqual(data[3], 0x80000003)

    def test_tlu_trigger_handshake_veto(self):
        self.chip['TLU'].TRIGGER_COUNTER = 0
        self.chip['TLU'].TRIGGER_MODE = 3
        # used when EN_TLU_VETO is True
        self.chip['TLU'].TRIGGER_VETO_SELECT = 255
        self.chip['TLU'].EN_TLU_VETO = 1
        self.chip['TLU'].TRIGGER_ENABLE = True
        self.chip['GPIO'].set_data([0x01])  # enable trigger/TLU FSM

        readings = 0
        while (self.chip['FIFO'].get_FIFO_INT_SIZE() == 0 and readings < 1000):
            readings += 1

        self.assertEqual(self.chip['FIFO'].get_FIFO_INT_SIZE(), 0)
        self.assertEqual(self.chip['TLU'].TRIGGER_COUNTER, 0)
        self.assertEqual(self.chip['TLU'].CURRENT_TLU_TRIGGER_NUMBER, 0)

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #34
0
class TestSimSpi(unittest.TestCase):
    def __init__(self, testname, tb='test_SimSpi.v', bus_drv='basil.utils.sim.BasilBusDriver', bus_split=False):
        super(TestSimSpi, self).__init__(testname)
        self._test_tb = tb
        self._sim_bus = bus_drv
        self._bus_split_def = ()
        if bus_split is not False:
            if bus_split == 'sbus':
                self._bus_split_def = ("BASIL_SBUS",)
            elif bus_split == 'top':
                self._bus_split_def = ("BASIL_TOPSBUS",)

    def setUp(self):
        cocotb_compile_and_run(sim_files=[os.path.join(os.path.dirname(__file__), self._test_tb)], sim_bus=self._sim_bus, extra_defines=self._bus_split_def)

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    def test_io(self):
        size = self.chip['SPI'].get_SIZE()
        self.chip['GPIO'].reset()
        self.assertEqual(size, 16 * 8)

        self.chip['SPI'].set_data(range(16))
        ret = self.chip['SPI'].get_data(size=16, addr=0)  # to read back what was written
        self.assertEqual(ret.tolist(), list(range(16)))

        self.chip['SPI'].set_data(range(16))
        ret = self.chip['SPI'].get_data(addr=0)  # to read back what was written
        self.assertEqual(ret.tolist(), list(range(16)))

        self.chip['SPI'].start()
        while(not self.chip['SPI'].is_ready):
            pass

        ret = self.chip['SPI'].get_data()  # read back what was received (looped)
        self.assertEqual(ret.tolist(), list(range(16)))

        # ext_start
        self.chip['SPI'].set_en(1)
        self.assertEqual(self.chip['SPI'].get_en(), 1)

        self.chip['PULSE_GEN'].set_DELAY(1)
        self.chip['PULSE_GEN'].set_WIDTH(1 + size)
        self.chip['PULSE_GEN'].set_REPEAT(1)
        self.assertEqual(self.chip['PULSE_GEN'].get_DELAY(), 1)
        self.assertEqual(self.chip['PULSE_GEN'].get_WIDTH(), 1 + size)
        self.assertEqual(self.chip['PULSE_GEN'].get_REPEAT(), 1)

        self.chip['PULSE_GEN'].start()
        while(not self.chip['PULSE_GEN'].is_ready):
            pass

        ret = self.chip['SPI'].get_data()  # read back what was received (looped)
        self.assertEqual(ret.tolist(), list(range(16)))

        # SPI_RX
        ret = self.chip['SPI_RX'].get_en()
        self.assertEqual(ret, False)

        self.chip['SPI_RX'].set_en(True)
        ret = self.chip['SPI_RX'].get_en()
        self.assertEqual(ret, True)

        self.chip['SPI'].start()
        while(not self.chip['SPI'].is_ready):
            pass

        ret = self.chip['FIFO'].get_FIFO_SIZE()
        self.assertEqual(ret, 32)

        ret = self.chip['FIFO'].get_data()

        data0 = ret.astype(np.uint8)
        data1 = np.right_shift(ret, 8).astype(np.uint8)
        data = np.reshape(np.vstack((data1, data0)), -1, order='F')
        self.assertEqual(data.tolist(), list(range(16)))

    def test_dut_iter(self):
        conf = yaml.safe_load(cnfg_yaml)

        def iter_conf():
            for item in conf['registers']:
                yield item
            for item in conf['hw_drivers']:
                yield item
            for item in conf['transfer_layer']:
                yield item

        for mod, mcnf in zip(self.chip, iter_conf()):
            self.assertEqual(mod.name, mcnf['name'])
            self.assertEqual(mod.__class__.__name__, mcnf['type'])

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #35
0
class TestSimBDAQ53Eth(unittest.TestCase):
    def setUp(self):
        sys.path = [os.path.dirname(os.getcwd())] + sys.path
        proj_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

        cocotb_compile_and_run(
            sim_files=[proj_dir + '/test/bdaq53_eth_tb.v'],
            top_level='tb',
            include_dirs=(proj_dir, proj_dir + '/firmware/src')
        )

        with open(proj_dir + '/bdaq53_eth.yaml') as conf_file:
            try:
                conf = yaml.safe_load(conf_file)
            except yaml.YAMLError as exception:
                print(exception)

        conf['transfer_layer'][0]['type'] = 'SiSim'
        conf['transfer_layer'][0]['tcp_connection'] = 'False'

#        conf['hw_drivers']['FIFO'] = ({'name': 'fifo',
#                                       'type': 'sram_fifo',
#                                       'interface': 'intf',
#                                       'base_addr': 0x8000,
#                                       'base_data_addr': 0x80000000})

        conf['hw_drivers'].append({'name': 'FIFO', 'type': 'sram_fifo',
                                   'interface': 'intf', 'base_addr': 0x8000, 'base_data_addr': 0x80000000})

        self.chip = Dut(conf)
        self.chip.init()

    def test(self):
        testduration = 10
        total_len = 0
        tick = 0
        tick_old = 0
        start_time = time.time()

        self.chip['CONTROL']['EN'] = 0x01  # start data source
        self.chip['CONTROL'].write()

        while time.time() - start_time < testduration:
            data = self.chip['FIFO'].get_data()
            total_len += len(data)
            time.sleep(0.01)
            tick = int(time.time() - start_time)
            if tick != tick_old:
                print(tick)
                tick_old = tick

            if doprint:
                print(data)

            for i in data:
                if i < (len(data) - 1):
                    assert data[i] == data[i + 1] - 1  # Check, if received integers are increasing numbers

            if total_len >= IntsToReceive:
                break

        total_len_bits = total_len * 32  # 32-bit ints to bits
        print('Bits received: {}; Data rate: {}Mbit/s'.format(total_len_bits, round((total_len_bits / 1e6 / testduration), 2)))

        self.chip['CONTROL']['EN'] = 0x00  # stop data source
        self.chip['CONTROL'].write()

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #36
0
class Test(object):
    def __init__(self):
        self.dut = Dut(conf)
        self.dut.init()
        # fw_version = dut['ETH'].read(0x0000, 1)[0]
        logging.info("Firmware version: %s" % self.dut['REGISTERS'].VERSION)

        signal.signal(signal.SIGINT, self.signal_handler)
        logging.info('Press Ctrl-C to stop')

        self.stop_thread = Event()
        self.total_tcp_err_cnt = 0

    def signal_handler(self, signum, frame):
        logging.info('Pressed Ctrl-C...')
        self.dut['REGISTERS'].TCP_WRITE_DLY = 0  # no TCP data
        self.time_stop = time.time()
        self.stop_thread.set()
        signal.signal(signal.SIGINT, signal.SIG_DFL)  # setting default handler

    def start(self, test_tcp=True, test_bus=True, tcp_write_delay=6, monitor_interval=1.0, deadline=None):
        if not test_tcp and not test_bus:
            return
        self.test_tcp = test_tcp
        self.test_bus = test_bus
        # reset registers
        self.dut['REGISTERS'].RESET
        # setup register values
        # Monitor
        self.monitor_delay = monitor_interval  # Speed of displaying netowrk speed
        # TCP
        self.tcp_readout_delay = 0.1  # Delay between reading TCP buffer
        self.dut['REGISTERS'].TCP_WRITE_DLY = 0  # no TCP data
        self.time_start = time.time()
        self.total_tcp_err_cnt = 0
        self.total_tcp_data_words_read = 0
        self.tcp_exception_cnt = 0
        self.tcp_read_speeds = None
        # BUS
        self.bus_readout_delay = 0.0  # Delay between reading/writing to BUS
        self.total_bus_err_cnt = 0
        self.total_bus_read_write_cnt = 0
        self.bus_exception_cnt = 0
        self.bus_read_write_speeds = None
        # initializing threads
        self.stop_thread.clear()
        self.mon_t = Thread(target=self.monitor, name='Monitor thread', kwargs={})
        self.mon_t.daemon = True
        self.mon_t.start()
        if test_tcp:
            self.tcp_t = Thread(target=self.tcp_read, name='TCP thread', kwargs={})
            self.tcp_t.daemon = True
            self.tcp_t.start()
        if test_bus:
            self.bus_t = Thread(target=self.bus_read_write, name='BUS thread', kwargs={})
            self.bus_t.daemon = True
            self.bus_t.start()
        if test_tcp:
            self.dut['REGISTERS'].TCP_WRITE_DLY = tcp_write_delay  # set TCP write delay: 1 equivalent to write data every clock cycle (1/133MHz=0.0075us=7.5ns)
        self.time_start = time.time()
        self.time_stop = self.time_start + 1.0
        # while loop for signal handler
        while not self.stop_thread.wait(0.05):
            if deadline and self.time_start + deadline < time.time():
                self.signal_handler(None, None)
        self.mon_t.join()
        self.mon_t = None
        logging.info("Stopped Monitor thread")
        if test_tcp:
            self.tcp_t.join()
            self.tcp_t = None
            logging.info("Stopped TCP thread")
        if test_bus:
            self.bus_t.join()
            self.bus_t = None
            logging.info("Stopped BUS thread")

        # some statistics
        logging.info("Total time: %s" % (str(datetime.timedelta(seconds=self.time_stop - self.time_start))))
        if test_tcp:
            logging.info("=== TCP transfer statistics ===")
            logging.info("TCP data error counter: %d" % self.total_tcp_err_cnt)
            logging.info("TCP exception counter: %d" % self.tcp_exception_cnt)
            logging.info("TCP write busy counter: %d" % self.dut['REGISTERS'].TCP_FAILED_WRITE_CNT)
            logging.info("TCP data words: read: %d, expected: %d" % (self.dut['REGISTERS'].TCP_WRITE_CNT * 4 + self.dut['REGISTERS'].TCP_RECV_WRITE_CNT, self.total_tcp_data_words_read * 4))
            if self.total_tcp_data_words_read * 4 / 10.0**6 > 1000000:
                logging.info("Total amount transmitted: %.2f TB" % (self.total_tcp_data_words_read * 4 / 10.0**12))
            elif self.total_tcp_data_words_read * 4 / 10.0**6 > 1000:
                logging.info("Total amount transmitted: %.2f GB" % (self.total_tcp_data_words_read * 4 / 10.0**9))
            else:
                logging.info("Total amount transmitted: %.2f MB" % (self.total_tcp_data_words_read * 4 / 10.0**6))
            total_tcp_avg_read_speed = self.total_tcp_data_words_read * 32 / (self.time_stop - self.time_start) / 10.0**6
            if total_tcp_avg_read_speed < 1.0:
                logging.info("Total average TCP read speed: %.2f kbit/s" % (total_tcp_avg_read_speed * 10**3))
            else:
                logging.info("Total average TCP read speed: %.2f Mbit/s" % (total_tcp_avg_read_speed))
            if self.tcp_read_speeds:
                if np.average(self.tcp_read_speeds) < 1.0:
                    logging.info("TCP read speed (min/median/average/max): %.2f/%.2f/%.2f/%.2f kbit/s" % (np.min(self.tcp_read_speeds) * 10**3, np.median(self.tcp_read_speeds) * 10**3, np.average(self.tcp_read_speeds) * 10**3, np.max(self.tcp_read_speeds) * 10**3))
                else:
                    logging.info("TCP read speed (min/median/average/max): %.2f/%.2f/%.2f/%.2f Mbit/s" % (np.min(self.tcp_read_speeds), np.median(self.tcp_read_speeds), np.average(self.tcp_read_speeds), np.max(self.tcp_read_speeds)))

        if test_bus:
            logging.info("=== BUS transfer statistics ===")
            logging.info("BUS data error counter: %d" % self.total_bus_err_cnt)
            logging.info("BUS exception counter: %d" % self.bus_exception_cnt)
            logging.info("BUS read/write counter: read: %d, expected: %d" % (self.dut['REGISTERS'].BUS_WRITE_CNT, self.total_bus_read_write_cnt * 8))
            if self.total_bus_read_write_cnt * 8 / 10.0**6 > 1000000:
                logging.info("Total amount transmitted: %.2f TB" % (self.total_bus_read_write_cnt * 8 / 10.0**12))
            elif self.total_bus_read_write_cnt * 8 / 10.0**6 > 1000:
                logging.info("Total amount transmitted: %.2f GB" % (self.total_bus_read_write_cnt * 8 / 10.0**9))
            else:
                logging.info("Total amount transmitted: %.2f MB" % (self.total_bus_read_write_cnt * 8 / 10.0**6))
            total_bus_avg_read_speed = self.total_bus_read_write_cnt * 64 / (self.time_stop - self.time_start) / 10.0**6
            if total_bus_avg_read_speed < 1.0:
                logging.info("Total average BUS read/write speed: %.2f kbit/s" % (total_bus_avg_read_speed * 10**3))
            else:
                logging.info("Total average BUS read/write speed: %.2f Mbit/s" % (total_bus_avg_read_speed))
            if self.bus_read_write_speeds:
                if np.average(self.bus_read_write_speeds) < 1.0:
                    logging.info("BUS read/write speed (min/median/average/max): %.2f/%.2f/%.2f/%.2f kbit/s" % (np.min(self.bus_read_write_speeds) * 10**3, np.median(self.bus_read_write_speeds) * 10**3, np.average(self.bus_read_write_speeds) * 10**3, np.max(self.bus_read_write_speeds) * 10**3))
                else:
                    logging.info("BUS read/write speed (min/median/average/max): %.2f/%.2f/%.2f/%.2f Mbit/s" % (np.min(self.bus_read_write_speeds), np.median(self.bus_read_write_speeds), np.average(self.bus_read_write_speeds), np.max(self.bus_read_write_speeds)))

        # close DUT
        self.dut.close()

    def monitor(self):
        logging.info("Started Monitor thread")
        time_read = time.time()
        last_total_tcp_data_words_read = 0
        last_total_bus_read_write_cnt = 0
        while not self.stop_thread.wait(max(0.0, self.monitor_delay - time_read + time.time())):
            tmp_time_read = time.time()
            tmp_total_tcp_data_words_read = self.total_tcp_data_words_read
            tmp_total_bus_read_write_cnt = self.total_bus_read_write_cnt
            if self.test_tcp:
                tcp_read_speed = (tmp_total_tcp_data_words_read - last_total_tcp_data_words_read) * 32 / (tmp_time_read - time_read) / 10**6
                if self.tcp_read_speeds is None:  # add on second iteration
                    self.tcp_read_speeds = []
                else:
                    self.tcp_read_speeds.append(tcp_read_speed)
                if tcp_read_speed < 1.0:
                    logging.info("TCP read speed: %0.2f kbit/s" % (tcp_read_speed * 10**3))
                else:
                    logging.info("TCP read speed: %0.2f Mbit/s" % tcp_read_speed)
            if self.test_bus:
                bus_read_write_speed = (tmp_total_bus_read_write_cnt - last_total_bus_read_write_cnt) * 64 / (tmp_time_read - time_read) / 10**6
                if self.bus_read_write_speeds is None:  # add on second iteration
                    self.bus_read_write_speeds = []
                else:
                    self.bus_read_write_speeds.append(bus_read_write_speed)
                if bus_read_write_speed < 1.0:
                    logging.info("BUS read/write speed: %0.2f kbit/s" % (bus_read_write_speed * 10**3))
                else:
                    logging.info("BUS read/write speed: %0.2f Mbit/s" % bus_read_write_speed)
            time_read = tmp_time_read
            last_total_tcp_data_words_read = tmp_total_tcp_data_words_read
            last_total_bus_read_write_cnt = tmp_total_bus_read_write_cnt
            if self.total_bus_err_cnt > 10 or self.total_tcp_err_cnt > 10:
                self.stop_thread.set()

        logging.info("Stopping Monitor thread...")

    def tcp_read(self):
        logging.info("Started TCP thread")
        fifo_data_last_value = -1
        fifo_was_empty = 0
        time_read = time.time()
        while not self.stop_thread.wait(max(0.0, self.tcp_readout_delay - time_read + time.time())) or fifo_was_empty < 1:
            time_read = time.time()
            try:
                fifo_data = self.dut['SITCP_FIFO'].get_data()
            except Exception as e:
                logging.error(e)
                self.tcp_exception_cnt += 1
            else:
                if fifo_data.shape[0]:
                    self.total_tcp_data_words_read += fifo_data.shape[0]
                    if fifo_data[0] != fifo_data_last_value + 1:
                        logging.warning("TCP not increased by 1 between readouts")
                        self.total_tcp_err_cnt += 1
                    err_cnt = np.count_nonzero(np.diff(fifo_data) != 1)
                    if err_cnt:
                        logging.warning("TCP data not increased by 1: errors=%d" % err_cnt)
                        self.total_tcp_err_cnt += err_cnt
                    fifo_data_last_value = fifo_data[-1]
                elif self.stop_thread.is_set():
                    fifo_was_empty += 1
            if self.stop_thread.is_set():
                time.sleep(max(0.0, self.tcp_readout_delay - time_read + time.time()))
        logging.info("Stopping TCP thread...")

    def bus_read_write(self):
        logging.info("Started BUS thread")
        time_read = time.time()
        while not self.stop_thread.wait(max(0.0, self.bus_readout_delay - time_read + time.time())):
            time_read = time.time()
            write_value = int(np.random.randint(2**64, size=None, dtype=np.uint64))  # random.randint(0, 2**64 - 1)
            try:
                self.dut['REGISTERS'].TEST_DATA = write_value
            except Exception as e:
                logging.error(e)
                self.bus_exception_cnt += 1
            else:
                try:
                    read_value = self.dut['REGISTERS'].TEST_DATA
                except Exception as e:
                    logging.error(e)
                    self.bus_exception_cnt += 1
                else:
                    self.total_bus_read_write_cnt += 1
                    if read_value != write_value:
                        logging.warning("BUS data not correct: read: %s, expected: %s" % (array('B', struct.unpack("BBBBBBBB", struct.pack("Q", read_value))), array('B', struct.unpack("BBBBBBBB", struct.pack("Q", write_value)))))
                        self.total_bus_err_cnt += 1
        logging.info("Stopping BUS thread...")
Exemple #37
0
class TestSimTimestampDiv(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run([
            os.path.join(os.path.dirname(__file__), 'test_SimTimestampDiv.v')
        ])

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    def test_io(self):
        self.chip['timestamp_div'].reset()
        self.chip['timestamp_div']["ENABLE"] = 1
        self.chip['gpio'].reset()

        self.chip['fifo'].reset()
        ret = self.chip['fifo'].get_fifo_size()
        self.assertEqual(ret, 0)

        # trigger timestamp
        repeat = 16
        width = 0x18
        self.chip['PULSE_GEN'].set_delay(0x20 + 0x7)
        self.chip['PULSE_GEN'].set_width(width)
        self.chip['PULSE_GEN'].set_repeat(repeat)

        self.chip['PULSE_GEN'].start()
        while (not self.chip['PULSE_GEN'].is_done()):
            pass

        # get data from fifo
        ret = self.chip['fifo'].get_fifo_size()
        self.assertEqual(ret, 3 * 4 * repeat)

        ret = self.chip['fifo'].get_data()
        self.assertEqual(len(ret), 3 * repeat)
        for i, r in enumerate(ret):
            self.assertEqual(r & 0xF0000000, 0x50000000)
            self.assertEqual(r & 0xF000000, 0x1000000 * (3 - i % 3))

        self.chip['timestamp_div']["ENABLE_TOT"] = 1
        self.chip['PULSE_GEN'].start()
        while (not self.chip['PULSE_GEN'].is_done()):
            pass

        ret = self.chip['fifo'].get_fifo_size()
        self.assertEqual(ret, 3 * 4 * repeat)

        ret = self.chip['fifo'].get_data()
        self.assertEqual(len(ret), 3 * repeat)
        for i, r in enumerate(ret):
            self.assertEqual(r & 0xF0000000, 0x50000000)
            self.assertEqual(r & 0xF000000, 0x1000000 * (3 - i % 3))
            if i % 3 == 0:
                self.assertEqual(r & 0xFFFF00, 0x100 * width)  # ToT value

    def tearDown(self):
        time.sleep(2)
        self.chip.close()  # let it close connection and stop simulator
        time.sleep(2)
        cocotb_compile_clean()
        time.sleep(2)
Exemple #38
0
class TestSram(unittest.TestCase):
    def setUp(self):

        fw_path = os.path.join(get_basil_dir(), 'firmware/modules')
        cocotb_compile_and_run([
            os.path.join(fw_path, 'gpio/gpio.v'),
            os.path.join(fw_path, 'utils/reset_gen.v'),
            os.path.join(fw_path, 'utils/bus_to_ip.v'),
            os.path.join(fw_path, 'rrp_arbiter/rrp_arbiter.v'),
            os.path.join(fw_path, 'utils/ODDR_sim.v'),
            os.path.join(fw_path, 'utils/generic_fifo.v'),
            os.path.join(fw_path, 'utils/cdc_pulse_sync.v'),
            os.path.join(fw_path, 'utils/fx2_to_bus.v'),
            os.path.join(fw_path, 'pulse_gen/pulse_gen.v'),
            os.path.join(fw_path, 'pulse_gen/pulse_gen_core.v'),
            os.path.join(fw_path, 'sram_fifo/sram_fifo_core.v'),
            os.path.join(fw_path, 'sram_fifo/sram_fifo.v'),
            os.path.join(os.path.dirname(__file__),
                         '../firmware/src/sram_test.v'),
            os.path.join(os.path.dirname(__file__), '../tests/tb.v')
        ],
                               top_level='tb',
                               sim_bus='basil.utils.sim.SiLibUsbBusDriver')

        with open(os.path.join(os.path.dirname(__file__), '../sram_test.yaml'),
                  'r') as f:
            cnfg = yaml.load(f)

        # change to simulation interface
        cnfg['transfer_layer'][0]['type'] = 'SiSim'

        self.chip = Dut(cnfg)
        self.chip.init()

    def test_simple(self):
        self.chip['CONTROL']['COUNTER_EN'] = 1
        self.chip['CONTROL'].write()
        self.chip['CONTROL'].write()
        self.chip['CONTROL']['COUNTER_EN'] = 0
        self.chip['CONTROL'].write()
        for _ in range(10):
            self.chip['CONTROL'].write()

        ret = self.chip['FIFO'].get_data()

        self.chip['CONTROL']['COUNTER_EN'] = 1
        self.chip['CONTROL'].write()
        self.chip['CONTROL'].write()
        self.chip['CONTROL'].write()
        self.chip['CONTROL']['COUNTER_EN'] = 0
        for _ in range(10):
            self.chip['CONTROL'].write()

        ret = np.hstack((ret, self.chip['FIFO'].get_data()))

        x = np.arange(175 * 4, dtype=np.uint8)
        x.dtype = np.uint32

        self.assertTrue(np.alltrue(ret == x))

        self.chip['FIFO'].reset()

        self.chip['CONTROL']['COUNTER_EN'] = 1
        self.chip['CONTROL'].write()
        self.chip['CONTROL'].write()

        self.chip['CONTROL']['COUNTER_EN'] = 0
        self.chip['CONTROL'].write()
        self.chip['CONTROL'].write()
        self.chip['CONTROL'].write()

        ret = np.hstack((ret, self.chip['FIFO'].get_data()))

        x = np.arange(245 * 4, dtype=np.uint8)
        x.dtype = np.uint32

        self.assertEqual(ret.tolist(), x.tolist())

    def test_full(self):
        self.chip['CONTROL']['COUNTER_EN'] = 1
        self.chip['CONTROL'].write()

        for _ in range(2):
            self.chip['FIFO'].get_FIFO_SIZE()

        self.chip['CONTROL']['COUNTER_EN'] = 0
        self.chip['CONTROL'].write()

        for _ in range(10):
            self.chip['CONTROL'].write()

        size = self.chip['FIFO'].get_FIFO_SIZE()
        self.assertEqual(size, 512)

        ret = self.chip['FIFO'].get_data()
        ret = np.hstack((ret, self.chip['FIFO'].get_data()))

        x = np.arange(203 * 4, dtype=np.uint8)
        x.dtype = np.uint32

        self.assertTrue(np.alltrue(ret == x))

    def test_overflow(self):
        self.chip['CONTROL']['COUNTER_EN'] = 1
        self.chip['CONTROL'].write()

        for _ in range(20):
            self.chip['FIFO'].get_FIFO_SIZE()

        self.chip['CONTROL']['COUNTER_EN'] = 0
        self.chip['CONTROL'].write()

        for _ in range(10):
            self.chip['CONTROL'].write()

        ret = self.chip['FIFO'].get_data()
        while (self.chip['FIFO'].get_FIFO_SIZE()):
            ret = np.hstack((ret, self.chip['FIFO'].get_data()))

        x = np.arange((128 + 1023) * 4, dtype=np.uint8)
        x.dtype = np.uint32

        self.assertTrue(np.alltrue(ret == x))

        self.chip['PULSE'].set_DELAY(1)
        self.chip['PULSE'].set_WIDTH(1)
        self.chip['PULSE'].start()

        ret = self.chip['FIFO'].get_data()
        x = np.arange((128 + 1023) * 4, (128 + 1023 + 1) * 4, dtype=np.uint8)
        x.dtype = np.uint32

        self.assertEqual(ret, x)

    def test_single(self):

        self.chip['PULSE'].set_DELAY(1)
        self.chip['PULSE'].set_WIDTH(1)
        self.chip['PULSE'].start()

        self.assertEqual(self.chip['FIFO'].get_data().tolist(), [0x03020100])

        self.chip['PULSE'].start()

        self.assertEqual(self.chip['FIFO'].get_data().tolist(), [0x07060504])

    def test_pattern(self):
        self.chip['PATTERN'] = 0xaa5555aa
        self.chip['PATTERN'].write()

        self.chip['CONTROL']['PATTERN_EN'] = 1
        self.chip['CONTROL'].write()
        self.chip['CONTROL']['PATTERN_EN'] = 0
        self.chip['CONTROL'].write()
        for _ in range(5):
            self.chip['CONTROL'].write()

        self.assertEqual(self.chip['FIFO'].get_data().tolist(),
                         [0xaa5555aa] * 35)

    def test_direct(self):
        self.chip['CONTROL']['COUNTER_DIRECT'] = 1
        self.chip['CONTROL'].write()

        size = 648
        base_data_addr = self.chip['FIFO']._conf['base_data_addr']

        ret = self.chip['USB'].read(base_data_addr, size=size)
        ret = np.hstack((ret, self.chip['USB'].read(base_data_addr,
                                                    size=size)))

        x = np.arange(size * 2, dtype=np.uint8)
        self.assertEqual(ret.tolist(), x.tolist())

    def test_continouse(self):
        self.chip['PULSE'].set_DELAY(35)
        self.chip['PULSE'].set_WIDTH(3)
        self.chip['PULSE'].set_repeat(0)
        self.chip['PULSE'].start()

        i = 0
        error = False
        for _ in range(100):
            ret = self.chip['FIFO'].get_data()

            x = np.arange(i * 4, (i + ret.shape[0]) * 4, dtype=np.uint8)
            x.dtype = np.uint32

            i += ret.shape[0]

            ok = np.alltrue(ret == x)
            # print 'OK?', ok, ret.shape[0], i, k
            if not ok:
                error = True
                break

        self.assertFalse(error)

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #39
0
class TestSimSeq(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run([os.path.join(os.path.dirname(__file__), 'test_SimCmdSeq.v')])

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    @unittest.skip("saving CPU time")
    def test_basic_io(self):
        self.chip['CMD_SEQ']['OUTPUT_MODE'] = 0
        self.chip['CMD_SEQ']['OUTPUT_ENABLE'] = 0x01
        self.chip['SEQ_REC']['EN_EXT_START'] = 1
        self.chip['CMD_SEQ']['EN_EXT_TRIGGER'] = 1
        self.chip['PULSE_GEN']['DELAY'] = 1
        self.chip['PULSE_GEN']['WIDTH'] = 1

        for cmd_pattern in [0x00, np.random.randint(1, 255), 0xFF]:
            for cmd_size in [0, 1, 2, np.random.randint(3, max_cmd_size - 1), max_cmd_size - 1, max_cmd_size]:
                # cmd_size of 0 will not start cmd_seq
                if isinstance(cmd_pattern, list):
                    write_cmd_pattern = list(cmd_pattern)  # copy
                    write_cmd_pattern.extend(np.random.randint(0, 256, size=max_cmd_byte_size - len(write_cmd_pattern)))
                    self.chip['CMD_SEQ'].set_data(data=write_cmd_pattern, addr=0)
                else:
                    write_cmd_pattern = [cmd_pattern] * max_cmd_byte_size
                    self.chip['CMD_SEQ'].set_data(data=write_cmd_pattern, addr=0)
                ret = self.chip['CMD_SEQ'].get_data(size=max_cmd_byte_size)
                np.testing.assert_array_equal(ret, write_cmd_pattern)
                # self.assertListEqual(ret.tolist(), write_cmd_pattern)
                self.chip['CMD_SEQ']['CMD_SIZE'] = cmd_size

                rec_size = cmd_size + rec_add_size
                self.chip['SEQ_REC']['SIZE'] = rec_size
                self.chip['PULSE_GEN']['START']

                while not self.chip['CMD_SEQ']['READY']:
                    pass
                while not self.chip['SEQ_REC']['READY']:
                    pass

                ret = self.chip['SEQ_REC'].get_data(size=rec_size)
                expected_arr = np.array(write_cmd_pattern, dtype=np.uint8)
                expected_bits = np.unpackbits(expected_arr).flatten()[:cmd_size]
                expected_bits = np.r_[expected_bits, [0] * (rec_size - len(expected_bits))]
                np.testing.assert_array_equal(ret, expected_bits)
                # self.assertListEqual(ret.tolist(), expected_bits.tolist())

    @unittest.skip("saving CPU time")
    def test_repeat(self):
        self.chip['CMD_SEQ']['OUTPUT_MODE'] = 0
        self.chip['CMD_SEQ']['OUTPUT_ENABLE'] = 0x01
        self.chip['SEQ_REC']['EN_EXT_START'] = 1
        self.chip['CMD_SEQ']['EN_EXT_TRIGGER'] = 1
        self.chip['PULSE_GEN']['DELAY'] = 1
        self.chip['PULSE_GEN']['WIDTH'] = 1

        for cmd_pattern in [0x00, np.random.randint(0, 256, size=max_cmd_byte_size).tolist(), 0xFF]:
            for cmd_size in [0, 1, 2, np.random.randint(3, max_cmd_size - 1), max_cmd_size - 1, max_cmd_size]:  # 0 will prevent writing command
                # cmd_size of 0 will not start cmd_seq
                for cmd_repeat in [1, 2, 3]:
                    # when cmd_repeat is 0 -> infinite loop
                    if isinstance(cmd_pattern, list):
                        write_cmd_pattern = list(cmd_pattern)  # copy
                        write_cmd_pattern.extend(np.random.randint(0, 256, size=max_cmd_byte_size - len(write_cmd_pattern)))
                        self.chip['CMD_SEQ'].set_data(data=write_cmd_pattern, addr=0)
                    else:
                        write_cmd_pattern = [cmd_pattern] * max_cmd_byte_size
                        self.chip['CMD_SEQ'].set_data(data=write_cmd_pattern, addr=0)
                    self.chip['CMD_SEQ']['CMD_SIZE'] = cmd_size
                    self.chip['CMD_SEQ']['CMD_REPEAT'] = cmd_repeat

                    rec_size = cmd_size * cmd_repeat + rec_add_size
                    self.chip['SEQ_REC']['SIZE'] = rec_size
                    self.chip['PULSE_GEN']['START']

                    while not self.chip['CMD_SEQ']['READY']:
                        pass
                    while not self.chip['SEQ_REC']['READY']:
                        pass

                    ret = self.chip['SEQ_REC'].get_data(size=rec_size)
                    expected_arr = np.array(write_cmd_pattern, dtype=np.uint8)
                    expected_bits = np.unpackbits(expected_arr).flatten()[:cmd_size]
                    expected_bits = np.tile(expected_bits, cmd_repeat)
                    expected_bits = np.r_[expected_bits, [0] * (rec_size - len(expected_bits))]
                    np.testing.assert_array_equal(ret, expected_bits)
                    # self.assertTrue(ret.tolist(), expected_bits.tolist())

    @unittest.skip("saving CPU time")
    def test_start_sequnce(self):
        cmd_pattern = np.random.randint(0, 256, size=max_cmd_byte_size).tolist()
        if isinstance(cmd_pattern, list):
            write_cmd_pattern = list(cmd_pattern)  # copy
            write_cmd_pattern.extend(np.random.randint(0, 256, size=max_cmd_byte_size - len(write_cmd_pattern)))
            self.chip['CMD_SEQ'].set_data(data=write_cmd_pattern, addr=0)
        else:
            write_cmd_pattern = [cmd_pattern] * max_cmd_byte_size
            self.chip['CMD_SEQ'].set_data(data=write_cmd_pattern, addr=0)

        self.chip['CMD_SEQ']['OUTPUT_MODE'] = 0
        self.chip['CMD_SEQ']['OUTPUT_ENABLE'] = 0x01
        self.chip['SEQ_REC']['EN_EXT_START'] = 1
        self.chip['CMD_SEQ']['EN_EXT_TRIGGER'] = 1
        self.chip['PULSE_GEN']['DELAY'] = 1
        self.chip['PULSE_GEN']['WIDTH'] = 1

        for cmd_size in [1, 2, np.random.randint(3, max_cmd_size - 1), max_cmd_size - 1, max_cmd_size]:
            # cmd_size of 0 will not start cmd_seq
            for cmd_repeat in [1, 2, 3]:
                # when cmd_repeat is 0 -> infinite loop
                for cmd_start_sequnce_length in [0, 1, np.random.randint(1, cmd_size + 2), cmd_size - 1, cmd_size, cmd_size + 1]:
                    # if cmd_start_sequnce_length > cmd_size, cmd_seq will not start
                    self.chip['CMD_SEQ']['CMD_SIZE'] = cmd_size
                    self.chip['CMD_SEQ']['CMD_REPEAT'] = cmd_repeat
                    self.chip['CMD_SEQ']['START_SEQUENCE_LENGTH'] = cmd_start_sequnce_length
                    self.chip['CMD_SEQ']['STOP_SEQUENCE_LENGTH'] = 0

                    if cmd_start_sequnce_length <= cmd_size:
                        rec_size = cmd_start_sequnce_length + (cmd_size - cmd_start_sequnce_length) * cmd_repeat + rec_add_size
                    else:
                        rec_size = rec_add_size
                    self.chip['SEQ_REC']['SIZE'] = rec_size
                    self.chip['PULSE_GEN']['START']

                    while not self.chip['CMD_SEQ']['READY']:
                        pass
                    while not self.chip['SEQ_REC']['READY']:
                        pass

                    ret = self.chip['SEQ_REC'].get_data(size=rec_size)
                    expected_arr = np.array(write_cmd_pattern, dtype=np.uint8)
                    expected_bits = np.unpackbits(expected_arr).flatten()[:cmd_size]
                    if cmd_start_sequnce_length <= cmd_size:
                        expected_bits = np.r_[expected_bits, np.tile(expected_bits[cmd_start_sequnce_length:], cmd_repeat - 1)]
                    else:
                        expected_bits = np.tile(expected_bits, 0)
                    expected_bits = np.r_[expected_bits, [0] * (rec_size - len(expected_bits))]
                    np.testing.assert_array_equal(ret, expected_bits)
                    # self.assertListEqual(ret.tolist(), expected_bits.tolist())

    @unittest.skip("saving CPU time")
    def test_stop_sequence(self):
        cmd_pattern = np.random.randint(0, 256, size=max_cmd_byte_size).tolist()
        if isinstance(cmd_pattern, list):
            write_cmd_pattern = list(cmd_pattern)  # copy
            write_cmd_pattern.extend(np.random.randint(0, 256, size=max_cmd_byte_size - len(write_cmd_pattern)))
            self.chip['CMD_SEQ'].set_data(data=write_cmd_pattern, addr=0)
        else:
            write_cmd_pattern = [cmd_pattern] * max_cmd_byte_size
            self.chip['CMD_SEQ'].set_data(data=write_cmd_pattern, addr=0)

        self.chip['CMD_SEQ']['OUTPUT_MODE'] = 0
        self.chip['CMD_SEQ']['OUTPUT_ENABLE'] = 0x01
        self.chip['SEQ_REC']['EN_EXT_START'] = 1
        self.chip['CMD_SEQ']['EN_EXT_TRIGGER'] = 1
        self.chip['PULSE_GEN']['DELAY'] = 1
        self.chip['PULSE_GEN']['WIDTH'] = 1

        for cmd_size in [1, 2, np.random.randint(3, max_cmd_size - 1), max_cmd_size - 1, max_cmd_size]:
            # cmd_size of 0 will not start cmd_seq
            for cmd_repeat in [1, 2, 3]:
                # when cmd_repeat is 0 -> infinite loop
                for cmd_stop_sequnce_length in [0, 1, np.random.randint(1, cmd_size + 2), cmd_size - 1, cmd_size, cmd_size + 1]:
                    # if cmd_stop_sequnce_length > cmd_size, cmd_seq will not start
                    self.chip['CMD_SEQ']['CMD_SIZE'] = cmd_size
                    self.chip['CMD_SEQ']['CMD_REPEAT'] = cmd_repeat
                    self.chip['CMD_SEQ']['START_SEQUENCE_LENGTH'] = 0
                    self.chip['CMD_SEQ']['STOP_SEQUENCE_LENGTH'] = cmd_stop_sequnce_length

                    if cmd_stop_sequnce_length <= cmd_size:
                        rec_size = (cmd_size - cmd_stop_sequnce_length) * cmd_repeat + cmd_stop_sequnce_length * (cmd_repeat if cmd_stop_sequnce_length == 0 else 1) + rec_add_size
                    else:
                        rec_size = rec_add_size
                    self.chip['SEQ_REC']['SIZE'] = rec_size
                    self.chip['PULSE_GEN']['START']

                    while not self.chip['CMD_SEQ']['READY']:
                        pass
                    while not self.chip['SEQ_REC']['READY']:
                        pass

                    ret = self.chip['SEQ_REC'].get_data(size=rec_size)
                    expected_arr = np.array(write_cmd_pattern, dtype=np.uint8)
                    expected_bits = np.unpackbits(expected_arr).flatten()[:cmd_size]
                    if cmd_stop_sequnce_length <= cmd_size:
                        expected_bits = np.r_[np.tile(expected_bits[:cmd_size if (cmd_stop_sequnce_length == 0) else -cmd_stop_sequnce_length], cmd_repeat), expected_bits[cmd_size if (cmd_stop_sequnce_length == 0) else -cmd_stop_sequnce_length:]]
                    else:
                        expected_bits = np.tile(expected_bits, 0)
                    expected_bits = np.r_[expected_bits, [0] * (rec_size - len(expected_bits))]
                    np.testing.assert_array_equal(ret, expected_bits)
                    # self.assertListEqual(ret.tolist(), expected_bits.tolist())

    # @unittest.skip("saving CPU time")
    def test_start_and_stop_sequence(self):
        cmd_pattern = np.random.randint(0, 256, size=max_cmd_byte_size).tolist()
        if isinstance(cmd_pattern, list):
            write_cmd_pattern = list(cmd_pattern)  # copy
            write_cmd_pattern.extend(np.random.randint(0, 256, size=max_cmd_byte_size - len(write_cmd_pattern)))
            self.chip['CMD_SEQ'].set_data(data=write_cmd_pattern, addr=0)
        else:
            write_cmd_pattern = [cmd_pattern] * max_cmd_byte_size
            self.chip['CMD_SEQ'].set_data(data=write_cmd_pattern, addr=0)

        self.chip['CMD_SEQ']['OUTPUT_MODE'] = 0
        self.chip['CMD_SEQ']['OUTPUT_ENABLE'] = 0x01
        self.chip['SEQ_REC']['EN_EXT_START'] = 1
        self.chip['CMD_SEQ']['EN_EXT_TRIGGER'] = 1
        self.chip['PULSE_GEN']['DELAY'] = 1
        self.chip['PULSE_GEN']['WIDTH'] = 1

        cmd_size = 1
        # cmd_size of 0 will not start cmd_seq
        cmd_repeat = 1
        # when cmd_repeat is 0 -> infinite loop
        cmd_start_sequnce_length = 1
        cmd_stop_sequnce_length = 0
        # if cmd_start_sequnce_length + cmd_stop_sequnce_length > cmd_size, cmd_seq will not start
        self.chip['CMD_SEQ']['CMD_SIZE'] = cmd_size
        self.chip['CMD_SEQ']['CMD_REPEAT'] = cmd_repeat
        self.chip['CMD_SEQ']['START_SEQUENCE_LENGTH'] = cmd_start_sequnce_length
        self.chip['CMD_SEQ']['STOP_SEQUENCE_LENGTH'] = cmd_stop_sequnce_length

        rec_size = 1 + rec_add_size
        self.chip['SEQ_REC']['SIZE'] = rec_size
        self.chip['PULSE_GEN']['START']

        while not self.chip['CMD_SEQ']['READY']:
            pass
        while not self.chip['SEQ_REC']['READY']:
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        expected_arr = np.array(write_cmd_pattern, dtype=np.uint8)
        expected_bits = np.unpackbits(expected_arr).flatten()[:cmd_size]
        expected_bits = np.r_[expected_bits, [0] * (rec_size - len(expected_bits))]
        np.testing.assert_array_equal(ret, expected_bits)
        # self.assertListEqual(ret.tolist(), expected_bits.tolist())

        cmd_start_sequnce_length = 0
        cmd_stop_sequnce_length = 1
        self.chip['CMD_SEQ']['START_SEQUENCE_LENGTH'] = cmd_start_sequnce_length
        self.chip['CMD_SEQ']['STOP_SEQUENCE_LENGTH'] = cmd_stop_sequnce_length

        self.chip['PULSE_GEN']['START']

        while not self.chip['CMD_SEQ']['READY']:
            pass
        while not self.chip['SEQ_REC']['READY']:
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        expected_arr = np.array(write_cmd_pattern, dtype=np.uint8)
        expected_bits = np.unpackbits(expected_arr).flatten()[:cmd_size]
        expected_bits = np.r_[expected_bits, [0] * (rec_size - len(expected_bits))]
        np.testing.assert_array_equal(ret, expected_bits)
        # self.assertListEqual(ret.tolist(), expected_bits.tolist())

        cmd_start_sequnce_length = 1
        cmd_stop_sequnce_length = 1
        self.chip['CMD_SEQ']['START_SEQUENCE_LENGTH'] = cmd_start_sequnce_length
        self.chip['CMD_SEQ']['STOP_SEQUENCE_LENGTH'] = cmd_stop_sequnce_length

        self.chip['PULSE_GEN']['START']

        while not self.chip['CMD_SEQ']['READY']:
            pass
        while not self.chip['SEQ_REC']['READY']:
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        expected_arr = np.array(write_cmd_pattern, dtype=np.uint8)
        expected_bits = np.unpackbits(expected_arr).flatten()[:0]
        expected_bits = np.r_[expected_bits, [0] * (rec_size - len(expected_bits))]
        np.testing.assert_array_equal(ret, expected_bits)
        # self.assertListEqual(ret.tolist(), expected_bits.tolist())

        cmd_repeat = 2
        cmd_start_sequnce_length = 1
        cmd_stop_sequnce_length = 0
        self.chip['CMD_SEQ']['CMD_REPEAT'] = cmd_repeat
        self.chip['CMD_SEQ']['START_SEQUENCE_LENGTH'] = cmd_start_sequnce_length
        self.chip['CMD_SEQ']['STOP_SEQUENCE_LENGTH'] = cmd_stop_sequnce_length

        self.chip['PULSE_GEN']['START']

        while not self.chip['CMD_SEQ']['READY']:
            pass
        while not self.chip['SEQ_REC']['READY']:
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        expected_arr = np.array(write_cmd_pattern, dtype=np.uint8)
        expected_bits = np.unpackbits(expected_arr).flatten()[:cmd_size]
        expected_bits = np.r_[expected_bits, [0] * (rec_size - len(expected_bits))]
        np.testing.assert_array_equal(ret, expected_bits)
        # self.assertListEqual(ret.tolist(), expected_bits.tolist())

        cmd_start_sequnce_length = 0
        cmd_stop_sequnce_length = 1
        self.chip['CMD_SEQ']['START_SEQUENCE_LENGTH'] = cmd_start_sequnce_length
        self.chip['CMD_SEQ']['STOP_SEQUENCE_LENGTH'] = cmd_stop_sequnce_length

        self.chip['PULSE_GEN']['START']

        while not self.chip['CMD_SEQ']['READY']:
            pass
        while not self.chip['SEQ_REC']['READY']:
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        expected_arr = np.array(write_cmd_pattern, dtype=np.uint8)
        expected_bits = np.unpackbits(expected_arr).flatten()[:cmd_size]
        expected_bits = np.r_[expected_bits, [0] * (rec_size - len(expected_bits))]
        np.testing.assert_array_equal(ret, expected_bits)
        # self.assertListEqual(ret.tolist(), expected_bits.tolist())

        cmd_start_sequnce_length = 1
        cmd_stop_sequnce_length = 1
        self.chip['CMD_SEQ']['START_SEQUENCE_LENGTH'] = cmd_start_sequnce_length
        self.chip['CMD_SEQ']['STOP_SEQUENCE_LENGTH'] = cmd_stop_sequnce_length

        self.chip['PULSE_GEN']['START']

        while not self.chip['CMD_SEQ']['READY']:
            pass
        while not self.chip['SEQ_REC']['READY']:
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        expected_arr = np.array(write_cmd_pattern, dtype=np.uint8)
        expected_bits = np.unpackbits(expected_arr).flatten()[:0]
        expected_bits = np.r_[expected_bits, [0] * (rec_size - len(expected_bits))]
        np.testing.assert_array_equal(ret, expected_bits)
        # self.assertListEqual(ret.tolist(), expected_bits.tolist())

        cmd_size = 2
        cmd_repeat = 1
        cmd_start_sequnce_length = 1
        cmd_stop_sequnce_length = 0
        self.chip['CMD_SEQ']['CMD_SIZE'] = cmd_size
        self.chip['CMD_SEQ']['CMD_REPEAT'] = cmd_repeat
        self.chip['CMD_SEQ']['START_SEQUENCE_LENGTH'] = cmd_start_sequnce_length
        self.chip['CMD_SEQ']['STOP_SEQUENCE_LENGTH'] = cmd_stop_sequnce_length

        rec_size = 2 + rec_add_size
        self.chip['SEQ_REC']['SIZE'] = rec_size
        self.chip['PULSE_GEN']['START']

        while not self.chip['CMD_SEQ']['READY']:
            pass
        while not self.chip['SEQ_REC']['READY']:
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        expected_arr = np.array(write_cmd_pattern, dtype=np.uint8)
        expected_bits = np.unpackbits(expected_arr).flatten()[:cmd_size]
        expected_bits = np.r_[expected_bits, [0] * (rec_size - len(expected_bits))]
        np.testing.assert_array_equal(ret, expected_bits)
        # self.assertListEqual(ret.tolist(), expected_bits.tolist())

        cmd_start_sequnce_length = 0
        cmd_stop_sequnce_length = 1
        self.chip['CMD_SEQ']['START_SEQUENCE_LENGTH'] = cmd_start_sequnce_length
        self.chip['CMD_SEQ']['STOP_SEQUENCE_LENGTH'] = cmd_stop_sequnce_length

        self.chip['PULSE_GEN']['START']

        while not self.chip['CMD_SEQ']['READY']:
            pass
        while not self.chip['SEQ_REC']['READY']:
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        expected_arr = np.array(write_cmd_pattern, dtype=np.uint8)
        expected_bits = np.unpackbits(expected_arr).flatten()[:cmd_size]
        expected_bits = np.r_[expected_bits, [0] * (rec_size - len(expected_bits))]
        np.testing.assert_array_equal(ret, expected_bits)
        # self.assertListEqual(ret.tolist(), expected_bits.tolist())

        cmd_start_sequnce_length = 1
        cmd_stop_sequnce_length = 1
        self.chip['CMD_SEQ']['START_SEQUENCE_LENGTH'] = cmd_start_sequnce_length
        self.chip['CMD_SEQ']['STOP_SEQUENCE_LENGTH'] = cmd_stop_sequnce_length

        self.chip['PULSE_GEN']['START']

        while not self.chip['CMD_SEQ']['READY']:
            pass
        while not self.chip['SEQ_REC']['READY']:
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        expected_arr = np.array(write_cmd_pattern, dtype=np.uint8)
        expected_bits = np.unpackbits(expected_arr).flatten()[:cmd_size]
        expected_bits = np.r_[expected_bits, [0] * (rec_size - len(expected_bits))]
        np.testing.assert_array_equal(ret, expected_bits)
        # self.assertListEqual(ret.tolist(), expected_bits.tolist())

        cmd_start_sequnce_length = 2
        cmd_stop_sequnce_length = 0
        self.chip['CMD_SEQ']['START_SEQUENCE_LENGTH'] = cmd_start_sequnce_length
        self.chip['CMD_SEQ']['STOP_SEQUENCE_LENGTH'] = cmd_stop_sequnce_length

        self.chip['PULSE_GEN']['START']

        while not self.chip['CMD_SEQ']['READY']:
            pass
        while not self.chip['SEQ_REC']['READY']:
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        expected_arr = np.array(write_cmd_pattern, dtype=np.uint8)
        expected_bits = np.unpackbits(expected_arr).flatten()[:cmd_size]
        expected_bits = np.r_[expected_bits, [0] * (rec_size - len(expected_bits))]
        np.testing.assert_array_equal(ret, expected_bits)
        # self.assertListEqual(ret.tolist(), expected_bits.tolist())

        cmd_start_sequnce_length = 0
        cmd_stop_sequnce_length = 2
        self.chip['CMD_SEQ']['START_SEQUENCE_LENGTH'] = cmd_start_sequnce_length
        self.chip['CMD_SEQ']['STOP_SEQUENCE_LENGTH'] = cmd_stop_sequnce_length

        self.chip['PULSE_GEN']['START']

        while not self.chip['CMD_SEQ']['READY']:
            pass
        while not self.chip['SEQ_REC']['READY']:
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        expected_arr = np.array(write_cmd_pattern, dtype=np.uint8)
        expected_bits = np.unpackbits(expected_arr).flatten()[:cmd_size]
        expected_bits = np.r_[expected_bits, [0] * (rec_size - len(expected_bits))]
        np.testing.assert_array_equal(ret, expected_bits)
        # self.assertListEqual(ret.tolist(), expected_bits.tolist())

        cmd_start_sequnce_length = 2
        cmd_stop_sequnce_length = 1
        self.chip['CMD_SEQ']['START_SEQUENCE_LENGTH'] = cmd_start_sequnce_length
        self.chip['CMD_SEQ']['STOP_SEQUENCE_LENGTH'] = cmd_stop_sequnce_length

        self.chip['PULSE_GEN']['START']

        while not self.chip['CMD_SEQ']['READY']:
            pass
        while not self.chip['SEQ_REC']['READY']:
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        expected_arr = np.array(write_cmd_pattern, dtype=np.uint8)
        expected_bits = np.unpackbits(expected_arr).flatten()[:0]
        expected_bits = np.r_[expected_bits, [0] * (rec_size - len(expected_bits))]
        np.testing.assert_array_equal(ret, expected_bits)
        # self.assertListEqual(ret.tolist(), expected_bits.tolist())

        cmd_start_sequnce_length = 1
        cmd_stop_sequnce_length = 2
        self.chip['CMD_SEQ']['START_SEQUENCE_LENGTH'] = cmd_start_sequnce_length
        self.chip['CMD_SEQ']['STOP_SEQUENCE_LENGTH'] = cmd_stop_sequnce_length

        self.chip['PULSE_GEN']['START']

        while not self.chip['CMD_SEQ']['READY']:
            pass
        while not self.chip['SEQ_REC']['READY']:
            pass

        ret = self.chip['SEQ_REC'].get_data(size=rec_size)
        expected_arr = np.array(write_cmd_pattern, dtype=np.uint8)
        expected_bits = np.unpackbits(expected_arr).flatten()[:0]
        expected_bits = np.r_[expected_bits, [0] * (rec_size - len(expected_bits))]
        np.testing.assert_array_equal(ret, expected_bits)
        # self.assertListEqual(ret.tolist(), expected_bits.tolist())

        for _ in range(1):
            cmd_size = np.random.randint(2, max_cmd_size + 1)
            # cmd_size of 0 will not start cmd_seq
            cmd_repeat = np.random.randint(1, 4)
            # when cmd_repeat is 0 -> infinite loop
            cmd_start_sequnce_length = np.random.randint(0, cmd_size + 1)
            cmd_stop_sequnce_length = np.random.randint(0, cmd_size - cmd_start_sequnce_length + 1)
            self.chip['CMD_SEQ']['CMD_SIZE'] = cmd_size
            self.chip['CMD_SEQ']['CMD_REPEAT'] = cmd_repeat
            self.chip['CMD_SEQ']['START_SEQUENCE_LENGTH'] = cmd_start_sequnce_length
            self.chip['CMD_SEQ']['STOP_SEQUENCE_LENGTH'] = cmd_stop_sequnce_length

            rec_size = cmd_start_sequnce_length + (cmd_size - cmd_stop_sequnce_length - cmd_start_sequnce_length) * cmd_repeat + cmd_stop_sequnce_length + rec_add_size
            self.chip['SEQ_REC']['SIZE'] = rec_size
            self.chip['PULSE_GEN']['START']

            while not self.chip['CMD_SEQ']['READY']:
                pass
            while not self.chip['SEQ_REC']['READY']:
                pass

            ret = self.chip['SEQ_REC'].get_data(size=rec_size)
            expected_arr = np.array(write_cmd_pattern, dtype=np.uint8)
            cmd_bits = np.unpackbits(expected_arr).flatten()[:cmd_size]
            expected_bits = np.r_[cmd_bits[:cmd_start_sequnce_length]]
            expected_bits = np.r_[expected_bits, np.tile(cmd_bits[cmd_start_sequnce_length:cmd_size if (cmd_stop_sequnce_length == 0) else -cmd_stop_sequnce_length], cmd_repeat)]
            expected_bits = np.r_[expected_bits, cmd_bits[cmd_size if (cmd_stop_sequnce_length == 0) else -cmd_stop_sequnce_length:]]
            expected_bits = np.r_[expected_bits, [0] * (rec_size - len(expected_bits))]
            np.testing.assert_array_equal(ret, expected_bits)
            # self.assertListEqual(ret.tolist(), expected_bits.tolist())

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #40
0
class TestSimTlu(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run([os.path.join(os.path.dirname(__file__), 'test_SimTlu.v')])

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    def test_simple_trigger_veto(self):
        self.chip['tlu'].TRIGGER_COUNTER = 0
        self.chip['tlu'].TRIGGER_MODE = 0
        self.chip['tlu'].TRIGGER_SELECT = 2
        self.chip['tlu'].TRIGGER_VETO_SELECT = 2
#         self.chip['CONTROL']['ENABLE'] = 1
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        self.chip['gpio'].set_data([0x07])  # trigger + veto
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

#         self.chip['CONTROL']['ENABLE'] = 0
        self.chip['gpio'].set_data([0x00])

        self.assertEqual(self.chip['sram'].get_fifo_int_size(), 1)
        self.assertEqual(self.chip['tlu'].TRIGGER_COUNTER, 1)

        data = self.chip['sram'].get_data()
        self.assertEqual(data[0], 0x80000000 + 0)

    def test_simple_trigger_veto_disabled(self):
        self.chip['tlu'].TRIGGER_COUNTER = 0
        self.chip['tlu'].TRIGGER_MODE = 0
        self.chip['tlu'].TRIGGER_SELECT = 2
        self.chip['tlu'].TRIGGER_VETO_SELECT = 252
#         self.chip['CONTROL']['ENABLE'] = 1
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU
        self.chip['gpio'].set_data([0x01])  # issue a second time, wait for reset

        self.chip['gpio'].set_data([0x07])  # trigger + veto
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

#         self.chip['CONTROL']['ENABLE'] = 0
        self.chip['gpio'].set_data([0x00])

        self.assertEqual(self.chip['sram'].get_fifo_int_size(), 2)
        self.assertEqual(self.chip['tlu'].TRIGGER_COUNTER, 2)

        data = self.chip['sram'].get_data()
        self.assertEqual(data[0], 0x80000000 + 0)
        self.assertEqual(data[1], 0x80000000 + 1)

    def test_simple_trigger_threshold(self):
        self.chip['tlu'].TRIGGER_COUNTER = 0
        self.chip['tlu'].TRIGGER_MODE = 0
        self.chip['tlu'].TRIGGER_SELECT = 4  # select single pulse trigger
        self.chip['tlu'].TRIGGER_THRESHOLD = 1  # at least two clock cycles
#         self.chip['CONTROL']['ENABLE'] = 1
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU
        self.chip['gpio'].set_data([0x01])  # issue a second time, wait for reset

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

#         self.chip['CONTROL']['ENABLE'] = 0
        self.chip['gpio'].set_data([0x00])

        self.assertEqual(self.chip['sram'].get_fifo_int_size(), 2)
        self.assertEqual(self.chip['tlu'].TRIGGER_COUNTER, 2)

        data = self.chip['sram'].get_data()
        self.assertEqual(data[0], 0x80000000 + 0)
        self.assertEqual(data[1], 0x80000000 + 1)

        self.chip['tlu'].TRIGGER_COUNTER = 0
        self.chip['tlu'].TRIGGER_THRESHOLD = 2  # at least two clock cycles

        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

#         self.chip['CONTROL']['ENABLE'] = 0
        self.chip['gpio'].set_data([0x00])

        self.assertEqual(self.chip['sram'].get_fifo_int_size(), 0)
        self.assertEqual(self.chip['tlu'].TRIGGER_COUNTER, 0)

    def test_simple_trigger_max_triggers(self):
        self.chip['tlu'].TRIGGER_COUNTER = 0
        self.chip['tlu'].MAX_TRIGGERS = 2
        self.chip['tlu'].TRIGGER_MODE = 0
        self.chip['tlu'].TRIGGER_SELECT = 2
        self.chip['tlu'].TRIGGER_VETO_SELECT = 252
#         self.chip['CONTROL']['ENABLE'] = 1
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        self.chip['gpio'].set_data([0x03])  # trigger
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

#         self.chip['CONTROL']['ENABLE'] = 0
        self.chip['gpio'].set_data([0x00])

        self.assertEqual(self.chip['sram'].get_fifo_int_size(), 2)
        self.assertEqual(self.chip['tlu'].TRIGGER_COUNTER, 2)

        data = self.chip['sram'].get_data()
        self.assertEqual(data[0], 0x80000000 + 0)
        self.assertEqual(data[1], 0x80000000 + 1)

    def test_simple_trigger(self):
        self.chip['tlu'].TRIGGER_COUNTER = 10
        self.chip['tlu'].TRIGGER_MODE = 0
        self.chip['tlu'].TRIGGER_SELECT = 1
        self.chip['tlu'].TRIGGER_VETO_SELECT = 0
#         self.chip['CONTROL']['ENABLE'] = 1
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        readings = 0
        while(self.chip['sram'].get_fifo_int_size() < 4 and readings < 1000):
            readings += 1

#         self.chip['CONTROL']['ENABLE'] = 0
        self.chip['gpio'].set_data([0x00])

        self.assertGreaterEqual(self.chip['sram'].get_fifo_int_size(), 4)
        self.assertGreaterEqual(self.chip['tlu'].TRIGGER_COUNTER, 14)

        data = self.chip['sram'].get_data()
        self.assertEqual(data[0], 0x80000000 + 10)
        self.assertEqual(data[1], 0x80000000 + 11)
        self.assertEqual(data[2], 0x80000000 + 12)
        self.assertEqual(data[3], 0x80000000 + 13)

    def test_tlu_trigger_handshake(self):
        self.chip['tlu'].TRIGGER_COUNTER = 0
        self.chip['tlu'].TRIGGER_MODE = 3
        self.chip['tlu'].TRIGGER_VETO_SELECT = 255
        self.chip['tlu'].EN_TLU_VETO = 0
#         self.chip['tlu'].DATA_FORMAT = 2
#         self.chip['tlu'].TRIGGER_LOW_TIMEOUT = 5
#         self.chip['tlu'].TRIGGER_HANDSHAKE_ACCEPT_WAIT_CYCLES = 0
#         self.chip['tlu'].HANDSHAKE_BUSY_VETO_WAIT_CYCLES = 0
#         self.chip['CONTROL']['ENABLE'] = 1
        self.chip['gpio'].set_data([0x01])

        readings = 0
        while(self.chip['sram'].get_fifo_int_size() < 4 and readings < 1000):
            readings += 1

#         self.chip['CONTROL']['ENABLE'] = 0
        self.chip['gpio'].set_data([0x00])

        self.assertGreaterEqual(self.chip['sram'].get_fifo_int_size(), 4)
        self.assertGreaterEqual(self.chip['tlu'].TRIGGER_COUNTER, 4)
        self.assertGreaterEqual(self.chip['tlu'].CURRENT_TLU_TRIGGER_NUMBER, 3)

        data = self.chip['sram'].get_data()
        self.assertEqual(data[0], 0x80000000)
        self.assertEqual(data[1], 0x80000001)
        self.assertEqual(data[2], 0x80000002)
        self.assertEqual(data[3], 0x80000003)

    def test_tlu_trigger_handshake_veto(self):
        self.chip['tlu'].TRIGGER_COUNTER = 0
        self.chip['tlu'].TRIGGER_MODE = 3
        self.chip['tlu'].TRIGGER_VETO_SELECT = 1
        self.chip['tlu'].EN_TLU_VETO = 1
#         self.chip['CONTROL']['ENABLE'] = 1
        self.chip['gpio'].set_data([0x01])  # ext enable trigger/TLU

        readings = 0
        while(self.chip['sram'].get_fifo_int_size() == 0 and readings < 1000):
            readings += 1

        self.assertEqual(self.chip['sram'].get_fifo_int_size(), 0)
        self.assertEqual(self.chip['tlu'].TRIGGER_COUNTER, 0)
        self.assertEqual(self.chip['tlu'].CURRENT_TLU_TRIGGER_NUMBER, 0)

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()
Exemple #41
0
class TestSimAdcRx(unittest.TestCase):
    def setUp(self):
        cocotb_compile_and_run(
            [os.path.join(os.path.dirname(__file__), 'test_SimAdcRx.v')])

        self.chip = Dut(cnfg_yaml)
        self.chip.init()

    def test_io(self):
        pattern = [1, 0, 1, 1, 1, 2, 1, 3, 1, 4, 1, 5, 1, 6, 1, 7]
        self.chip['SEQ_GEN'].set_data(pattern)

        self.chip['PULSE_GEN'].set_DELAY(1)
        self.chip['PULSE_GEN'].set_WIDTH(1)

        self.chip['SEQ_GEN'].set_en_ext_start(True)
        self.chip['SEQ_GEN'].set_SIZE(8)
        self.chip['SEQ_GEN'].set_REPEAT(1)

        # this is to have something in memory and not X
        self.chip['PULSE_GEN'].start()
        self.chip['SEQ_GEN'].is_ready
        self.chip['SEQ_GEN'].is_ready

        while (not self.chip['SEQ_GEN'].is_ready):
            pass

        # take some data
        self.chip['FADC'].set_align_to_sync(True)
        self.chip['FADC'].set_data_count(16)
        self.chip['FADC'].set_single_data(True)
        self.chip['FADC'].start()

        self.chip['PULSE_GEN'].start()
        self.chip['SEQ_GEN'].is_ready
        self.chip['SEQ_GEN'].is_ready

        while (not self.chip['FADC'].is_ready):
            pass

        ret = self.chip['FIFO'].get_data()

        self.assertEqual(len(ret), 16)
        self.assertEqual(
            ret[2:2 + 8].tolist(),
            [0x0100, 0x0101, 0x0102, 0x0103, 0x0104, 0x0105, 0x0106, 0x0107])

        # 2times
        self.chip['FADC'].start()

        self.chip['PULSE_GEN'].start()
        self.chip['SEQ_GEN'].is_ready

        while (not self.chip['FADC'].is_ready):
            pass

        self.chip['FADC'].start()

        self.chip['PULSE_GEN'].start()
        self.chip['SEQ_GEN'].is_ready

        while (not self.chip['FADC'].is_ready):
            pass

        ret = self.chip['FIFO'].get_data()
        self.assertEqual(len(ret), 32)
        self.assertEqual(
            ret[2:2 + 8].tolist(),
            [0x0100, 0x0101, 0x0102, 0x0103, 0x0104, 0x0105, 0x0106, 0x0107])

        self.chip['FADC'].set_align_to_sync(False)
        self.chip['FADC'].start()
        self.chip['FADC'].start()

        while (not self.chip['FADC'].is_ready):
            pass

        ret = self.chip['FIFO'].get_data()
        self.assertEqual(len(ret), 16)

    def tearDown(self):
        self.chip.close()  # let it close connection and stop simulator
        cocotb_compile_clean()