Esempio n. 1
0
    def createBuffers(self):

        for i in range(self.blocks):
            # Create buffers ready for assigning pointers for data collection
            self.bufferMaxRay[i] = (ctypes.c_int16 * self.maxsamples)()
            self.bufferMinRay[i] = (ctypes.c_int16 * self.maxsamples)()
            self.bufferAMax = (ctypes.c_int16 * self.maxsamples)()
            self.bufferAMin = (ctypes.c_int16 * self.maxsamples)()

            # Setting the data buffer location for data collection from channel A
            # Handle = Chandle
            self.source = ps.PS5000A_CHANNEL["PS5000A_CHANNEL_A"]
            # Buffer max = ctypes.byref(bufferMaxRay[i])
            # Buffer min = ctypes.byref(bufferMinRay[i])
            # Buffer length = maxsamples
            # Segment index = i
            # Ratio mode = ps5000a_Ratio_Mode_None = 0
            self.status["SetDataBuffers"] = ps.ps5000aSetDataBuffers(
                self.chandle, self.source, ctypes.byref(self.bufferMaxRay[i]),
                ctypes.byref(self.bufferMinRay[i]), self.maxsamples, i, 0)

            assert_pico_ok(self.status["SetDataBuffers"])

        # Creates a overflow location for data
        self.overflow = (ctypes.c_int16 * self.blocks)()
        # Creates converted types maxsamples
        self.cmaxSamples = ctypes.c_int32(self.maxsamples)
Esempio n. 2
0
    def setDatabuffer(self, channelIndex):

        self.bufferMax.append((ctypes.c_int16 * self.maxSamples)())
        self.bufferMin.append((ctypes.c_int16 * self.maxSamples)(
        ))  # used for downsampling which isn't in the scope of this example
        # used for downsampling which isn't in the scope of this example

        # Set data buffer location for data collection from channel A
        # handle = chandle
        self.source = ps.PS5000A_CHANNEL["PS5000A_CHANNEL_{0}".format(
            self.channels[channelIndex])]
        # pointer to buffer max = ctypes.byref(bufferAMax)
        # pointer to buffer min = ctypes.byref(bufferAMin)
        # buffer length = maxSamples
        # segment index = 0
        # ratio mode = PS5000A_RATIO_MODE_NONE = 0
        self.status["setDataBuffers{0}".format(
            self.channels[channelIndex])] = ps.ps5000aSetDataBuffers(
                self.chandle, self.source,
                ctypes.byref(self.bufferMax[channelIndex]),
                ctypes.byref(self.bufferMin[channelIndex]), self.maxSamples, 0,
                0)
        assert_pico_ok(self.status["setDataBuffers{0}".format(
            self.channels[channelIndex])])
        self.returnData = np.zeros((self.numberOfChannels, self.maxSamples))
    def retrieveCaptureData(self, channels):
        segment_index = 0
        ratio_move = 0  #PS5000A_RATIO_MODE_NONE
        if self.channela in channels:
            self.status["setDataBuffersA"] = ps.ps5000aSetDataBuffers(
                self.chandle, self.channela, ctypes.byref(self.bufferAMax),
                ctypes.byref(self.bufferAMin), self.totalSamples,
                segment_index, ratio_move)
            assert_pico_ok(self.status["setDataBuffersA"])
        if self.channelb in channels:
            self.status["setDataBuffersB"] = ps.ps5000aSetDataBuffers(
                self.chandle, self.channelb, ctypes.byref(self.bufferBMax),
                ctypes.byref(self.bufferBMin), self.totalSamples,
                segment_index, ratio_move)
            assert_pico_ok(self.status["setDataBuffersB"])
        if len(channels) < 1 or (self.channela not in channels
                                 and self.channelb not in channels):
            raise ValueError("Missing or unrecognised channel(s) requested")

        # create overflow loaction
        overflow = ctypes.c_int16()
        # create converted type maxSamples
        cmaxSamples = ctypes.c_int32(self.totalSamples)

        # Retried data from scope to buffers assigned above
        start_index = 0
        downsample_ratio = 0
        downsample_mode = 0  #PS5000A_RATIO_MODE_NONE
        segment_index = 0
        self.status["getValues"] = ps.ps5000aGetValues(
            self.chandle, start_index, ctypes.byref(cmaxSamples),
            downsample_ratio, downsample_mode, segment_index,
            ctypes.byref(overflow))
        assert_pico_ok(self.status["getValues"])

        # convert ADC counts data to mV
        adc2mVMaxChA, adc2mVMaxChB = None, None
        if self.channela in channels:
            adc2mVMaxChA = adc2mV(self.bufferAMax, self.channela_range,
                                  self.maxADC)
        if self.channelb in channels:
            adc2mVMaxChB = adc2mV(self.bufferBMax, self.channelb_range,
                                  self.maxADC)

        return [adc2mVMaxChA, adc2mVMaxChB]
 def _setDataBuffers(self,**kwargs):
     '''
     sets the data reduction method.
     arguments: none
     keyword arguments (defaults in channel.settings):
     reduction_mode:     'none':          no data reduction,
                         'aggregate':     min and max over block,
                         'decimate':      just the first value in the block
                         'average':       average over block
     segmentIndex: the segment to read (mostly useful for rapidBlock)
     '''
     settings = {} #in case of failure, settings is updated only at the end
     settings['segmentIndex'] = self.scope.settings['segmentIndex'] #default value
     for key,current_value in self.settings.items():
         settings[key] = kwargs[key] if key in kwargs else current_value
     
     #checks
     check_kwargs_scope(**kwargs)
     
     maxSamples = self.scope.settings['noSamples']
     # Create buffers ready for assigning pointers for data collection
     _ratio_mode = ratio_mode_index[settings['reduction_mode']]
     self._bufferMax = [(ctypes.c_int16 * maxSamples)() for i in range(self.scope.trigger.settings['nSegments'])]
     self._bufferMin = [(ctypes.c_int16 * maxSamples)() for i in range(self.scope.trigger.settings['nSegments'])] # used for downsampling which isn't in the scope of this example
     for _bufferMax,_bufferMin,i in zip(self._bufferMax,self._bufferMin,range(self.scope.trigger.settings['nSegments'])):
         # Set data buffer location for data collection from channel
         # handle = chandle
         #source = ps.PS5000A_CHANNEL["PS5000A_CHANNEL_A"]
         # pointer to buffer max = ctypes.byref(bufferMax)
         # pointer to buffer min = ctypes.byref(bufferMin)
         # buffer length = maxSamples
         # segment index = 0
         # ratio mode = PS5000A_RATIO_MODE_NONE = 0
         self.status["setDataBuffers"] = ps.ps5000aSetDataBuffers(self.chandle, self._source, 
                                                                  ctypes.byref(_bufferMax), ctypes.byref(_bufferMin), 
                                                                  maxSamples, settings['segmentIndex']+i, _ratio_mode)
         assert_pico_ok(self.status["setDataBuffers"])
     self.settings = settings
Esempio n. 5
0
# Create buffers ready for assigning pointers for data collection
bufferDPort0Max = (ctypes.c_int16 * totalSamples)()
bufferDPort0Min = (ctypes.c_int16 * totalSamples)()

# Set the data buffer location for data collection from ps5000a_DIGITAL_PORT0
# handle = chandle
# source = ps5000a_DIGITAL_PORT0 = 0x80
# Buffer max = ctypes.byref(bufferDPort0Max)
# Buffer min = ctypes.byref(bufferDPort0Min)
# Buffer length = totalSamples
# Segment index = 0
# Ratio mode = ps5000a_RATIO_MODE_NONE = 0
status["SetDataBuffers"] = ps.ps5000aSetDataBuffers(chandle,
                                                    0x80,
                                                    ctypes.byref(bufferDPort0Max),
                                                    ctypes.byref(bufferDPort0Min),
                                                    totalSamples,
                                                    0,
                                                    0)
assert_pico_ok(status["SetDataBuffers"])

print ("Starting data collection...")

# Starts the block capture
# handle = chandle
# Number of preTriggerSamples
# Number of postTriggerSamples
# Timebase = 1252 = 10000 ns (see Programmer's guide for more information on timebases)
# time indisposed ms = None (This is not needed within the example)
# Segment index = 0
# LpRead = None
status["runblock"] = ps.ps5000aRunBlock(chandle, preTriggerSamples, postTriggerSamples, timebase, None, 0, None, None)
assert_pico_ok(status["runblock"])

# Create buffers ready for assigning pointers for data collection
bufferAMax = (ctypes.c_int16 * maxsamples)()
bufferAMin = (ctypes.c_int16 * maxsamples)() # used for downsampling which isn't in the scope of this example

# Setting the data buffer location for data collection from channel A
# Handle = Chandle
source = ps.PS5000A_CHANNEL["PS5000A_CHANNEL_A"]
# Buffer max = ctypes.byref(bufferAMax)
# Buffer min = ctypes.byref(bufferAMin)
# Buffer length = maxsamples
# Segment index = 0
# Ratio mode = ps5000a_Ratio_Mode_None = 0
status["SetDataBuffers"] = ps.ps5000aSetDataBuffers(chandle, source, ctypes.byref(bufferAMax), ctypes.byref(bufferAMin), maxsamples, 0, 0)
assert_pico_ok(status["SetDataBuffers"])

# Create buffers ready for assigning pointers for data collection
bufferAMax1 = (ctypes.c_int16 * maxsamples)()
bufferAMin1 = (ctypes.c_int16 * maxsamples)() # used for downsampling which isn't in the scope of this example

# Setting the data buffer location for data collection from channel A
# Handle = Chandle
# source = ps.PS5000A_CHANNEL["ps5000a_channel_A"]
# Buffer max = ctypes.byref(bufferAMax)
# Buffer min = ctypes.byref(bufferAMin)
# Buffer length = maxsamples
# Segment index = 1
# Ratio mode = ps5000a_Ratio_Mode_None = 0
status["SetDataBuffers"] = ps.ps5000aSetDataBuffers(chandle, source, ctypes.byref(bufferAMax1), ctypes.byref(bufferAMin1), maxsamples, 1, 0)
bufferAMin = (ctypes.c_int16 * maxSamples)(
)  # used for downsampling which isn't in the scope of this example
bufferBMax = (ctypes.c_int16 * maxSamples)()
bufferBMin = (ctypes.c_int16 * maxSamples)(
)  # used for downsampling which isn't in the scope of this example

# Set data buffer location for data collection from channel A
# handle = chandle
source = ps.PS5000A_CHANNEL["PS5000A_CHANNEL_A"]
# pointer to buffer max = ctypes.byref(bufferAMax)
# pointer to buffer min = ctypes.byref(bufferAMin)
# buffer length = maxSamples
# segment index = 0
# ratio mode = PS5000A_RATIO_MODE_NONE = 0
status["setDataBuffersA"] = ps.ps5000aSetDataBuffers(chandle, source,
                                                     ctypes.byref(bufferAMax),
                                                     ctypes.byref(bufferAMin),
                                                     maxSamples, 0, 0)
assert_pico_ok(status["setDataBuffersA"])

# Set data buffer location for data collection from channel B
# handle = chandle
source = ps.PS5000A_CHANNEL["PS5000A_CHANNEL_B"]
# pointer to buffer max = ctypes.byref(bufferBMax)
# pointer to buffer min = ctypes.byref(bufferBMin)
# buffer length = maxSamples
# segment index = 0
# ratio mode = PS5000A_RATIO_MODE_NONE = 0
status["setDataBuffersB"] = ps.ps5000aSetDataBuffers(chandle, source,
                                                     ctypes.byref(bufferBMax),
                                                     ctypes.byref(bufferBMin),
                                                     maxSamples, 0, 0)
bufferAMax = np.zeros(shape=sizeOfOneBuffer, dtype=np.int16)
bufferBMax = np.zeros(shape=sizeOfOneBuffer, dtype=np.int16)

memory_segment = 0

# Set data buffer location for data collection from channel A
# handle = chandle
# source = PS5000A_CHANNEL_A = 0
# pointer to buffer max = ctypes.byref(bufferAMax)
# pointer to buffer min = ctypes.byref(bufferAMin)
# buffer length = maxSamples
# segment index = 0
# ratio mode = PS5000A_RATIO_MODE_NONE = 0
status["setDataBuffersA"] = ps.ps5000aSetDataBuffers(
    chandle, ps.PS5000A_CHANNEL['PS5000A_CHANNEL_A'],
    bufferAMax.ctypes.data_as(ctypes.POINTER(ctypes.c_int16)), None,
    sizeOfOneBuffer, memory_segment,
    ps.PS5000A_RATIO_MODE['PS5000A_RATIO_MODE_NONE'])
assert_pico_ok(status["setDataBuffersA"])

# Set data buffer location for data collection from channel B
# handle = chandle
# source = PS5000A_CHANNEL_B = 1
# pointer to buffer max = ctypes.byref(bufferBMax)
# pointer to buffer min = ctypes.byref(bufferBMin)
# buffer length = maxSamples
# segment index = 0
# ratio mode = PS5000A_RATIO_MODE_NONE = 0
status["setDataBuffersB"] = ps.ps5000aSetDataBuffers(
    chandle, ps.PS5000A_CHANNEL['PS5000A_CHANNEL_B'],
    bufferBMax.ctypes.data_as(ctypes.POINTER(ctypes.c_int16)), None,
Esempio n. 9
0
 def set_buffer(self, channel, channelID, buffer, Samples):
     self.status["setDataBuffers{}".format(channel)] = ps.ps5000aSetDataBuffers(self.chandle, channelID, ctypes.byref(buffer['Max']), ctypes.byref(buffer['Min']), Samples, 0, 0)
Esempio n. 10
0
class BuildModel_M3_Single(object):
    if __name__ == "__main__":
        # Serial port communication: look this up in 'device manager'
        port = '/dev/ttyUSB0'  # Serial port
        step = 1000
        # Number of traces
        N = 5000 * 23
        # Number of samples
        samples = 1000
        # 2ns, sampling rate= 500MSa/s(p22 2.7 Timebase)
        timebase = 1
        # post-trigger or before-trigger
        post_trigger = True
        # trigger threshold(mV)
        threshold = 2000
        # trigger direction
        posedge_trigger = True
        # vertical offset
        vertical_offset = 0.1
        #delay
        delay = 0
        plain_len = 32  # byte length of the plaintext
        cipher_len = 32  # byte length of the ciphertext

        # Intiliazed random generator
        random.seed()
        # Open serial port
        ser = serial.Serial(port)
        # Wait for 200ms
        time.sleep(0.2)
        if (post_trigger):
            preTriggerSamples = 0
            postTriggerSamples = samples
        else:
            preTriggerSamples = samples
            postTriggerSamples = 0

            # Connect the scope
        chandle = ctypes.c_int16()
        status = ps.ps5000aOpenUnit(
            ctypes.byref(chandle), None,
            ps.PS5000A_DEVICE_RESOLUTION["PS5000A_DR_8BIT"])
        if status != PICO_STATUS['PICO_OK']:
            raise PicoSDKCtypesError("PicoSDK returned '{}'".format(
                PICO_STATUS_LOOKUP[status]))
        # Set up channel A
        status = ps.ps5000aSetChannel(chandle, ps.PICO_CHANNEL["A"], 1,
                                      ps.PICO_COUPLING['DC'],
                                      ps.PS5000A_RANGE["PS5000A_1V"],
                                      vertical_offset)
        if status != PICO_STATUS['PICO_OK']:
            raise PicoSDKCtypesError("PicoSDK returned '{}'".format(
                PICO_STATUS_LOOKUP[status]))
        # Set up channel B
        status = ps.ps5000aSetChannel(chandle, ps.PICO_CHANNEL["B"], 1,
                                      ps.PICO_COUPLING['DC'],
                                      ps.PS5000A_RANGE["PS5000A_5V"], 0)
        if status != PICO_STATUS['PICO_OK']:
            raise PicoSDKCtypesError("PicoSDK returned '{}'".format(
                PICO_STATUS_LOOKUP[status]))
        # Set up trigger
        if (posedge_trigger):
            status = ps.ps5000aSetSimpleTrigger(
                chandle, 1, ps.PICO_CHANNEL["B"],
                mV2adc(threshold, ps.PS5000A_RANGE["PS5000A_5V"],
                       ctypes.c_int16(32512)),
                ps.PS5000A_THRESHOLD_DIRECTION["PS5000A_RISING"], delay, 0)
        else:
            status = ps.ps5000aSetSimpleTrigger(
                chandle, 1, ps.PICO_CHANNEL["B"],
                mV2adc(threshold, ps.PS5000A_RANGE["PS5000A_5V"],
                       ctypes.c_int16(32512)),
                ps.PS5000A_THRESHOLD_DIRECTION["PS5000A_FALLING"], delay, 0)
        if status != PICO_STATUS['PICO_OK']:
            raise PicoSDKCtypesError("PicoSDK returned '{}'".format(
                PICO_STATUS_LOOKUP[status]))

        # Create buffers ready for assigning pointers for data collection
        Databuffer = (ctypes.c_int16 * samples)()
        status = ps.ps5000aSetDataBuffers(chandle, 0, ctypes.byref(Databuffer),
                                          None, samples, 0, 0)
        if status != PICO_STATUS['PICO_OK']:
            raise PicoSDKCtypesError("PicoSDK returned '{}'".format(
                PICO_STATUS_LOOKUP[status]))

        trs = TRS_TraceSet.TRS_TraceSet("BuildModel_M3_Single_1000Samples.trs")
        trs.write_header(N, samples, True, plain_len + cipher_len, 2E-9,
                         1 / 65536)
        for i in range(0, N):
            # Generate plaintext & mask
            plaintext = bytearray(
                [secrets.randbits(8) for j in range(0, plain_len)])
            plaintext[28] = int(i / 5000) + 1
            # Start
            status = ps.ps5000aRunBlock(chandle, preTriggerSamples,
                                        postTriggerSamples, timebase, None, 0,
                                        None, None)
            if status != PICO_STATUS['PICO_OK']:
                raise PicoSDKCtypesError("PicoSDK returned '{}'".format(
                    PICO_STATUS_LOOKUP[status]))
            # Send plaintext
            ser.write(plaintext)
            # Read out ciphertext
            ciphertext = bytearray(ser.read(cipher_len))
            # Check for data collection to finish using ps5000aIsReady
            ready = ctypes.c_int16(0)
            check = ctypes.c_int16(0)
            while ready.value == check.value:
                status = ps.ps5000aIsReady(chandle, ctypes.byref(ready))
            # Create overflow location
            overflow = ctypes.c_int16()
            # create converted type totalSamples
            cTotalSamples = ctypes.c_int32(samples)
            # Retried data from scope to buffers assigned above
            status = ps.ps5000aGetValues(chandle, 0,
                                         ctypes.byref(cTotalSamples), 0, 0, 0,
                                         ctypes.byref(overflow))
            if status != PICO_STATUS['PICO_OK']:
                raise PicoSDKCtypesError("PicoSDK returned '{}'".format(
                    PICO_STATUS_LOOKUP[status]))
            if (overflow.value != 0):
                print("overflow!")
            # Write trace
            trs.write_trace(plaintext, ciphertext, np.array(Databuffer), True)
            # print to screen
            if i % step == 0 and i > 0:
                print("i=" + str(i))
                print("Instr=" + str(plaintext[28]))
                print("plain=")
                PrintHexData(plaintext)
                print("cipher=")
                PrintHexData(ciphertext)
        trs.close()
Esempio n. 11
0
    def setupStreaming(self, sizeOfOneBuffer, numBuffersToCapture,
                       sampleInterval):
        # Size of capture

        self.sampleInterval = ctypes.c_int32(sampleInterval)

        totalSamples = sizeOfOneBuffer * numBuffersToCapture

        # Create buffers ready for assigning pointers for data collection

        bufferAMax = np.zeros(shape=sizeOfOneBuffer, dtype=np.int16)

        memory_segment = 0

        # Set data buffer location for data collection from channel A
        # handle = chandle
        # source = PS5000A_CHANNEL_A = 0
        # pointer to buffer max = ctypes.byref(bufferAMax)
        # pointer to buffer min = ctypes.byref(bufferAMin)
        # buffer length = maxSamples
        # segment index = 0
        # ratio mode = PS5000A_RATIO_MODE_NONE = 0
        self.status["setDataBuffersA"] = ps.ps5000aSetDataBuffers(
            self.chandle, ps.PS5000A_CHANNEL['PS5000A_CHANNEL_A'],
            bufferAMax.ctypes.data_as(ctypes.POINTER(ctypes.c_int16)), None,
            sizeOfOneBuffer, memory_segment,
            ps.PS5000A_RATIO_MODE['PS5000A_RATIO_MODE_AVERAGE'])
        assert_pico_ok(self.status["setDataBuffersA"])

        # Set data buffer location for data collection from channel B
        # handle = chandle
        # source = PS5000A_CHANNEL_B = 1
        # pointer to buffer max = ctypes.byref(bufferBMax)
        # pointer to buffer min = ctypes.byref(bufferBMin)
        # buffer length = maxSamples
        # segment index = 0
        # ratio mode = PS5000A_RATIO_MODE_NONE = 0

        # Begin streaming mode:
        self.sampleInterval = ctypes.c_int32(sampleInterval)
        self.sampleUnits = ps.PS5000A_TIME_UNITS['PS5000A_NS']

        # We are not triggering:
        self.maxPreTriggerSamples = 0
        self.autoStopOn = 1

        # No downsampling:
        self.downsampleRatio = 1

        # Find maximum ADC count value
        # handle = chandle
        # pointer to value = ctypes.byref(maxADC)
        self.status["maximumValue"] = ps.ps5000aMaximumValue(
            self.chandle, ctypes.byref(self.maxADC))
        assert_pico_ok(self.status["maximumValue"])

        self.status["runStreaming"] = ps.ps5000aRunStreaming(
            self.chandle, ctypes.byref(self.sampleInterval), self.sampleUnits,
            self.maxPreTriggerSamples, totalSamples, self.autoStopOn,
            self.downsampleRatio,
            ps.PS5000A_RATIO_MODE['PS5000A_RATIO_MODE_AVERAGE'],
            sizeOfOneBuffer)
        assert_pico_ok(self.status["runStreaming"])

        actualSampleInterval = self.sampleInterval.value

        print("Capturing at sample interval %s ns" % actualSampleInterval)

        # We need a big buffer, not registered with the driver, to keep our complete capture in.
        time = np.linspace(0, sizeOfOneBuffer * actualSampleInterval,
                           sizeOfOneBuffer)
        buffer = np.zeros(shape=sizeOfOneBuffer, dtype=np.int16)
        bufferCompleteA = np.zeros(shape=totalSamples, dtype=np.int16)
        global nextSample
        nextSample = 0
        autoStopOuter = False
        wasCalledBack = False

        def streaming_callback(handle, noOfSamples, startIndex, overflow,
                               triggerAt, triggered, autoStop, param):
            print(t.time())
            global nextSample, autoStopOuter, wasCalledBack, startTime
            wasCalledBack = True
            destEnd = nextSample + noOfSamples
            sourceEnd = startIndex + noOfSamples
            buffer = bufferAMax[startIndex:sourceEnd]

            bufferCompleteA[nextSample:destEnd] = buffer
            time = np.linspace(0,
                               len(buffer) * actualSampleInterval, len(buffer))

            # Convert ADC counts data to mV
            adc2mVChAMax = np.asarray(
                buffer, dtype=int) * self.channel_range / self.maxADC.value

            if t.time() - startTime > .016:
                plt.plot(time, adc2mVChAMax, clear=True)
                pg.QtGui.QApplication.processEvents()
                startTime = t.time()

            # print(noOfSamples)
            nextSample += noOfSamples
            if autoStop:
                autoStopOuter = True

        # Convert the python function into a C function pointer.
        cFuncPtr = ps.StreamingReadyType(streaming_callback)

        # Fetch data from the driver in a loop, copying it out of the registered buffers and into our complete one.

        startTime = t.time()
        while nextSample < totalSamples and not autoStopOuter:
            wasCalledBack = False
            self.status[
                "getStreamingLastestValues"] = ps.ps5000aGetStreamingLatestValues(
                    self.chandle, cFuncPtr, None)