예제 #1
1
파일: forum.py 프로젝트: Jamiemattsmith/Pit
def RedPitaya_Connect ():
	global rp_s, samplingrate_pitaya, buffersize_pitaya, pointernow, pointerold, actual_time_pitaya, old_time_pitaya, decimation
	##OPEN CONNECTION TO RED PITAYA 1
	rp_s = scpi.scpi('148.122.56.1') 
	decimation = 8192
	buffersize_pitaya = 16384 #Buffersize [S]
	samplingrate_pitaya = 125e6/decimation #Sampling rate [S/s]
	rp_s.tx_txt('ACQ:RST') #reset aquire
	rp_s.tx_txt('ACQ:DEC ' + str(decimation)) #set the decimation value
	rp_s.tx_txt('ACQ:SOUR1:GAIN LV') #set voltage level according to jumpers (HV max 20V)
	rp_s.tx_txt('ACQ:SOUR2:GAIN LV') #set voltage level according to jumpers (HV max 20V)
	rp_s.tx_txt('ACQ:TRIG:LEV 0') #Trigger Level: 0 default = 0
	rp_s.tx_txt('ACQ:TRIG:DLY 8192') #Trigger Delay: 8192 Samples default = 0

	##Start the first acquisition
	rp_s.tx_txt('ACQ:START') #Starts acquisition
	rp_s.tx_txt('ACQ:TRIG DISABLED') #disabled --> continuous sampling
	rp_s.tx_txt('ACQ:WPOS?') #ask for the actual pointer position
	actual_time_pitaya = int(round(time.time() * 1000)) #in ms
	old_time_pitaya = actual_time_pitaya
	pointernow = int(rp_s.rx_txt())
예제 #2
0
def eval_scpi_slow_out_trigger_speed(rp_ip: str):
    # Establish connection
    rp_s = scpi.scpi(rp_ip)

    # Reset acquisition
    rp_s.tx_txt(f"ACQ:RST")

    # Setup acquisition
    rp_s.tx_txt(f"ACQ:DEC 64")
    rp_s.tx_txt(f"ACQ:TRIG:LEV 0")
    rp_s.tx_txt(f"ACQ:TRIG:DLY 0")

    # Start acquisition
    rp_s.tx_txt(f"ACQ:START")
    time.sleep(1)
    rp_s.tx_txt(f"ACQ:SOUR1:GAIN HV")
    rp_s.tx_txt(f"ACQ:SOUR2:GAIN HV")
    rp_s.tx_txt(f"ACQ:TRIG AWG_PE")
    rp_s.tx_txt(f"SOUR2:TRIG:IMM")

    rp_s.tx_txt(f"ANALOG:PIN AOUT0,1.8")
    time.sleep(0.001)
    rp_s.tx_txt(f"ANALOG:PIN AOUT0,0.1")

    gen_data = get_data_on_trigger(rp_s, 2)

    data_line_plt, data_line_ax = plt.subplots()
    data_line_ax = data_line_ax.plot(gen_data)

    data_line_plt.show()
def LED_blinking(number):
    rp_s = scpi.scpi('192.168.128.1')
    for i in range(5):
        time.sleep(1 / 2.0)
        rp_s.tx_txt('DIG:PIN LED' + str(number) + ',' + str(1))
        time.sleep(1 / 2.0)
        rp_s.tx_txt('DIG:PIN LED' + str(number) + ',' + str(0))
예제 #4
0
def scpi_server():
    # Scpi args are in form ARG1 ARG2,...,ARGN
    # as defined in scpi-99 standard
    post_request = json.loads(request.data.decode())
    rp_s = None
    response = {'success': False, 'data': "Pitaya not connected!"}
    print session['rp'].get('connected')
    if (session['rp'].get('connected') == True):
        rp_s = scpi.scpi(session.get('rp')['ip'])
        print session.get('rp')['ip']
    else:
        pass

    rp = session['rp']
    exec_type = post_request.get('type')

    if exec_type == 'single':
        scpi_command = post_request.get('scpi_command')
        scpi_args = post_request.get('scpi_args')

        if scpi_args:
            scpi_args = scpi_args.split(' ')
        rp_s.tx_txt(scpi_command + ' ' + ''.join(scpi_args))
        print scpi_command + ''.join(scpi_args)
    elif exec_type == 'script':
        scpi_script = post_request.get('scpi_script')
        print scpi_script

    response = {'success': True}
    return jsonify(response), 200
 def connect(self):
     if self.rp_s is None:
         self.rp_s = scpi.scpi(self.IP)  # setting a timeout does not help (random crashes)
         self.rp_s.tx_txt('ACQ:RST')
         self.rp_s.tx_txt('ACQ:DEC 1')
         self.rp_s.tx_txt('ACQ:TRIG:DLY 16384')
         self.rp_s.tx_txt('ACQ:DATA:UNITS VOLTS')
         self.rp_s.tx_txt('ACQ:AVG ON')
         self.rp_s.tx_txt('ACQ:SOUR1:GAIN HV')
         self.set_state(DevState.ON)
         print('diode connected')
예제 #6
0
def eval_scpi_fast_out_trigger_speed(rp_ip: str):
    # Establish connection
    rp_s = scpi.scpi(rp_ip)

    # Reset signal generator & oscilloscope
    rp_s.tx_txt(f"GEN:RST")
    rp_s.tx_txt(f"ACQ:RST")

    # Setup siggen
    # rp_s.tx_txt(f"SOUR1:FUNC SINE")
    # rp_s.tx_txt(f"SOUR1:FREQ:FIX 1000")
    # rp_s.tx_txt(f"SOUR1:VOLT 1")

    # Setup arbitrary waveform
    # wav = [0 for _ in range(1)] + [1 for _ in range(10000)]
    wav = [0] + [1 for _ in range(10000)]

    rp_s.tx_txt(
        f"SOUR1:TRAC:DATA:DATA {str(wav).strip('[]').replace(' ', '')}")
    rp_s.tx_txt(f"SOUR1:FUNC ARBITRARY")

    # Set burst mode, 1 pulse
    rp_s.tx_txt(f"SOUR1:BURS:STAT ON")
    rp_s.tx_txt(f"SOUR1:BURS:NCYC 1")
    rp_s.tx_txt(f"OUTPUT1:STATE ON")

    # Setup acquisition
    rp_s.tx_txt(f"ACQ:DEC 64")
    rp_s.tx_txt(f"ACQ:TRIG:LEV 0")
    rp_s.tx_txt(f"ACQ:TRIG:DLY 0")

    # Start acquisition
    rp_s.tx_txt(f"ACQ:START")
    time.sleep(1)
    rp_s.tx_txt(f"ACQ:SOUR1:GAIN HV")
    rp_s.tx_txt(f"ACQ:SOUR2:GAIN HV")
    rp_s.tx_txt(f"ACQ:TRIG AWG_PE")
    rp_s.tx_txt(f"SOUR1:TRIG:IMM")

    while True:
        rp_s.tx_txt('ACQ:TRIG:STAT?')
        if rp_s.rx_txt() == 'TD':
            break

    rp_s.tx_txt('ACQ:SOUR1:DATA?')
    buff_string = rp_s.rx_txt()
    gen_data = np.genfromtxt(
        buff_string.strip('{}\n\r').replace("  ", "").split(','))

    data_line_plt, data_line_ax = plt.subplots()
    data_line_ax = data_line_ax.plot(gen_data)

    data_line_plt.show()
예제 #7
0
    def meas_start(self):
        #if self.ui.ad_ver.text.isempty or self.ui.ad_name_meas.isempyty:
        #    self.ui.msg_text.setText("no path selcted")
        #elif self.ui.ad_val_meas.isempty:
        #    self.ui.msg_text.setText("no num of cycle set")
        #else:
            # Variables
            ip_adress = '192.168.128.1'
            file_path = str(self.ui.ad_ver.text())+'/'+str(self.ui.ad_name_meas.text())+'.csv'
            num_of_cycle = int(self.ui.ad_val_meas.text())
            buff_array = ''
            buff_np = np.zeros((num_of_cycle, 16384), float)

            # inizilation trigger
            rp_s = scpi.scpi(host=ip_adress)

            rp_s.tx_txt('ACQ:DEC 64')
            rp_s.tx_txt('ACQ:TRIG:LEVEL -21')
            rp_s.tx_txt('ACQ:TRIG:DLY 12192')
            rp_s.tx_txt('ACQ:START')
            rp_s.tx_txt('ACQ:TRIG EXT_NE')

            # wait untill trigger is activated
            while 1:
                rp_s.tx_txt('ACQ:TRIG:STAT?')
                if rp_s.rx_txt() == 'TD':
                    break
            for x in range(num_of_cycle):
                # collecting all 16xxx values and save and convert
                rp_s.tx_txt('ACQ:SOUR1:DATA?')
                buff_string = rp_s.rx_txt()
                buff_string = buff_string.strip('{}\n\r').replace("  ", "")
                buff = np.fromstring(buff_string, sep=',')
                buff = np.round(buff, 3)
                buff_np[x:] = buff

            np.savetxt(file_path, buff_np, delimiter=';', fmt='%.3f')
            print('done')
예제 #8
0
import time
import redpitaya_scpi as scpi
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
# redpitaya_scpi.py is used to connect to the SCPI server

def gaussian(x,a,b,n):
	return n*np.exp(-(x-b)**2/(2*a))
# intialize fit function

ip = '169.254.174.98'
# Get IP by typing arp -a in cmd line and looking for RP MAC address 
# Can also include ip as an argument when calling this script, use sys.argv

rp = scpi.scpi(ip)
# Initialize connection

rp.tx_txt('ACQ:RST')
# Reset acquisition parameters

decimation = 8
buff_time_ms = decimation * 131.072 * 10**-3
rp.tx_txt('ACQ:DEC '+str(decimation))
rp.tx_txt('ACQ:DEC?')
print('Decimation factor is '+rp.rx_txt())
print('Buffer length is ' +str(buff_time_ms) + ' ms')
# Set decimation, {1,8,64,1024,8192,65536}

avg = 'ON'
rp.tx_txt('ACQ:AVG '+ str(avg))
예제 #9
0
__author__ = "Luka Golinar <*****@*****.**>"

#Imports
import redpitaya_scpi as scpi
import unittest

#Scpi declaration
rp_scpi = scpi.scpi('192.168.1.241')

#Global variables
rp_dpin_p = {i: 'DIO' + str(i) + '_P' for i in range(8)}
rp_dpin_n = {i: 'DIO' + str(i) + '_N' for i in range(8)}
rp_a_pin_o = {i: 'AOUT' + str(i) for i in range(4)}
rp_a_pin_i = {i: 'AIN' + str(i) for i in range(4)}
rp_leds = {i: 'LED' + str(i) for i in range(8)}

rp_freq_range = [100, 1000, 10000, 100000, 1e+06, 1e+07, 3e+07]
rp_volt_range = [0.25, 0.5, 0.75, 1.0]
rp_phase_range = [-360, -180, -90, -30, 30, 90, 180, 360]
rp_offs_range = [-0.75, -0.5, -0.25, 0.25, 0.5, 0.75]
rp_dcyc_range = [0.5, 1, 10, 50, 75, 100]
rp_ncyc_range = [0, 1, 10, 100, 1000, 10000, 50000]
rp_nor_range = rp_ncyc_range[:]
rp_inp_range = [i * 100 for i in range(1, 6)]
rp_channels = ['CH1', 'CH2', 'MATH']
rp_scales = [0.5, 1, 2, 3, 10]
rp_decimation = ['1', '8', '64', '1024', '8192', '65536']
rp_sampling = ['100', '10000', '100000', '1000000', '10000000', '125000000']
rp_trig_dly = ['10', '1000', '10000', '16500']
rp_trig_dly_ns = ['10', '100', '250', '500']
rp_trig_level = ['10', '100', '1000']  #TODO: Add more options
예제 #10
0
# Before beginning, must execute:
# ssh [email protected] "nohup systemctl start redpitaya_scpi &"
# Send a guassian pulse from out1, acquire the pulse from in1, plot both
import redpitaya_scpi as scpi
import sys
import math
from scipy.signal import gaussian
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import numpy as np
import time

rp = scpi.scpi('rp-f06b95.local')

# in secs
decToTimeScale = {
    1: 131.072E-6,
    8: 1.049E-3,
    64: 8.389E-3,
    1024: 134.218E-3,
    8192: 1.074,
    65536: 8.590
}

# ========= parameters =========
gaussAmpl = 1
freq = 3000
volt = 1
dec = 8
totalAmpl = gaussAmpl * volt
#!/usr/bin/python

import sys
import redpitaya_scpi as scpi

rp_s = scpi.scpi(sys.argv[1])

wave_form = 'sine'
freq = 10000
ampl = 1

rp_s.tx_txt('GEN:RST')
rp_s.tx_txt('SOUR1:FUNC ' + str(wave_form).upper())
rp_s.tx_txt('SOUR1:FREQ:FIX ' + str(freq))
rp_s.tx_txt('SOUR1:VOLT ' + str(ampl))
rp_s.tx_txt('SOUR1:BURS:NCYC 2')
rp_s.tx_txt('OUTPUT1:STATE ON')
rp_s.tx_txt('SOUR1:BURS:STAT ON')
rp_s.tx_txt('SOUR1:TRIG:SOUR EXT_PE')
#!192.168.158.88

import redpitaya_scpi as scpi
import matplotlib.pyplot as plt
import numpy as np
import time
import math
plt.close('all')
rp_s = scpi.scpi('192.168.158.88')
print('Connected to RedPitaya')
rp_s.tx_txt('GEN:RST')
rp_s.tx_txt('ACQ:RST')
rp_s.tx_txt('ACQ:BUF:SIZE?')
BUFF_SIZE = int(rp_s.rx_txt())
#BUFF_SIZE = 15644
print(BUFF_SIZE)
f = 50
y1 = ''
t = []

#set up the values of the waveform
u50 = 1
f50 = 1
uharm = 0.1
fharm = 5

#calculate total waveform to normalize later
x = np.linspace(
    0, 2 * np.pi,
    BUFF_SIZE)  # generates x axis in range 0 to 6 with 20000 points
y = u50 * np.sin(2 * np.pi * x) + uharm * np.sin(2 * fharm * np.pi * x)
예제 #13
0
import redpitaya_scpi as scpi
import time

rp_s = scpi.scpi('152.78.194.163') #connect to red pitaya ip

#-----------------------------------------------------------------------------

def startRP(dec=1, lvl=0, dly=8192):
    sample_rate_dict = {'125':'125MHz', '15.6': '15_6MHz', '1.9': '1_9MHz'} #possible sample rates
    
    rp_s.tx_txt('ACQ:DEC %d' %dec) #decimation
    rp_s.tx_txt('ACQ:SRAT '+ sample_rate_dict['125']) #sample rate
    rp_s.tx_txt('ACQ:TRIG:LEV %d' %lvl) #trigger level in mV
    rp_s.tx_txt('ACQ:TRIG:DLY %d' %dly) #trigger delay in sample steps

#-----------------------------------------------------------------------------

'''Function to read data from Red Pitaya and return as array'''
def getdata(ch=1, tch=1):
    rp_s.tx_txt('ACQ:START')
    rp_s.tx_txt('ACQ:TRIG CH%d_PE' % tch)
    while 1:        
        rp_s.tx_txt('ACQ:TRIG:STAT?')
        if rp_s.rx_txt() == 'TD':
            break
    rp_s.tx_txt('ACQ:SOUR%d:DATA:LAT:N? 16384' % ch)
    buff_string = rp_s.rx_txt()
    buff_string = buff_string.strip('{}\n\r').replace("  ", "").split(',')
    buff = map(float, buff_string)
    return buff
    
예제 #14
0
#!/usr/bin/python

import sys
import redpitaya_scpi as scpi
import matplotlib.pyplot as plot
import time
rp_s = scpi.scpi("148.122.56.1")
buff_string = ""
dec = 1.00000000
freq = 7632.0
while (1):
    mode = input("Select mode")
    if mode == "acq":
        x = []
        rp_s.tx_txt("ACQ:DEC " + str(int(dec)))
        rp_s.tx_txt('ACQ:START')
        rp_s.tx_txt("ACQ:TRIG:DLY 16384")
        rp_s.tx_txt('ACQ:TRIG NOW')
        while 1:
            rp_s.tx_txt('ACQ:TRIG:STAT?')
            if rp_s.rx_txt() == 'TD':
                break
        rp_s.tx_txt('ACQ:SOUR1:DATA?')
        buff_string = rp_s.rx_txt()
        rp_s.tx_txt('ACQ:WPOS?')
        print(rp_s.rx_txt())
        buff_string = buff_string.strip('{}\n\r').replace(" ", "").split(',')
        buff = list(map(float, buff_string))
        err = 0
        for item in buff:
            if item > 1 or item < -1:
import peakutils
from peakutils.plot import plot as pplt

#-----------------------------------------------------------------------------

'''Create figure'''
plt.ion()
fig = plt.figure(figsize=(8,6))
ax = fig.add_subplot(111)
#ax2 = fig.add_subplot(212)
ax.set_ylabel('Voltage(V)')
ax.set_xlabel('Arbitrary Scale')

#-----------------------------------------------------------------------------

rp_s = scpi.scpi('152.78.193.126') #connect to red pitaya ip

xscale = 1 #scale of x-axis in ms

sample_rate_dict = {'125':'125MHz', '15.6': '15_6MHz', '1.9': '1_9MHz'} #possible sample rates

rp_s.tx_txt('ACQ:DEC 64') #decimation
rp_s.tx_txt('ACQ:SRAT '+ sample_rate_dict['125']) #sample rate
rp_s.tx_txt('ACQ:TRIG:LEV 0') #trigger level in mV
rp_s.tx_txt('ACQ:TRIG:DLY 8192') #trigger delay in sample steps

#-----------------------------------------------------------------------------

'''Function to read data from Red Pitaya and return as array'''
def getdata(ch=1, tch=2):
    rp_s.tx_txt('ACQ:START')
예제 #16
0
    # Setup acquisition
    acq.reset_acquisition(rp_s)
    acq.set_decimation(rp_s, 1)
    trig.set_trigger_level(rp_s, 500)
    trig.set_trigger_delay(rp_s, 17000)
    acq.set_channel_gain(rp_s, 1, "HV")
    acq.set_channel_gain(rp_s, 2, "HV")
    acq.start_acquisition(rp_s)
    trig.set_trigger_mode(rp_s, "NOW")
    gen.pulse_slow_analog_out(rp_s, aout=0, voltage=1.8, duration=0)
    trig.wait_for_trigd(rp_s)
    data_ch1 = acq.get_channel_data(rp_s, 1)
    data_ch2 = acq.get_channel_data(rp_s, 2)

    return data_ch1.append(data_ch2)


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("IP", type=str, help="The IP adress of the RedPitaya")

    arguments = parser.parse_args()

    sns.set_style("darkgrid")

    rp_connection = scpi.scpi(arguments.IP)
    try:
        eval_sipm(rp_s=rp_connection, num=2)
    finally:
        rp_connection.close()
예제 #17
0
파일: scpi_t.py 프로젝트: Gulzt/RedPitaya
__author__ = "Luka Golinar <*****@*****.**>"

#Imports
import sys
import redpitaya_scpi as scpi
import unittest
import collections


#Scpi declaration
rp_scpi = scpi.scpi('192.168.178.115')

#Global variables
rp_dpin_p  = {i: 'DIO'+str(i)+'_P' for i in range(8)}
rp_dpin_n  = {i: 'DIO'+str(i)+'_N' for i in range(8)}
rp_a_pin_o = {i: 'AOUT'+str(i) for i in range(4)}
rp_a_pin_i = {i: 'AIN'+str(i) for i in range(4)}
rp_leds    = {i: 'LED'+str(i) for i in range(8)}

rp_freq_range  = [100, 1000, 10000, 100000, 1e+06, 1e+07, 3e+07]
rp_volt_range  = [0.25, 0.5, 0.75, 1.0]
rp_phase_range = [360, -180, -90, -30, 30, 90, 180, 360]
rp_offs_range  = [-0.75, -0.5, -0.25, 0.25, 0.5 , 0.75]
rp_dcyc_range  = [0.5, 1, 10, 50, 75, 100]
rp_ncyc_range  = [1, 10, 100, 1000, 10000, 50000, 'INF']
rp_nor_range   = rp_ncyc_range[:]
rp_inp_range   = [i * 100 for i in range(1, 6)]


rp_wave_forms  = ['SINE', 'SQUARE', 'TRIANGLE', 'PWM', 'SAWU', 'SAWD']
예제 #18
0
def capture_traces(profiling=False, n_traces=1000, ext=''):

    # for dynamic plotting of traces
    if (plotting):
        plt.ion()
        plt.show()

    print('\n==============================')
    print('=                            =')
    print('=     TRACES ACQUISITION     =')
    print('=                            =')
    print('==============================\n')

    if (ext != ''):
        print('Set extension: ' + ext)

    # input('Press enter to proceed...\n')

    if plotting:
        plt.figure(1)
        plt.xticks([])
        plt.yticks([])
        plt.text(0.4, 0.5, 'Press enter to proceed...')
        input('Press enter to proceed...\n')

    # connection info to Red Pitaya
    # SCPI server should run
    rp_addr = '192.168.1.6'
    rp_port = 5000
    rp_timeout = 5
    rp_s = scpi.scpi(rp_addr, timeout=rp_timeout, port=rp_port)
    rp_s.tx_txt('ACQ:RST')

    # connection info to Arduino
    # ser_port = '/dev/tty.usbmodem14101'
    ser_port = 'COM5'
    ser_baud = 19200
    ser_timeout = 5
    ser = serial.Serial(ser_port, ser_baud, timeout=ser_timeout)
    s = ser.readline()
    print(s.decode())

    # commands for Arduino
    LOAD_KEY = bytes([0x01])
    STOR_KEY = bytes([0x02])
    ENC_TXT = bytes([0x10])
    DEC_TXT = bytes([0x11])
    REQ_VER = bytes([0xff])

    # preparation of the demodulation parameters (only for display)
    fs = 125  # sampling frequency [MHz]
    cutoff = 10  # cutoff frequency [MHz]
    width = 4  # transition width [MHz]
    attenuation = 65  # stop band attenuation [dB]

    # trace acquisition parameters
    nt = n_traces  # total number of traces
    nl = 16384  # number of samples per trace

    if (profiling):
        print('CAPTURING PROFILING TRACES')
        filename = '../traces/profiling_set_nt_' + str(nt) + ext + '.mat'
    else:
        print('CAPTURING ATTACK TRACES')
        filename = '../traces/attack_set_nt_' + str(nt) + ext + '.mat'

    traces = np.zeros((nt, nl))
    traces_sum = np.zeros(nl)
    traces_sum2 = np.zeros(nl)

    if (profiling):
        keys = np.zeros((nt, 32))
    plaintexts = np.zeros((nt, 16))
    ciphertexts = np.zeros((nt, 16))

    # for handling timeout with red pitaya commands
    acquisitionDone = False
    timeoutInARow = 0
    maxTimeoutInARow = 5

    for i in range(nt):
        print('-------------------------')
        print('Trace ' + str(i + 1) + ' (' + str(nt) + ')')
        print('-------------------------')

        timeoutInARow = 0
        acquisitionDone = False

        while acquisitionDone == False:
            try:

                # oscilloscope configuration
                rp_s.tx_txt('ACQ:START')
                rp_s.tx_txt('ACQ:DEC 1')
                rp_s.tx_txt('ACQ:SOUR1:GAIN LV')
                rp_s.tx_txt('ACQ:SOUR2:GAIN LV')
                rp_s.tx_txt('ACQ:TRIG:LEV 300 mV')
                rp_s.tx_txt('ACQ:TRIG:LEV?')
                data = rp_s.rx_txt()
                # print('Trigger level ' + data)
                rp_s.tx_txt('ACQ:TRIG:DLY 8000')
                rp_s.tx_txt('ACQ:TRIG:DLY?')
                data = rp_s.rx_txt()
                # print('Trigger delay ' + data)
                rp_s.tx_txt('ACQ:TRIG CH2_PE')
                rp_s.tx_txt('ACQ:TRIG:STAT?')
                data = rp_s.rx_txt()
                # print('Trigger status ' + data)

                # sending key
                if (profiling):
                    key = np.random.bytes(32)
                    ser.write(LOAD_KEY)
                    s = ser.readline()
                    print(s.decode()[:-1])
                    ser.write(key)
                    s = ser.readline()
                    print(s.decode()[:-1])
                    s_hex = "KEY: " + "".join('%02x ' % b for b in key)
                    print(s_hex)

                # sending plaintext
                plaintext = np.random.bytes(16)
                ser.write(ENC_TXT)
                s = ser.readline()
                print(s.decode()[:-1])
                ser.write(plaintext)
                ptx = "".join('%02x ' % b for b in plaintext)
                s_hex = "PTX: " + ptx
                print(s_hex)

                # waiting 1ms to make the AES execution is complete
                time.sleep(0.001)

                # ciphertext recovery
                ciphertext = ser.read(16)
                ctx = "".join('%02x ' % b for b in ciphertext)
                s_hex = "CTX: " + ctx
                print(s_hex)

                # check if triggered
                rp_s.tx_txt('ACQ:TRIG:STAT?')
                data = rp_s.rx_txt()
                if data == 'TD':
                    print()
                else:
                    print("Error: no trigger detected. Stopping acquisition.")
                    exit()

                # trace acquisition
                rp_s.tx_txt('ACQ:SOUR1:DATA?')
                data = rp_s.rx_txt()
                data = data.strip('{}\n\r')
                trace = np.fromstring(data, dtype=float, sep=',')

                # stopping acquisition
                rp_s.tx_txt('ACQ:STOP')
                acquisitionDone = True

            except socket.timeout:
                # this exception handling is there because of (so far) unexpected
                # loss of TCP connection with the Red Pitaya: it stops answering
                # requests and a timeout exception is issued
                #
                # the only solution I found is to re-open the connection
                # with the Red Pitaya (max 5 times)

                rp_s.close()
                rp_s = scpi.scpi(rp_addr, timeout=rp_timeout, port=rp_port)

                acquisitionDone = False
                timeoutInARow += 1
                if timeoutInARow >= maxTimeoutInARow:
                    print('Something is fishy, too many timeouts!')
                    exit()
                else:
                    print('Timeout during acquisition! Re-trying...')

        if (profiling):
            keys[i, :] = np.frombuffer(key, dtype=np.uint8).astype(float)
        plaintexts[i, :] = np.frombuffer(plaintext,
                                         dtype=np.uint8).astype(float)
        ciphertexts[i, :] = np.frombuffer(ciphertext,
                                          dtype=np.uint8).astype(float)

        traces[i, :] = trace

        # trace demodulation (only for display)
        trace_demodulated = sca.kaiser_LP_filter(np.absolute(trace), fs,
                                                 cutoff, width, attenuation)

        traces_sum += trace_demodulated
        traces_sum2 += trace_demodulated**2
        traces_avg = traces_sum / (i + 1)
        traces_var = traces_sum2 / (i + 1) - traces_avg**2

        if (plotting):

            plt.figure(1)
            plt.clf()

            plt.subplot(2, 1, 1)
            plt.title('Trace ' + str(i) + ' (' + str(nt) + ')', fontsize=20)
            plt.axis([0, nl, 0, 0.06])
            plt.plot(trace_demodulated)
            plt.ylabel('demodulated', fontsize=15)
            plt.tick_params(axis='both',
                            which='both',
                            bottom=False,
                            top=False,
                            left=False,
                            right=False,
                            labelleft=False,
                            labelbottom=False)

            plt.subplot(2, 1, 2)
            plt.axis([0, nl, 0, 0.05])
            plt.plot(traces_avg)
            plt.ylabel('average', fontsize=15)
            plt.xlabel('time samples', fontsize=15)
            plt.tick_params(axis='both',
                            which='both',
                            bottom=False,
                            top=False,
                            left=False,
                            right=False,
                            labelleft=False,
                            labelbottom=False)

            plt.draw()
            plt.pause(0.01)

    if (profiling):
        sio.savemat(
            filename,
            dict([('nt', nt), ('nl', nl), ('keys', keys),
                  ('plaintexts', plaintexts), ('ciphertexts', ciphertexts),
                  ('traces', traces)]))
    else:
        sio.savemat(
            filename,
            dict([('nt', nt), ('nl', nl), ('plaintexts', plaintexts),
                  ('ciphertexts', ciphertexts), ('traces', traces)]))

    print('\nTraces saved in ' + filename + '\n')

    ser.close()
예제 #19
0
#! /usr/bin/python

import sys
import time
import redpitaya_scpi as scpi
# redpitaya_scpi.py is used to connect to the SCPI server

ip = '169.254.174.98'
# Get IP by typing arp -a in cmd line and looking for RP MAC address 
# Can also include ip as an argument when calling this script, use sys.argv

rp_s = scpi.scpi(ip)
# Initialize connection

def SetDecimation(dec,rp):
	rp.tx_txt('ACQ:DEC '+str(dec))

def StartAcquisition(rp):
	rp.tx_txt('ACQ:START')


class FastAnalogOutput:
	def __init__(self,sourceNum):
		self.source = str(sourceNum)
		self.waveform = 'SINE'
		self.freq = 1000
		self.ampl = 1
		self.state = 'OFF'
		self.offset = 0
		self.phase = 0
		self.duty = 50
예제 #20
0
import time
import socket
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
import scipy.io as sio
import redpitaya_scpi as scpi
import scalib as sca

demodulation = True
plotting = False

rp_addr = '192.168.1.6'
rp_port = 5000
rp_timeout = 5
rp_s = scpi.scpi(rp_addr, timeout=rp_timeout, port=rp_port)
rp_s.tx_txt('ACQ:RST')

# connection info to Arduino
ser_port = 'COM5'
ser_baud = 19200
ser_timeout = 5
ser = serial.Serial(ser_port, ser_baud, timeout=ser_timeout)
s = ser.readline()
print(s.decode())

# projection profiles
filename = '../traces/PP_CPA.mat'
mat_contents = sio.loadmat(filename)
alphas = mat_contents['alphas']
예제 #21
0
import sys
import time
import redpitaya_scpi as scpi

print(sys.argv)
rp_ip = '129.199.115.243'
rp_s = scpi.scpi(rp_ip)

if (len(sys.argv) > 2):
    led = int(sys.argv[2])
else:
    led = 0

print("Blinking LED[" + str(led) + "]")

period = 1  # seconds
time_start = time.time()
while time.time() < time_start + 10:
    time.sleep(period / 2.0)
    rp_s.tx_txt('DIG:PIN LED' + str(led) + ',' + str(1))
    time.sleep(period / 2.0)
    rp_s.tx_txt('DIG:PIN LED' + str(led) + ',' + str(0))
예제 #22
0
# Import needed modules from osc4py3
from osc4py3.as_eventloop import *
from osc4py3 import oscbuildparse

import time
import redpitaya_scpi as scpi

rp_s = scpi.scpi('0')
# clear all leds
for i in range(8):
    rp_s.tx_txt('DIG:PIN LED' + str(i) + ',' + str(0))

# Start the system.
osc_startup()

# Make client channels to send packets.
osc_udp_client("10.0.10.101", 1234, "redpitaya")

# Build a simple message and send it.
msg = oscbuildparse.OSCMessage("/test/me", ",sif", ["text", 672, 8.871])
osc_send(msg, "redpitaya")

# Build a message with autodetection of data types, and send it.
msg = oscbuildparse.OSCMessage("/test/me", None, ["text", 672, 8.871])
osc_send(msg, "redpitaya")

# Buils a complete bundle, and postpone its executions by 10 sec.
# exectime = time.time() + 10   # execute in 10 seconds
msg1 = oscbuildparse.OSCMessage("/sound/levels", None, [1, 5, 3])
# msg2 = oscbuildparse.OSCMessage("/sound/bits", None, [32])
# msg3 = oscbuildparse.OSCMessage("/sound/freq", None, [42000])
 def __init__(self, ip, port=5000, exceptions=[]):
     super(RedPitaya, self).__init__()
     #RedPitaya server implemented in redpitaya_scpi.py (code from RedPitaya docs)
     self.rp_server = scpi.scpi(ip, port=port, exceptions=exceptions)
#!/usr/bin/python

import sys
import redpitaya_scpi as scpi
import matplotlib.pyplot as plot

file = 'Prueba.txt'
Data = open(file, 'w')
Data.close()

if len(sys.argv) > 1:
    print(sys.argv[1])
else:
    IP = '192.168.0.52'  # Red Piyata IP

rp_s = scpi.scpi(IP)

rp_s.tx_txt('ACQ:DEC 1')
rp_s.tx_txt('ACQ:TRIG:LEVEL 30')  # Trigger level 1 Volt

NPulses = 1000  # Number of pulses

for j in range(0, NPulses):

    rp_s.tx_txt('ACQ:START')
    rp_s.tx_txt('ACQ:TRIG EXT_PE')

    while 1:
        rp_s.tx_txt('ACQ:TRIG:STAT?')
        if rp_s.rx_txt() == 'TD':
            break
예제 #25
0
#!/usr/bin/python
"""
Author      Nicolas Peschke
Date        26.07.2019
"""

import redpitaya_scpi as scpi
import time

rp_s = scpi.scpi("10.11.79.149")

for _ in range(100):
    rp_s.tx_txt(f"ANALOG:PIN AOUT0,1.8")
    time.sleep(1)
    rp_s.tx_txt(f"ANALOG:PIN AOUT0,0.1")
    time.sleep(1)
예제 #26
0
https://github.com/RedPitaya/RedPitaya/blob/master/Examples/python/redpitaya_scpi.py)

Device: Redpitaya STEMlab 14bit

"""
import redpitaya_scpi as scpi
import matplotlib.pyplot as plt
import time
import pandas as pd
import os
import sys

plt.close('all')  #close all open plots

try:
    rp_s = scpi.scpi(
        '192.168.158.88')  #IP of redpitaya - IS THE SCPI SERVER RUNNING?
    print('Connected to RedPitaya')
except:
    print('Redpitaya connection NOT successful.')
    print('Redpitaya running? SCPI Server running?.')
    sys.exit('Execution aborted')

#Prep the device. Reset. Acquire buffer size
rp_s.tx_txt('ACQ:RST')
rp_s.tx_txt('ACQ:BUF:SIZE?')
BUFF_SIZE = int(rp_s.rx_txt())
print(BUFF_SIZE)

avg_corr = -0.0215  #Average correction offset - the RP output channel seem to have some offset
""" Waveform input. Can be calculated manually (function). In this case a csv is read. """
#Locate the file with ~16000 values (csv) - Backslash must be forward slash!
        ax3.set_xlabel('Frequency (MHz)', **axis_font)

        if do_piderror_plot:
            fig2 = plt.figure(2, figsize=(22.5 / 2.53, 8. / 2.53))
            fig2.subplots_adjust(left=0.25)
            fig2.subplots_adjust(bottom=0.25)
            fig2.subplots_adjust(top=0.90)
            fig2.subplots_adjust(right=0.95)

            ax21 = fig2.add_subplot(111)
            ax21_hdl, = ax21.plot([], [])
            ax21.set_xlabel('Time (s)', **axis_font)
            ax21.set_ylabel('Pid error (MHz)', **axis_font)

    ###REMOTE CONNECTION
    rp_s = scpi.scpi("10.64.11.12")
    #	rp_s = scpi.scpi("169.254.255.216")

    #	print '###START RECORDING###'
    #	print 'decimation is', decimation,
    #	print 'Nr of runs', num_run
    #	print 'Nr of samples', buff_len
    #	print 'sample_rate_MHz', sample_rate_MHz
    #	print 'sampling distance_ms', delta_time_s_ms

    ###START PID
    ###READ USER INPUT
    newstdin = sys.stdin.fileno()
    reading_process = multiprocessing.Process(target=read_user_input,
                                              args=(newstdin, flag, pid_status,
                                                    show_status, P_pid, I_pid,
예제 #28
0
__author__ = "Luka Golinar <*****@*****.**>"

#Imports
import redpitaya_scpi as scpi
import unittest

#Scpi declaration
rp_scpi = scpi.scpi('192.168.1.241')

#Global variables
rp_dpin_p  = {i: 'DIO'+str(i)+'_P' for i in range(8)}
rp_dpin_n  = {i: 'DIO'+str(i)+'_N' for i in range(8)}
rp_a_pin_o = {i: 'AOUT'+str(i) for i in range(4)}
rp_a_pin_i = {i: 'AIN'+str(i) for i in range(4)}
rp_leds    = {i: 'LED'+str(i) for i in range(8)}

rp_freq_range  = [100, 1000, 10000, 100000, 1e+06, 1e+07, 3e+07]
rp_volt_range  = [0.25, 0.5, 0.75, 1.0]
rp_phase_range = [-360, -180, -90, -30, 30, 90, 180, 360]
rp_offs_range  = [-0.75, -0.5, -0.25, 0.25, 0.5 , 0.75]
rp_dcyc_range  = [0.5, 1, 10, 50, 75, 100]
rp_ncyc_range  = [0, 1, 10, 100, 1000, 10000, 50000]
rp_nor_range   = rp_ncyc_range[:]
rp_inp_range   = [i * 100 for i in range(1, 6)]
rp_channels    = ['CH1', 'CH2', 'MATH']
rp_scales      = [0.5, 1, 2, 3, 10]
rp_decimation  = ['1', '8', '64', '1024', '8192', '65536']
rp_sampling    = ['100', '10000', '100000', '1000000', '10000000', '125000000']
rp_trig_dly    = ['10', '1000', '10000', '16500']
rp_trig_dly_ns = ['10', '100', '250', '500']
import redpitaya_scpi as scpi
import matplotlib.pyplot as plt
import numpy as np
import time
from keras.models import load_model
import tensorflow as tf
from FeatureExtraction import signal_feature
from BlackBox import LED_blinking

#Establishing SCPI connection
rp = scpi.scpi('192.168.128.1')
while 1:
    rp.tx_txt('ACQ:DEC 64')  #DECIMATION FACTOR
    rp.tx_txt('ACQ:TRIG EXT_PE')  #TRIGGER SOURCE
    rp.tx_txt('ACQ:TRIG:DLY 8192')  #DELAY SET
    rp.tx_txt('ACQ:START')  #ACQUISTION START
    while 1:
        rp.tx_txt('ACQ:TRIG:STAT?')  #TRIGGER STATS
        if rp.rx_txt() == 'TD':
            break
    rp.tx_txt('ACQ:SOUR1:DATA?')  #DATA FROM CHANNEL SOURCE1
    stri = rp.rx_txt()[1:-1]
    measRes = np.fromstring(stri, dtype=float, sep=',')
    plt.plot(measRes)  #PLOT THE SIGNAL
    plt.show(block=False)
    time.sleep(5)
    plt.close("all")
    signal = np.array([measRes])
    f = open("Signal.csv", "a")
    np.savetxt(f, signal, fmt='%3.8f', delimiter=',')  #SAVING THE SIGNAL
    f.close()
예제 #30
0
#!/usr/bin/python

import redpitaya_scpi as scpi
import time
import sys

__author__ = "Luka Golinar, Iztok Jeras"
__copyright__ = "Copyright 2015, Red Pitaya"

rp_s = scpi.scpi(sys.argv[1])

time_out = 1#seconds
diode = 5

while 1:
    time.sleep(time_out)
    rp_s.tx_txt(rp_s.choose_state(diode, 1))
    time.sleep(time_out)
    rp_s.tx_txt(rp_s.choose_state(diode, 0))
예제 #31
0
#!/usr/bin/python

import redpitaya_scpi as scpi
import matplotlib.pyplot as plot
import time
import numpy as np

# Variables
ip_adress = '192.168.128.1'
file_path = r'Ergebnisse/Test/Test.csv'
num_of_cycle = 10
buff_array = ''
buff_np = np.zeros((num_of_cycle, 16384), float)

#inizilation trigger
rp_s = scpi.scpi(host=ip_adress)

rp_s.tx_txt('ACQ:DEC 64')
rp_s.tx_txt('ACQ:TRIG:LEVEL -21')
rp_s.tx_txt('ACQ:TRIG:DLY 12192')
rp_s.tx_txt('ACQ:START')
rp_s.tx_txt('ACQ:TRIG EXT_NE')

#wait untill trigger is activated
while 1:
    rp_s.tx_txt('ACQ:TRIG:STAT?')
    if rp_s.rx_txt() == 'TD':

        break
for x in range(num_of_cycle):
    #collecting all 16xxx values and save and convert