예제 #1
0
    def __init__(self, snap_ip, snap_port):
        self.fpga=casperfpga.CasperFpga(host=snap_ip, port=snap_port, transport=casperfpga.KatcpTransport)
        if self.fpga.is_running():
            logger.info("Fpga is already programmed")
	    self.fpga.get_system_information()
        else:
            logger.info("Fpga not programmed")
예제 #2
0
def getFPGA():
    """Returns a casperfpga object of the Roach2"""
    try:
        fpga = casperfpga.CasperFpga(roach_ip, timeout = 120.)
    except RuntimeError:
        print "\nNo connection to ROACH. If booting, wait 30 seconds and retry. Otherwise, check gc config."
    return fpga
예제 #3
0
def initialise_snap(args, adc_tries, fft_of_tries, logger):
	logger.info("Beginning SNAP Board initialisation")
	logger.info("Connecting to SNAP Board at %s:%s"%(args.ip,args.port))
	snap = casperfpga.CasperFpga(args.ip)
	if snap.is_connected():
		logger.info("Connected")
	else:
		logger.error("Failed to connect. Exiting!!!")
		exit(0)
	try:
		logger.info("Programming FPGA")
		snap.upload_to_ram_and_program(args.firmware)
	except e:
		logger.error("Failed to program with error: "+e)
		logger.error("Exiting!!!")
		exit(0)
	else:
		logger.info("FPGA programmed successfully")
	logger.info("Attempting to initialize ADCs")
	snap_adc = casperfpga.snapadc.SNAPADC(snap, ref=None)
	for i in range(adc_tries):
		if snap_adc.init(samplingRate=250, numChannel=4, resolution=8) == 0:
			for j in range(3):
				snap_adc.selectADC(j)
				snap_adc.adc.selectInput([1,2,3,4])
			logger.info("ADC calibration done after %d attempts"%(i+1))
			break
		elif i==adc_tries-1:
			logger.error("ADC calibration failed after %d attempts. Exiting!!!"%(i+1))
			exit(0)
		else:
			logger.error("ADC calibration failed. Retrying.")
	logger.info("Board clock: %f"%snap.estimate_fpga_clock())
	logger.info("Setting fft_shift")
	snap.registers.pfb0_fft_shift.write_int(args.fftshift & 0xffff)
	snap.registers.pfb1_fft_shift.write_int(args.fftshift & 0xffff)
	logger.info("Setting acc_len")
	snap.registers.acc_len.write_int(args.acclen)
	logger.info("Syncing from software trigger")
	snap.registers.cnt_rst.write_int(0)
	snap.registers.sw_sync.write_int(0)
	snap.registers.sw_sync.write_int(1)
	snap.registers.sw_sync.write_int(0)
	snap.registers.cnt_rst.write_int(1)
	snap.registers.cnt_rst.write_int(0)
	time.sleep(2.5)
	pfb0_fft_of = False
	pfb1_fft_of = False
	for i in range(fft_of_tries):
		pfb0_fft_of = pfb0_fft_of or bool(snap.registers.pfb0_fft_of.read_int())
		pfb1_fft_of = pfb1_fft_of or bool(snap.registers.pfb1_fft_of.read_int())
	if pfb0_fft_of:
		logger.warning("pfb0 FFT overflow")
	if pfb1_fft_of:
		logger.warning("pfb1 FFT overflow")
	if not(pfb0_fft_of) and not(pfb1_fft_of):
		logger.info("No FFT overflow detected")
	logger.info("Initialization complete")
	return snap
예제 #4
0
 def connect(self):
     """
     Connects to a client. Raises runtime error after timeout.
     """
     log.debug("Connecting to FPGA {}:{}".format(self.__ip, self.__port))
     self._client = casperfpga.CasperFpga(self.__ip, self.__port)
     info = self._client.transport.get_skarab_version_info()
     log.debug(
         "Succcessfully Connected to FPGA - Retrieved Skarab info:" +
         "\n".join(["    -  {}: {}".format(k, v) for k, v in info.items()]))
예제 #5
0
    def __init__(self, host, ant_indices=None, logger=None):
        self.host = host
        self.logger = logger or helpers.add_default_log_handlers(logging.getLogger(__name__ + "(%s)" % host))
        self.fpga = casperfpga.CasperFpga(host=host, transport=casperfpga.TapcpTransport)
        # Try and get the canonical name of the host
        # to use as a serial number
        try:
            self.serial = socket.gethostbyaddr(self.host)[0]
        except:
            self.serial = None

        # blocks
        self.synth       = Synth(self.fpga, 'lmx_ctrl')
        self.adc         = Adc(self.fpga) # not a subclass of Block
        self.sync        = Sync(self.fpga, 'sync')
        self.noise       = NoiseGen(self.fpga, 'noise', nstreams=6)
        self.input       = Input(self.fpga, 'input', nstreams=12)
        self.delay       = Delay(self.fpga, 'delay', nstreams=6)
        self.pfb         = Pfb(self.fpga, 'pfb')
        self.eq          = Eq(self.fpga, 'eq_core', nstreams=6, ncoeffs=2**10)
        self.eq_tvg      = EqTvg(self.fpga, 'eqtvg', nstreams=6, nchans=2**13)
        self.reorder     = ChanReorder(self.fpga, 'chan_reorder', nchans=2**10)
        self.rotator     = Rotator(self.fpga, 'rotator')
        self.packetizer  = Packetizer(self.fpga, 'packetizer', n_time_demux=2) # Round robin time packets to two destinations
        self.eth         = Eth(self.fpga, 'eth')
        self.corr        = Corr(self.fpga,'corr_0')
        self.phaseswitch = PhaseSwitch(self.fpga, 'phase_switch')
        self.i2c_initialized = False
        try:
            self._add_i2c()
        except:
            pass

        self.ants = [None] * 6 # An attribute to store the antenna names of this board's inputs
        self.ant_indices = ant_indices or range(3) # An attribute to store the antenna numbers used in packet headers
        
        # The order here can be important, blocks are initialized in the
        # order they appear here
        self.blocks = [
            self.synth,
            self.adc,
            self.sync,
            self.noise,
            self.input,
            self.delay,
            self.pfb,
            self.eq,
            self.eq_tvg,
            self.reorder,
            self.packetizer,
            self.eth,
            self.corr,
            self.phaseswitch,
        ]
예제 #6
0
def plot_main():
    try:
        fpga = casperfpga.CasperFpga(
            gc[np.where(gc == 'roach_ppc_ip')[0][0]][1], timeout=3.)
    except RuntimeError:
        fpga = None
    # Roach interface
    ri = roachInterface(fpga, gc, regs, None)
    while 1:
        plot_opt(ri)
    return
예제 #7
0
def testConn(fpga):
    """Tests the link to Roach2 PPC, using return from getFPGA()
        inputs:
            casperfpga object fpga: The fpga object
        outputs: the fpga object"""
    if not fpga:
        try:
            fpga = casperfpga.CasperFpga(roach_ip, timeout = 3.)
        except RuntimeError:
            print "\nNo connection to ROACH. If booting, wait 30 seconds and retry. Otherwise, check gc config."
    return fpga
예제 #8
0
 def __init__(self, snap_ip, snap_port, logger):
     self.logger = logger
     self.fpga = casperfpga.CasperFpga(host=snap_ip,
                                       port=snap_port,
                                       transport=casperfpga.KatcpTransport)
     self.logger.info("Connected to SNAP Board at %s:%s" %
                      (snap_ip, snap_port))
     if self.fpga.is_running():
         self.logger.info("Fpga is already programmed")
         self.fpga.get_system_information()
     else:
         self.logger.info("Fpga not programmed")
예제 #9
0
def init_snaps(arg_counter, arg_snap_list):
    """
    Initialize a snaps array
    """
    asnaps = []
    for snap_name in arg_snap_list:
        print("init_snaps: [{}] {}".format(arg_counter, snap_name))
        if SIMULATION:
            snap_instance = open("/etc/profile", "r")
        else:
            snap_instance = casperfpga.CasperFpga(
                snap_name, transport=casperfpga.KatcpTransport)
        asnaps.append(snap_instance)
    return asnaps
예제 #10
0
def main():
    parser = argparse.ArgumentParser(description="Stop FPGAs ethernet output")
    parser.add_argument("snaps", nargs="?", help="snaps hostname")
    args = parser.parse_args()

    snap_list = args.snaps
    if not snap_list:
        snap_list = ['frb-snap%i-pi' % i for i in [1, 2, 3, 4, 5, 6, 8, 9, 10]]
    snaps = [
        casperfpga.CasperFpga(snap, transport=casperfpga.KatcpTransport)
        for snap in snap_list
    ]

    for i, snap in enumerate(snaps):
        snap.write_int("tge_en", 0)
예제 #11
0
 def testConn(self, fpga):
     """Tests the link to Roach2 PPC, using return from getFPGA()
         inputs:
             casperfpga object fpga: The fpga object
         outputs: the fpga object"""
     if not fpga:
         try:
             fpga = casperfpga.CasperFpga(self.roach_ip, timeout=3.)
             # Roach interface
             self.ri = roachInterface(self.fpga, self.gc, self.regs, None)
         except RuntimeError:
             logging.warning(
                 "No connection to ROACH. If booting, wait 30 seconds and retry. Otherwise, check gc config."
             )
     return fpga
예제 #12
0
def main():
    parser = argparse.ArgumentParser(description="Synchronise FPGA")
    parser.add_argument("snaps", nargs="?", help="snaps hostname")
    args = parser.parse_args()

    snap_list = args.snaps
    if not snap_list:
        snap_list = ['frb-snap%i-pi' % i for i in [4]]  #[3,4,5,6,8,9,10]]
    snaps = [
        casperfpga.CasperFpga(snap, transport=casperfpga.KatcpTransport)
        for snap in snap_list
    ]

    # Disable ethernet output
    for snap in snaps:
        snap.write_int("tge_en", 0)
        snap.write_int("tge_rst", 1)
        snap.write_int("tge_ctr_rst", 1)

    #grace_period = 4
    #unix_time_start = time.time() + grace_period
    #expected_synctime = int(np.ceil(unix_time_start)) + 2
    #print expected_synctime
    #time.sleep(1)
    #wait_until_time(unix_time_start-1)

    current_sync = snaps[0].read_int("sync_count")
    time.sleep(0.05)
    while (snaps[0].read_int("sync_count") == current_sync):
        time.sleep(0.05)

    for i, snap in enumerate(snaps):
        print(snap_list[i], snap.read_int("sync_count"))

    sync_time = int(np.ceil(
        time.time())) + 2  # Number of seconds for sync is det rmined by design
    print("  PPS passed! New sync time will be %d" % sync_time)
    for snap in snaps:
        snap.write_int("sync_arm", 1)
        snap.write_int("sync_arm", 0)
        print("  Writing new sync time to snap memory")
        snap.write_int("sync_sync_time", sync_time)

    for snap in snaps:
        snap.write_int("tge_rst", 0)
        snap.write_int("tge_ctr_rst", 0)
        snap.write_int("tge_en", 1)
예제 #13
0
  def init(self, index):
    print(os.path.basename(__file__)+'::'+sys._getframe().f_code.co_name)
    try:
      self.sim = sys.argv[3]
      print('sim =', self.sim)
    except Exception as e:
      self.sim = None

    try:
      udp_port = sys.argv[2]
    except Exception as e:
      pass
    
    roach = None
    if self.sim == None:
      try:
        roach = casperfpga.katcp_fpga.KatcpFpga(ppc_ip, timeout=5.)
      except Exception as ex:
        print('casperfpga.katcp_fpga.KatcpFpga ', ex)
        try:
          roach = casperfpga.CasperFpga(ppc_ip, timeout=5.)
        except Exception as e:
          print('CasperFpga', e)
          return False
        else:
          print('using casperfpga.CasperFpga')
      else:
        print('using casperfpga.latcp_fpga.KatcpFpga')
      print('udp_iface =', udp_iface)
    print('udp_port =', udp_port)
    
    self.gbe = Gbe(int(udp_port))
    self.gbe.upload_firmware(roach, ppc_ip, firmware)
    self.gbe.init_reg(roach)
    self.gbe.init()
    self.out_data = [[0]]

    toltecTask = threading.Thread(target=self.gbe.stream_UDP,
                                  args=(roach, udp_iface, 511, self.out_data))
    toltecTask.daemon = True
    toltecTask.start()

    return True
예제 #14
0
def main():
    """Main function, try to initialize the system the first time, then open the menu"""

    s = None
    try:
        fpga = casperfpga.CasperFpga(roach_ip, timeout = 120.)
        print "\nConnected to: " + roach_ip
    except RuntimeError:
        fpga = None
        print "\nRoach link is down"

    # UDP socket
    s = socket(AF_PACKET, SOCK_RAW, htons(3))

    # Roach interface
    ri = roachInterface(fpga, gc, regs, None)

    # Windfreak synthesizer
    synthRF = synthclass.Synthesizer(synthID)

    # GbE interface
    udp = roachDownlink(ri, fpga, gc, regs, s, ri.accum_freq)
    udp.configSocket()

    os.system('clear')

    valon = None

    while 1:
        try:
            upload_status = 0
            if fpga:
                if fpga.is_running():
                    upload_status = 1
            time.sleep(0.1)
            #fpga = None
            #ri = None
            #udp = None
            upload_status = main_opt(fpga, ri, udp, valon, upload_status)
        except TypeError:
            pass
    return
예제 #15
0
 def __init__(self, host, logger=None):
     self.hostname = host  #: hostname of the F-Engine's host SNAP2 board
     #: Python Logger instance
     self.logger = logger or helpers.add_default_log_handlers(
         logging.getLogger(__name__ + ":%s" % (host)))
     #: Underlying CasperFpga control instance
     self._cfpga = casperfpga.CasperFpga(
         host=self.hostname,
         transport=casperfpga.TapcpTransport,
     )
     try:
         self._cfpga.get_system_information()
     except:
         self.logger.error(
             "Failed to read and decode .fpg header from flash")
     self.blocks = {}
     try:
         self._initialize_blocks()
     except:
         self.logger.error("Failed to inialize firmware blocks. "
                           "Maybe the board needs programming.")
예제 #16
0
def initialize(params):
    """Connect to SNAP board, configure settings"""

    # Connect to the SNAP board configure spectrometer settings
    logging.info('Connecting to server %s:%d' %
                 (params['snap-board']['ip'], params['snap-board']['port']))
    fpga = casperfpga.CasperFpga(host=params['snap-board']['ip'],
                                 port=params['snap-board']['port'])
    time.sleep(1)  # important for live connection reporting
    if fpga.is_connected():
        logging.info('Connected!')
    else:
        logging.error('ERROR connecting to %s .' % (snap_ip))
        exit(1)
    logging.info('Programming SNAP Board')
    fpga.upload_to_ram_and_program(params['firmware'])
    # Configure iADC
    adc = iadc.Iadc(fpga)
    adc.set_dual_input()
    logging.info(
        'Board clock is %f' % (fpga.estimate_fpga_clock())
    )  #Board clock should be 1/4 of the sampling clock (board clock=125 MHz)
    # Deal with FFT shift, accumulation length, and sync trigger
    logging.info('Setting fft shift, accumulation length...')
    # fpga.write_int('fft_shift', 0x00000000)  # verified fft_of = 1 all the time
    # fpga.write_int('fft_shift', 0xF0F0F0F0)  # fft_of = 1 ~80% of the time
    # fpga.write_int('fft_shift', 0xFFF0F0FF)  # fft_of = 0 100% of the time
    # fpga.write_int('fft_shift', 0xF0F0F0FF)  # fft_of = 0 100% of the time
    # fpga.write_int('fft_shift', 0xF0F0F0F8)  # fft_of = 0 90% of the time
    # fpga.write_int('fft_shift', 0x80808088)  # fft_of = 1 100% of the time
    # fpga.write_int('fft_shift', 0xC0C0C0C8)  # fft_of = 1 100% of the time
    # fpga.write_int('fft_shift', 0xE0E0E0E8)  # fft_of = 1 100% of the time
    # fpga.write_int('fft_shift', 0xF0F0F0FF)  # fft_of = 0 90% of the time
    # As of 4 May 2017, above value is dead to us.
    # fpga.write_int('fft_shift', 0xFFFFFFFF)  # fft_of = 0 90% of the time
    fpga.write_int('fft_shift', params['fft-shift'])
    fpga.write_int('acc_len', params['accumulation-length'])
    logging.info('Done configuring')
    time.sleep(2)
    return fpga
예제 #17
0
def main():
    s = None
    try:
        fpga = casperfpga.CasperFpga(
            gc[np.where(gc == 'roach_ppc_ip')[0][0]][1], timeout=120.)
    except RuntimeError:
        fpga = None
    # UDP socket
    s = socket(AF_PACKET, SOCK_RAW, htons(3))

    # Valon synthesizer instance
    try:
        #valon = valon_synth9.Synthesizer(gc[np.where(gc == 'valon_comm_port')[0][0]][1])
        valon = None
        print "$NO VALON$"
    except OSError:
        "Valon could not be initialized. Check comm port and power supply."

    # Roach interface
    ri = roachInterface(fpga, gc, regs, valon)

    # GbE interface
    udp = roachDownlink(ri, fpga, gc, regs, s, ri.accum_freq)
    udp.configSocket()
    os.system('clear')
    while 1:
        try:
            upload_status = 0
            if fpga:
                if fpga.is_running():
                    #firmware_info = fpga.get_config_file_info()
                    upload_status = 1
            time.sleep(0.1)
            upload_status = main_opt(fpga, ri, udp, valon, upload_status)
        except TypeError:
            pass
    return
예제 #18
0
        if timeout == 1000:
            print("ERROR: Timeout waiting for ADC SYNC to complete!")

        # Disable the ADC SYNC
        for mezzanine in range(0, 4):
            if synchronise_mezzanine[mezzanine] == True:
                print(("Disabling ADC SYNC on mezzanine: ", mezzanine))

                skarab.transport.write_i2c(i2c_interface,
                                           STM_I2C_DEVICE_ADDRESS,
                                           MEZ_CONTROL_REG, 0x0)


# Connect to SKARAB and upload .fpg file
skarab = casperfpga.CasperFpga('10.0.0.14')
skarab.upload_to_ram_and_program('test_skarab_adc_2019-01-28_1152.fpg')
skarab.listdev()
# Specify Mezzanine Site
mezzanine_site = 2
# Create SKARAB ADC receiver controller object
skarab_adc_rx_obj = skarab_adc_rx(skarab, mezzanine_site)
#skarab_adc_rx_obj.ConfigureGain(skarab, 0, 0)
#skarab_adc_rx_obj.ConfigureAdcDdc(skarab, 0, False)
#skarab_adc_rx_obj.EnableAdcRampData(skarab)
skarab_adc_rx_obj.PerformAdcPllSync(skarab)

# Read register values
read_value = skarab.read_int('adc0_data_q_out0')
print(("ADC0 Q:", read_value))
read_value = skarab.read_int('adc0_data_i_out0')
    parser.add_argument(
        "-D",
        "--drive",
        type=str,
        default='',
        help=
        "Force output drive to this (otherwise use drive with most empty space)"
    )
    args = parser.parse_args()

    use_trimble = True

    try:
        ip_port = args.ip.split(":")
        snap = casperfpga.CasperFpga(host=ip_port[0],
                                     port=ip_port[1],
                                     transport=casperfpga.KatcpTransport)
        if snap.is_running():
            print("SNAP board is up and programmmed")
            snap.get_system_information()
            print(snap.listdev())
        else:
            print("SNAP board not programmed")
        pols = args.pol.split(" ")
        print(pols)
        regs = ["sync_cnt", "pfb_fft_of", "acc_cnt", "sys_clkcounter"]
        if use_trimble:
            if trimble_utils.get_report_trimble() is None:
                print("Trying to use GPS clock but Trimble not detected.")
            else:
                print("Trimble GPS clock successfully detected.")
예제 #20
0
#!/usr/bin/env python

import casperfpga, struct, time
import matplotlib.pyplot as plt
import numpy as np
import sys


def swap16(x):
    return (((x >> 8) & 0x00FF) | ((x << 8) & 0xFF00))


fpganame = sys.argv[1]

fpga = casperfpga.CasperFpga(fpganame, timeout=20)

acc_snap = struct.unpack('>2048H', fpga.read('acc_16', 2048 * 2))

#acc1 = acc_snap[0::4]
#acc2 = acc_snap[1::4]
#acc3 = acc_snap[2::4]
#acc4 = acc_snap[3::4]

#acc1a = np.zeros((512))
#acc2a = np.zeros((512))
#acc3a = np.zeros((512))
#acc4a = np.zeros((512))
#
#for i in range(0,512):
#	acc1a[i] = swap16(acc1[i])
#	acc2a[i] = swap16(acc2[i])
예제 #21
0
    parser.add_argument('-i', '--dest_ip', default='10.0.0.100',
                        help='Destination IP. Default:10.0.0.100')
    parser.add_argument('-m', '--dest_mac', type=str, default="0x020304050607",
                        help='Destination MAC address. Must be specified as \
                              a hex string. Default:0x020304050607')
    parser.add_argument('-P', '--dest_port', type=int, default=10000,
                        help='Destination UDP port. Default:10000')
    parser.add_argument('-S', '--spec_per_packet', type=int, default=8,
                        help='Number of spectra per packet. Default:8')
    parser.add_argument('-B', '--bytes_per_spectra', type=int, default=128,
                        help='Number of valid bytes per packet. Default:128')

    opts = parser.parse_args()

    print 'Connecting to %s' % opts.snap
    r = casperfpga.CasperFpga(opts.snap, transport=casperfpga.KatcpTransport)
    time.sleep(0.05)

    if r.is_connected():
        print 'Connected!'
    else:
        print 'Failed to Connect!'
        exit()

    if opts.prog:
        print 'Trying to program with fpgfile %s' % opts.fpgfile
        print '(You probably don\'t want to do this -- this script won\'t configure the ADCs)'
        print 'TODO: see the spectrometer tutorial for details of how to calibrate SNAP\'s ADCs using casperfpga'
        r.upload_to_ram_and_program(opts.fpgfile)
        print 'done'
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul  5 14:22:17 2019

@author: talon
"""

import numpy as np
import casperfpga
import pickle

##########FPGA setup###########
fpga =  casperfpga.CasperFpga('skarab020A44-01')
fpga.upload_to_ram_and_program('meerkat_4k_pfb.fpg')
fpga.registers.fft_shift.write(reg=0)
fpga.registers.control.write(src_mux=0)

#######Sort Data placement#####
outputdict={"read_init":{"valid_count":0,"of_count":0,"real":np.zeros(4,dtype=np.float64),"imag":np.zeros(4,dtype=np.float64)}}


##########Initialise###########
fpga.registers.control.write(en=1)
fpga.registers.control.write(sync=1)

fpga.registers.control.write(sync=0)


i=0
j=0
# -*- coding: utf-8 -*-
import numpy as np
import casperfpga
import pickle
import sys

##########FPGA setup###########
board = sys.argv[1]  #specify IP of board to program
image = sys.argv[2]  #specify image to program FPGA
inputdata = sys.argv[3]  #specify data to process
stackcount = int(sys.argv[4]) * 128  #specify how many full reads are required
floatorint = bool(sys.argv[5])  #process float or integer
fpga = casperfpga.CasperFpga(board)  #configure board as object
fpga.upload_to_ram_and_program(image)  #upload image to board
fpga.registers.fft_shift.write(reg=0)  #populate FFT shift registers
if (floatorint):
    fpga.registers.control.write(
        src_mux=0)  #decide on whether to pass floats (0) or ints (1)
    DTYPE = np.float
else:
    fpga.registers.control.write(
        src_mux=1)  #decide on whether to pass floats (0) or ints (1)
    DTYPE = np.int32

#######Sort Data placement#####
data = np.load(inputdata)  #fetch data from npy file
#Per read, we get 4 real and 4 imag results, which are stored in a dictionary with key = #read
outputdict = {
    "read_init": {
        "valid_count": 0,
        "of_count": 0,
예제 #24
0
                        action='store_true',
                        help="Enable iPython control")

    args = parser.parse_args()

    if args.snap == "":
        print 'Please specify a SNAP board. \nExiting'
        exit()
    else:
        snap = args.snap

    if args.fpgfile != '':
        fpgfile = args.fpgfile

print "Connecting to server %s . . . " % (snap),
fpga = casperfpga.CasperFpga(snap)
time.sleep(1)

if fpga.is_connected():
    print 'ok\n'
else:
    print 'ERROR connecting to server %s . . .' % (snap)
    exit_fail()

# program fpga with bitstream

print '------------------------'
print 'Programming FPGA...',
sys.stdout.flush()
fpga.upload_to_ram_and_program(fpgfile)
time.sleep(1)
예제 #25
0
#!/usr/bin/env python
'''
Description:
    Display the power going into the ADC chips on SNAP Board.
======================================================================
Notes:
    This script was confirmed to be accurate in dBm units, with a very small difference 
    to powermeter. 

Updated 07/25/2020
'''
import casperfpga
import numpy as np

fpga = casperfpga.CasperFpga('localhost')

try:
    import Tkinter as tk  # Python 2.x
except:
    import tkinter as tk  # Python 3.x


def get_adc_rms():
    '''
    This function gets sum square from 
    adc_sum_sq0, adc_sum_sq1, adc_sum_sq2
    software registers. 

    Parameters:  
    None 
예제 #26
0
import casperfpga, time

#Tutorial HMC (SKARAB) Python Script to read back the HMC snap shot data and the registers

#parameters
#snapshot read length (can be adjusted)
read_length = 600

#Connecting to the SKARAB
print 'connecting to SKARAB...'
f = casperfpga.CasperFpga('skarab020301')
print 'done'

#program the SKARAB
print 'programming the SKARAB...'
#f.upload_to_ram_and_program('tut9_2017-7-28_1414.fpg')
f.upload_to_ram_and_program('tut_hmc_2017-8-2_1100.fpg')
print 'done'

#Set the data rate control
#False = write and read every 2nd clock cycle (HMC can handle the data rate: 230MHz x 256 bits/2 = 29.44Gbps)
#True = write and read every clock cycle (HMC can't handle the data rate: 230MHz x 256 bits = 58.88Gbps)
f.registers.reg_cntrl.write(data_rate_sel=False)

#arm the snap shots
print 'arming snapshot blocks...'
f.snapshots.hmc_in_snap_ss.arm()
f.snapshots.hmc_out_snap_ss.arm()
f.snapshots.hmc_reorder_snap_ss.arm()
print 'done'
예제 #27
0
# with new firmware (hex file).
#
# The programming takes approximately 10 minutes to complete.
#
# After the programming is complete, the SKARAB can be rebooted so that it
# can boot with its new firmware.
#
# Set the script configuration (under "1. SCRIPT CONFIG") as required.
#
#--------------------------------------------------------------------------------------

import casperfpga

# ---------------------------------------------------------------
# 1. SCRIPT CONFIG
# ---------------------------------------------------------------
# SKARAB IP ADDRESS
skarab_ip_address = '10.0.7.3'
# HEX FILE NAME (SHOULD BE UNDER SAME DIRECTORY AS THIS SCRIPT)
hex_file_name = 'frm123701u1r4_mez3.hex'

# ---------------------------------------------------------------
# 2. RECONFIGURE VIRTEX-7 FPGA FLASH ON SKARAB
# ---------------------------------------------------------------
fpga = casperfpga.CasperFpga(skarab_ip_address)
print(
    "Programming Virtex 7 FPGA flash on SKARAB (the process takes approximately 10 minutes to complete)..."
)
fpga.transport.virtex_flash_reconfig('frm123701u1r4_mez3.hex')
print("Programming complete...")
예제 #28
0
# DO NOT CHANGE THESE THREE VALUES!!!
mac_location = 0x00
ip_location = 0x10
port_location = 0x8

try:
    #lh = corr.log_handlers.DebugLogHandler()
    lh = logging.StreamHandler()
    #lh = casperfpga.casperfpga.logging.getLogger()
    logger = logging.getLogger(snap)
    logger.addHandler(lh)
    logger.setLevel(10)

    print('Connecting to server %s... ' % (snap)),
    fpga = casperfpga.CasperFpga(snap, logger=logger)
    #fpga = corr.katcp_wrapper.FpgaClient(snap, logger=logger)
    time.sleep(1)

    if fpga.is_connected():
        print 'ok\n'
    else:
        print 'ERROR connecting to server %s.\n' % (snap)
        exit_fail()

    if not opts.noprogram:
        print '------------------------'
        print 'Programming FPGA...',
        sys.stdout.flush()
        fpga.upload_to_ram_and_program(fpgfile)
        time.sleep(10)
예제 #29
0
                    help='RF centre frequency in MHz')
parser.add_argument('-i',
                    dest='ifc',
                    type=float,
                    default=629.1452,
                    help='IF centre frequency in MHz')

args = parser.parse_args()

assert args.ant in ['0', '1', 'cross_even', 'cross_odd']

print "Using RF center frequency of %.2f" % args.rfc
print "Using IF center frequency of %.2f" % args.ifc

print "Connecting to %s" % args.host
snap = casperfpga.CasperFpga(args.host)
print "Interpretting design data for %s with %s" % (args.host, args.fpgfile)
snap.get_system_information(args.fpgfile)

print "Figuring out accumulation length"
acc_len = float(snap.read_int('timebase_sync_period') / (4096 / 4))
print "Accumulation length is %f" % acc_len

mux_sel = {'0': 0, '1': 0, 'cross': 1}
print "Setting snapshot select to %s (%d)" % (args.ant, mux_sel[args.ant])
snap.write_int('vacc_ss_sel', mux_sel[args.ant])

print "Snapping data"
x, t = snap.snapshots.vacc_ss_ss.read_raw()
d = np.array(struct.unpack('>%dl' %
                           (x['length'] / 4), x['data'])) / acc_len * 2**18.
예제 #30
0
"""
Currently, hwicap can't be use on VCU128.
Please make sure you finished the following steps before using this script:
1. download lwip_echo_server.bit via vivado
2. download top.bit via vivado
"""
import casperfpga
import time
import matplotlib.pyplot as plt
# 10.0.1.25 is the IP address of VCU128
fpga = casperfpga.CasperFpga('10.0.1.25')
fpga.get_system_information('adc_snapshot_inside_2021-01-10_2322.fpg')
fpga.adcs.adc_16g_asnt.adc_init()
reg_addr = [1, 3, 5, 7, 2, 4, 6, 8]
# These vals are related to the specific adc board
# Different boards should have different val lists
val = [825, 775, 700, 513, 420, 410, 410, 410]
fpga.adcs.adc_16g_asnt.set_DACs(reg_addr, val)
fpga.adcs.adc_16g_asnt.set_alignment()
time.sleep(2)
vals = []
fpga.adcs.adc_16g_asnt.get_samples(0, 1024, vals)