Esempio n. 1
0
def read_bytes_and_decrypt(handle, channel, to):

    byte_buffer = [None] * 4
    byte_count = 0
    current_time = time.time()
    time_out = False
    not_zero_det = False

    while not not_zero_det:
        if time.time() - current_time > to:
            time_out = True
            break
        else:
            num = fl.flReadChannel(handle, channel, 1)
            fl.flSleep(50)
            if not num == 0:
                byte_buffer[byte_count] = num
                byte_count += 1
                while byte_count < 4:
                    num = fl.flReadChannel(handle, channel, 1)
                    byte_buffer[byte_count] = num
                    fl.flSleep(50)
                    byte_count += 1
                not_zero_det = True

    if not time_out:
        byte_buffer.reverse()
        c = 0
        for read_byte in byte_buffer:
            c = c << 8 | read_byte
        p = decrypt(c)
        return p
    else:
        return False
Esempio n. 2
0
def findCenter(handle, init_only):

    laserInit(handle)
    thresholdInit(handle, 0, 15000)  #CHECK THE STARTING POINT HERE
    thresholdInit(handle, 1, 15000)
    thresholdInit(handle, 2, 15000)
    sleep(5)
    print("Initialization Complete")
    if (init_only):
        return
    while (fl.flReadChannel(handle, memMap.get_register('PDI')) < 1):

        #check starting temp
        MSB = fl.flReadChannel(handle, memMap.get_register('LTSa'))
        LSB = fl.flReadChannel(handle, memMap.get_register('LTSb'))

        value = MSB * 256 + LSB
        new_value = value + 1
        new_MSB = new_value / 256
        new_LSB = new_value % 256
        fl.flWriteChannel(handle, memMap.get_register('LTSa'), new_MSB)
        fl.flWriteChannel(handle, memMap.get_register('LTSb'), new_LSB)
        sleep(.15)
        if (new_value < 1100 or new_value > 1800):
            print("Center frequency was not matched")
            return
        reg64 = fl.flReadChannel(handle, memMap.get_register('PDI'))
        print(new_value, MSB, new_MSB, LSB, new_LSB, "Power level: ", reg64)
    print("matched center frequency")
Esempio n. 3
0
    def getLaserCurrent(self):

        #Current Consumption 3
        #MSB_channel = 100   #CC3a
        MSB_channel = self.getMemMap().getAddress('CC3a')
        #LSB_channel = 101   #CC3b
        LSB_channel = self.getMemMap().getAddress('CC3b')

        rxm = fl.flReadChannel(self.handle, MSB_channel)
        rxl = fl.flReadChannel(self.handle, LSB_channel)

        #converts the bytes read to a current value
        return (rxm*256 + rxl)/4096 * (4.096*1.1*((1/6.81)+(1/16500)))
Esempio n. 4
0
def read_SPI(handle, channels):
    """
    Reads the SPI

    Args:
        handle: An opaque reference to an internal structure representing the connection.
        channels(list): channles to be used as conduits

    Returns:
        (list): rxm and rxl read from channels specified
    """
    MSB_channel = channels[0]
    LSB_channel = channels[1]
    rxm = fl.flReadChannel(handle, MSB_channel)
    rxl = fl.flReadChannel(handle, LSB_channel)
    return [rxm, rxl]
Esempio n. 5
0
    def measureSER(self, obslength=1.0):
        # Wait for DAC to settle
        time.sleep(0.1)

        # Reset cycle and error counters
        fl.flWriteChannel(self.handle, self.FIFO_ASYNC_WR, 0x00)

        # Wait for the observation time
        time.sleep(obslength)

        # TODO: combine commands below together
        # Latch cycle and error counters
        fl.flWriteChannel(self.handle, self.FIFO_ASYNC_WR, 0x01)

        # Request readback of cycle counter and error counter
        fl.flWriteChannel(self.handle, self.FIFO_ASYNC_WR,
                          0x03)  # cycle counter
        fl.flWriteChannel(self.handle, self.FIFO_ASYNC_WR,
                          0x04)  # error counter
        fl.flWriteChannel(self.handle, self.FIFO_ASYNC_WR,
                          0x05)  # ones counter

        # Readback counters (two counters, each 8 bytes)
        resp = fl.flReadChannel(self.handle, self.FIFO_ASYNC_RD, 24)
        if self.DEBUG: print "Length of response:", len(resp)
        if self.DEBUG: print[hex(a) for a in resp]
        (cycles, errors, ones) = struct.unpack(">QQQ", resp)
        ser = float(errors) / float(cycles)

        if self.DEBUG:
            print "0x%016X 0x%016X 0x%016X SER = %e" % (cycles, errors, ones,
                                                        ser)

        return cycles, errors, ones, ser
Esempio n. 6
0
def checkTECPowerOn(handle):

    status = fl.flReadChannel(handle, memMap.get_register('PO4'))
    if (status != 85):
        return False
    else:
        return True
Esempio n. 7
0
def debounce(handle, length, reg, pin, val):
    pos = 0.0
    mask = 0b00000001 << pin
    for i in range(length):
        if (fl.flReadChannel(handle, reg & mask) == val):
            pos += 1
    return pos / length
Esempio n. 8
0
def laserInit(handle):
    #if(checkTECPowerOn(handle) == False):
    #Set DAC for TEC Controller before turning on power. Otherwise it will burn out the laser
    #Setting temp to 4,20 should be 25C Use below table as a guide for temps
    #Temps should be set between 35-45C
    # 25C = 8,52
    # 30C = 7,78
    # 35C = 6,114
    # 40C = 5,170
    # 45C = 4,246
    fl.flWriteChannel(handle, 1, 4)
    fl.flWriteChannel(handle, 2, 100)
    print("Wrote to TEC registers")
    sleep(.10)
    #Turn on TEC Power/LD Controller Power AND make sure TEC set voltage is non zero
    if (fl.flReadChannel(handle, 1) > 0):
        fl.flWriteChannel(handle, 36, 85)
        print("TEC Power on")

    #Turn on Current Driver Power to drive current make sure initial values are zero
    fl.flWriteChannel(handle, 3, 0)
    fl.flWriteChannel(handle, 4, 0)
    #fl.flWriteChannel(handle,33,85)
    print("LD Bias Power On")

    #Set Start current at minimum threshold of 30mA
    #Equation for current: 4.096 *1.1(1/6.81+1/16500)*CODE/4096
    #Code = MSB + LSB
    fl.flWriteChannel(handle, 33, 85)
    sleep(.25)
    fl.flWriteChannel(handle, 3, 15)
    fl.flWriteChannel(handle, 4, 100)
    print("Laser Current Code set to 60mA")
Esempio n. 9
0
 def fill_fifo(self):
     count = 0
     end = 2048
     while (count != len(self.bytes)):
         fifo_space = 2048 - (
             (0x07 & fl.flReadChannel(
                 self.handle, self.memory.get_register('fff')) << 8) +
             fl.flReadChannel(self.handle, self.memory.get_register('dfp')))
         if (fifo_space > 0):
             end += fifo_space
             if (end > len(self.bytes)):
                 end = len(self.bytes)
             fl.flWriteChannel(self.handle, memMap.get_register('dat'),
                               bytearray(self.bytes[count:end]))
             print('Data FIFO Pointer = ' + str(
                 fl.flReadChannel(self.handle,
                                  self.memory.get_register('dfp'))))
             count = end
Esempio n. 10
0
    def read(self, channel):
        """
		Reads binary data from FPGA at channel

		Args:
			channel(int): channel to be read
		"""

        return fl.flReadChannel(self.handle, channel)
Esempio n. 11
0
    def getLaserTemp(self):

        #Measured Temp
        #MSB_channel = 116   #LTMa
        MSB_channel = self.getMemMap().getAddress('LTMa')

        #LSB_channel = 117   #LTMb
        LSB_channel = self.getMemMap().getAddress('LTMb')
        
        rxm = fl.flReadChannel(self.handle,MSB_channel)
        rxl = fl.flReadChannel(self.handle,LSB_channel)

        code_meas = rxm*256 + rxl           #byte to code
        V_meas = self.code2voltage(code_meas)

        #Converts voltage to temperature
        R_t = R_known * (Vcc/V_meas - 1)
        T = B/m.log(R_t/R_0 * m.exp(-B/T_0))

        return T
Esempio n. 12
0
    def test_read(self, channel, expected):
        """
		Compares data read from channel to what is expected from channel

		Args:
			channel(int): conduit channel to communicate through to fpga board
			expected(): expected response from communication through channel
		Returns:
			(boolean): True if expected matches what is read, else false
		"""

        return expected == fl.flReadChannel(self.handle, channel)
Esempio n. 13
0
    def transfer(self, addr_in, is_write, values):

        # Prepare data
        iter_input = zip(addr_in, is_write, values)

        # Run transfer
        values_out = []
        for addr, w_f, val in iter_input:
            if w_f:
                fl.flWriteChannel(self.handle, addr, byte[num])
                values_out.append(None)
            else:
                values_out.append(fl.flReadChannel(self.handle, addr))

        #no error check for USB
        errors = [0] * len(addr_in)

        return errors, values_out
Esempio n. 14
0
    def readSLERcounts(self):
        # Latch cycle and error counters
        fl.flWriteChannel(self.handle, self.FIFO_ASYNC_WR, 0x01)

        # Request readback of cycle counter and error counter
        fl.flWriteChannel(self.handle, self.FIFO_ASYNC_WR,
                          0x03)  # cycle counter
        fl.flWriteChannel(self.handle, self.FIFO_ASYNC_WR,
                          0x04)  # error counter
        fl.flWriteChannel(self.handle, self.FIFO_ASYNC_WR,
                          0x05)  # ones counter

        # Readback counters (two counters, each 8 bytes)
        resp = fl.flReadChannel(self.handle, self.FIFO_ASYNC_RD, 24)
        if self.DEBUG: print "Length of response:", len(resp)
        if self.DEBUG: print[hex(a) for a in resp]
        (cycles, errors, ones) = struct.unpack(">QQQ", resp)
        ser = float(errors) / float(cycles)

        if self.DEBUG:
            print "0x%016X 0x%016X 0x%016X SER = %e" % (cycles, errors, ones,
                                                        ser)

        return cycles, errors, ones, ser
Esempio n. 15
0
    def downlink(self, FILE):
        M = int(self.ppm_order) >> 2
        f = open(FILE, 'rb')
        self.bytes += [
            128 + self.ppm_order
        ]  # create first byte (sets ppm order in FPGA), MSB tells FPGA whether this byte sets the ppm order (1) or not (0), other 7 bits are data

        # read file data into an array
        done = False
        while not done:
            char = f.read(1)
            if (char == ''):
                f.close()
                done = True
            else:
                self.data += [ord(char)]

        self.pack_data()
        self.fill_fifo()

        ones = 0
        errors = 0
        while (fl.flReadChannel(self.handle, self.memory.get_register('efp'))
               or
               fl.flReadChannel(self.handle, self.memory.get_register('fff'))
               & 56):
            errors += fl.flReadChannel(self.handle,
                                       self.memory.get_register('err'))
        while (fl.flReadChannel(self.handle, self.memory.get_register('ofp'))
               or
               fl.flReadChannel(self.handle, self.memory.get_register('fff'))
               & 196):
            ones += fl.flReadChannel(self.handle,
                                     self.memory.get_register('one'))
        #    print('Ones FIFO Pointer = '+str(fl.flReadChannel(handle, memMap.get_register('ofp'))))
        print('errors = ' + str(errors))
Esempio n. 16
0
        print("Programming device with config {}...".format(progConfig))
        if ( isNeroCapable ):
            fl.flProgram(handle, progConfig)
        else:
            raise fl.FLException("Device program requested but device at {} does not support NeroProg".format(vp))
    
    if ( argList.f and not(isCommCapable) ):
        raise fl.FLException("Data file load requested but device at {} does not support CommFPGA".format(vp))

    if ( isCommCapable and fl.flIsFPGARunning(handle) ):
        print("Zeroing R1 & R2...")
        fl.flWriteChannel(handle, 0x01, 0x00)
        fl.flWriteChannel(handle, 0x02, 0x00)
        if ( argList.f ):
            dataFile = argList.f[0]
            print("Writing {} to FPGALink device {}...".format(dataFile, vp))
            for chunk in readFile(dataFile):
                fl.flWriteChannelAsync(handle, 0x00, chunk)
        
        print("Reading channel 0...")
        print("Got 0x{:02X}".format(fl.flReadChannel(handle, 0x00)))
        print("Reading channel 1...")
        print("Got 0x{:02X}".format(fl.flReadChannel(handle, 0x01)))
        print("Reading channel 2...")
        print("Got 0x{:02X}".format(fl.flReadChannel(handle, 0x02)))

except fl.FLException as ex:
    print(ex)
finally:
    fl.flClose(handle)
Esempio n. 17
0
 def getTemp(self):
     self.measTemp = fl.flReadChannel(self.handle,
                                      memMap.get_register('LTMa')) << 8
     self.measTemp += fl.flReadChannel(self.handle,
                                       memMap.get_register('LTMb'))
Esempio n. 18
0
def readCurrent(handle):

    MSB = fl.flReadChannel(handle, memMap.get_register('LTSa'))
    LSB = fl.flReadChannel(handle, memMap.get_register('LTSb'))
    return MSB * 256 + LSB
Esempio n. 19
0
def read(a,b):
    return fl.flReadChannel(handle,a,b)
Esempio n. 20
0
 binary = []
 done = False
 count = 0
 end = 2048
 bin_size = 0xFF
 while not done:
     char = f.read(1)
     if (char == ''):
         done = True
     else:
         data += [ord(char)]
 #print(len(data))
 while (count != len(data)):
     fifo_space = 2048 - (
         (0x07
          & fl.flReadChannel(handle, memMap.get_register('fff')) << 8) +
         fl.flReadChannel(handle, memMap.get_register('dfp')))
     if (fifo_space > 0):
         end += fifo_space
         if (end > len(data)):
             end = len(data)
         fl.flWriteChannel(handle, memMap.get_register('dat'),
                           bytearray(data[count:end]))
         #print('Data FIFO Pointer = '+str(fl.flReadChannel(handle, memMap.get_register('dfp'))))
         count = end
 ones = 0
 errors = 0
 while (fl.flReadChannel(handle, memMap.get_register('efp'))
        or fl.flReadChannel(handle, memMap.get_register('fff')) & 56):
     errors += fl.flReadChannel(handle, memMap.get_register('err'))
 while (fl.flReadChannel(handle, memMap.get_register('ofp'))
Esempio n. 21
0
def checkLDPowerOn(handle):

    if (fl.flReadChannel(handle, 33) != 85):
        return False
    else:
        return True
Esempio n. 22
0
    def writeFile(self, writechannel, resetchannel, statuschannel,
                  data_packets, delay, vp):
        # inputs: channel to write data to, channel to reset (writes to this
        # channel reset modulator), channel to read back status flags, data_packets as a list of
        # bytearrays, delay between writing packets,FPGA identifier (vp)
        # outputs: writes to FPGA and writes to terminal

        # reset channel is 0x08, read channel is 0x05

        # initiate list for saving write times
        wholetime = []
        print("Writing to FPGAlink device {}...".format(vp))
        start_reset = time.time()  # start timer for reset
        fl.flWriteChannel(self.handle, resetchannel,
                          0x01)  # reset flags in FPGA
        time.sleep(0.02)
        flag = fl.flReadChannel(self.handle,
                                statuschannel)  # read out flag in FPGA
        print flag  # Print out value for flag - value of 0 shows that flags are cleared
        end_reset = time.time()  # determine time to perform reset
        # write data to virtual channel in FPGA
        for packet in data_packets:
            start = time.time()
            fl.flWriteChannel(self.handle, writechannel, packet)
            end = time.time()
            time.sleep(delay)
            wholetime.append(
                (end - start)
            )  # add write time to list for assessing time to write each packet
        start = time.time()  # initialize measuring time to read channel
        flag = fl.flReadChannel(
            self.handle, statuschannel)  # read flag for modulator status
        end = time.time()  # determine time to read channel
        # print information about time to read/write
        print("read time is: %f" % (end - start))
        maxtime = max(wholetime)
        mintime = min(wholetime)
        avgtime = sum(wholetime) / len(wholetime)
        print("Write time is %f" % avgtime)
        print("max time is %f" % maxtime)
        print("min time is %f" % mintime)
        print("Reset time is %f" % (end_reset - start_reset))
        # Print status of FPGA/modulator to terminal and reset flags
        if flag == 0x1E:
            fl.flWriteChannel(self.handle, resetchannel, 0x01)
            time.sleep(0.01)
            raise ValueError('data error and empty')
        elif flag == 0xFE:
            fl.flWriteChannel(self.handle, resetchannel, 0x01)
            time.sleep(0.01)
            print('data error and full')
            #raise ValueError('data error and full')
        elif flag == 0xDE:
            fl.flWriteChannel(self.handle, resetchannel, 0x01)
            time.sleep(0.01)
            print('data error')
            #raise ValueError('data error')
        elif flag == 0xFF:
            fl.flWriteChannel(self.handle, resetchannel, 0x01)
            time.sleep(0.01)
            raise ValueError('full and empty asserted')
        elif flag == 0xCF:
            fl.flWriteChannel(self.handle, resetchannel, 0x01)
            time.sleep(0.01)
            print('full asserted')
        elif flag == 0x11:
            fl.flWriteChannel(self.handle, resetchannel, 0x01)
            time.sleep(0.01)
            raise ValueError('empty asserted')
        elif flag == 0xAF:
            fl.flWriteChannel(self.handle, resetchannel, 0x01)
            time.sleep(0.01)
            print('prog_full asserted')
        elif flag == 0xBF:
            fl.flWriteChannel(self.handle, resetchannel, 0x01)
            time.sleep(0.01)
            print('all prog_fulls asserted')
        else:
            print('Good fifo')
        print('file sent')
Esempio n. 23
0
            # ~ #print "HEADER_PID: " + HEADER_PID
            # ~ #Header format checks and padding
            # ~ assert len(HEADER_PID) <= HEADER_SIZE #Ensure HEADER is the right length
            # ~ if(len(HEADER_PID) < HEADER_SIZE):
            # ~ for i in range(HEADER_SIZE - len(HEADER_PID)):
            # ~ HEADER_PID = HEADER_PID + '\0' #append null padding
            # ~ assert HEADER_PID[len(HEADER_PID)-1] == '\0' #always terminate strings with null character ('\0') for c-code

            send_zmq(socket_FPGA_map_answer, raw)  #, HEADER_PID)
        else:
            print('| got FPGA_MAP_REQUEST_PACKET with READ in ENVELOPE %d' %
                  (ipc_fpgarqpacket.return_addr))
            # send the FPGA_map_answer packet (read)
            ipc_fpgaaswpacket_read = FPGAMapAnswerPacket()
            ch_val_read = str(
                fl.flReadChannel(handle, ipc_fpgarqpacket.start_addr)) + '\0\0'
            ch_val_read = ch_val_read.encode('ascii')
            raw = ipc_fpgaaswpacket_read.encode(
                return_addr=ipc_fpgarqpacket.return_addr,
                rq_number=ipc_fpgarqpacket.rq_number,
                rw_flag=0,
                error_flag=0,
                start_addr=ipc_fpgarqpacket.start_addr,
                size=len(ch_val_read),
                read_data=ch_val_read)
            ipc_fpgaaswpacket_read.decode(raw)
            print('SENDING to %s with ENVELOPE %d' %
                  (socket_FPGA_map_answer.get_string(
                      zmq.LAST_ENDPOINT), ipc_fpgaaswpacket_read.return_addr))
            print(ipc_fpgaaswpacket_read)
Esempio n. 24
0
def read_SPI(handle, channels):
    MSB_channel = channels[0]
    LSB_channel = channels[1]
    rxm = fl.flReadChannel(handle, MSB_channel)
    rxl = fl.flReadChannel(handle, LSB_channel)
    return [rxm, rxl]
Esempio n. 25
0
        print("Programming device with config {}...".format(progConfig))
        if isNeroCapable:
            fl.flProgram(handle, progConfig)
        else:
            raise fl.FLException("Device program requested but device at {} does not support NeroProg".format(vp))

    if argList.f and not (isCommCapable):
        raise fl.FLException("Data file load requested but device at {} does not support CommFPGA".format(vp))

    if isCommCapable and fl.flIsFPGARunning(handle):
        print("Zeroing R1 & R2...")
        fl.flWriteChannel(handle, 0x01, 0x00)
        fl.flWriteChannel(handle, 0x02, 0x00)
        if argList.f:
            dataFile = argList.f[0]
            print("Writing {} to FPGALink device {}...".format(dataFile, vp))
            for chunk in readFile(dataFile):
                fl.flWriteChannelAsync(handle, 0x00, chunk)

        print("Reading channel 0...")
        print("Got 0x{:02X}".format(fl.flReadChannel(handle, 0x00)))
        print("Reading channel 1...")
        print("Got 0x{:02X}".format(fl.flReadChannel(handle, 0x01)))
        print("Reading channel 2...")
        print("Got 0x{:02X}".format(fl.flReadChannel(handle, 0x02)))

except fl.FLException as ex:
    print(ex)
finally:
    fl.flClose(handle)
    print("jtagScanChain(): {")
    for idCode in fl.jtagScanChain(conn, PROG_CONFIG):
        print("  0x{:08X}".format(idCode))
    print("}")

    print("flProgram()...")
    fl.flProgram(conn, "J:{}:../../../../hdlmake/apps/makestuff/swled/cksum/vhdl/fpga.xsvf".format(PROG_CONFIG))
    print("...done.")

    fl.flSelectConduit(conn, CONDUIT)
    print("flIsFPGARunning(): {}".format(fl.flIsFPGARunning(conn)))

    fl.flWriteChannel(conn, 0, BYTE_ARRAY)

    bs = fl.flReadChannel(conn, 1, 16)
    print("flReadChannel(1, 16) got {} bytes: {{\n  {}\n}}".format(
        len(bs),
        " ".join(["{:02X}".format(b) for b in bs])))
    
    print("flReadChannel(2) got {:02X}".format(fl.flReadChannel(conn, 2)))

    fl.flReadChannelAsyncSubmit(conn, 0, 4)
    fl.flReadChannelAsyncSubmit(conn, 1, 8)
    fl.flReadChannelAsyncSubmit(conn, 2, 16)
    for i in range(3):
        bs = fl.flReadChannelAsyncAwait(conn)
        print("flReadChannelAsyncAwait() got {} bytes: {{\n  {}\n}}".format(
            len(bs),
            " ".join(["{:02X}".format(b) for b in bytearray(bs)])))