def testConnectBehavior(self): ####################################################################### # Make sure start and stop can be called without throwing exceptions alloc=frontend.createTunerAllocation() snk_1 = sb.StreamSink() snk_2 = sb.StreamSink() self.comp.allocateCapacity(alloc) self.comp.connect(snk_1, connectionId='some_connection') tuner_status = self.comp.frontend_tuner_status[0] alloc_id = alloc['FRONTEND::tuner_allocation']['FRONTEND::tuner_allocation::allocation_id'] self.assertEquals(tuner_status.allocation_id_csv, alloc_id) self.comp.connect(snk_2) self.assertEquals(len(self.comp.connectionTable), 2) alloc_id = alloc_id + ',' + self.comp.connectionTable[1].connection_id self.assertEquals(tuner_status.allocation_id_csv, alloc_id) sb.start() time.sleep(0.1) time.sleep(0.25) self.comp.deallocateCapacity(alloc) time.sleep(0.1) data_1 = snk_1.read(timeout=1) self.assertEquals(data_1, None) data_2 = snk_2.read(timeout=1) self.assertEquals(data_2.streamID, 'my_data') self.assertEquals(len(data_2.data), 25) self.assertEquals(len(self.comp.connectionTable), 0) sb.stop()
def testFloatPort(self): ####################################################################### # Test FLOAT Functionality print "\n**TESTING FLOAT PORT" # Define test files dataFileIn = "./data.in" dataFileOut = "./data.out" # Create Test Data File if it doesn't exist if not os.path.isfile(dataFileIn): with open(dataFileIn, "wb") as dataIn: dataIn.write(os.urandom(1024)) # Read in Data from Test File size = os.path.getsize(dataFileIn) with open(dataFileIn, "rb") as dataIn: data = list(struct.unpack("f" * (size / 4), dataIn.read(size))) # Create Components and Connections comp = sb.launch("../FileWriter.spd.xml") comp.destination_uri = dataFileOut comp.advanced_properties.existing_file = "TRUNCATE" source = sb.DataSource(bytesPerPush=64, dataFormat="32f") source.connect(comp, providesPortName="dataFloat_in") # Start Components & Push Data sb.start() source.push(data) time.sleep(2) sb.stop() # Check that the input and output files are the same try: self.assertEqual(filecmp.cmp(dataFileIn, dataFileOut), True) except self.failureException as e: # unpacked bytes may be NaN, which could cause test to fail unnecessarily size = os.path.getsize(dataFileOut) with open(dataFileOut, "rb") as dataOut: data2 = list(struct.unpack("f" * (size / 4), dataOut.read(size))) for a, b in zip(data, data2): if a != b: if a != a and b != b: print "Difference in NaN format, ignoring..." else: print "FAILED:", a, "!=", b raise e # Release the components and remove the generated files finally: comp.releaseObject() source.releaseObject() os.remove(dataFileIn) os.remove(dataFileOut) print "........ PASSED\n" return
def tearDown(self): ####################################################################### # Simulate regular resource shutdown self.comp.releaseObject() self.comp.stop() sb.reset() sb.stop() ossie.utils.testing.ScaComponentTestCase.tearDown(self)
def tearDown(self): ####################################################################### # Simulate regular resource shutdown self.comp.releaseObject() self.comp.stop() sb.reset() sb.stop() ossie.utils.testing.ScaComponentTestCase.tearDown(self);
def testDoublePort(self): ####################################################################### # Test DOUBLE Functionality print "\n**TESTING DOUBLE PORT" #Define test files dataFileIn = './data.in' #Create Test Data File if it doesn't exist #Floats and Doubles are a special case, as #NaNs can be generated randomly and will #not equal one another if not os.path.isfile(dataFileIn): with open(dataFileIn, 'wb') as dataIn: for i in range(1024 / 8): doubleNum = struct.unpack('d', os.urandom(8))[0] while isnan(doubleNum): doubleNum = struct.unpack('d', os.urandom(8))[0] dataIn.write(struct.pack('d', doubleNum)) #Read in Data from Test File size = os.path.getsize(dataFileIn) with open(dataFileIn, 'rb') as dataIn: data = list(struct.unpack('d' * (size / 8), dataIn.read(size))) #Create Components and Connections comp = sb.launch('../FileReader.spd.xml') comp.source_uri = dataFileIn comp.file_format = 'DOUBLE' sink = sb.DataSink() comp.connect(sink, usesPortName='dataDouble_out') #Start Components & Push Data sb.start() comp.playback_state = 'PLAY' time.sleep(2) readData = sink.getData() sb.stop() #Check that the input and output files are the same try: self.assertEqual(data, readData) except self.failureException as e: comp.releaseObject() sink.releaseObject() os.remove(dataFileIn) raise e #Release the components and remove the generated files comp.releaseObject() sink.releaseObject() os.remove(dataFileIn) print "........ PASSED\n" return
def tearDown(self): """ Stops unit test - run after every method that starts with test """ ####################################################################### # Simulate regular resource shutdown self.comp.releaseObject() # stops everything self.comp.stop() sb.reset() sb.stop() ossie.utils.testing.ScaComponentTestCase.tearDown(self)
def test_vector(self): dsource=sb.DataSource() dsink=sb.DataSink() test_comp=sb.Component(self.cname) data=range(100) dsource.connect(test_comp, providesPortName=self.inport ) test_comp.connect(dsink, providesPortName=self.sink_port_name, usesPortName=self.outport) sb.start() dsource.push(data,EOS=True) dest_data=dsink.getData(eos_block=True) sb.stop() self.assertEqual(data, dest_data)
def run(self): print 'starting benchmark' sb.start() #first sample recorded should be a couple away from the start of BenchmarkGen #due to the high output rate to fill up the queue lastTP = self.bc.packets_per_time_avg*self.samplesAway #loop counter loopCount = 0 #run until less than 1% while 1: timer = 0 #run until time for benchmark runs out while timer <= self.bmTime: #run until next value can be collected while self.bc.totalPackets <= lastTP: sleep(.1) timer = timer + .1; #collect data from benchmark component self.samples.append(float(timer + loopCount*self.bmTime)) self.outputRates.append(float(self.bc.avg_output_rate)) self.times.append(float(self.bc.time)) lastTP = lastTP + self.bc.packets_per_time_avg #calculating statistics N = len(self.samples) s = numpy.std(self.outputRates) x = numpy.mean(self.outputRates) value = 1.96*(s/numpy.sqrt(N)) lower = x - value upper = x + value percent = (value / x) * 100 #debug if self.debug==1: print 'N is: ' + str(int(N)) print 's is: ' + str(float(s)) print 'x is: ' + str(float(x)) print 'value is: ' + str(float(value)) print '95% confidence level: ' + str(float(lower)) + ' - ' + str(float(upper)) print 'percent away is: ' + str(float(percent)) loopCount = loopCount + 1 if(percent <= 1): break; self.printStats() if self.showPlot==1: self.plot() sb.reset() sb.stop()
def testCharPort(self): ####################################################################### # Test Char Functionality print "\n**TESTING CHAR PORT" # Define test files dataFileIn = "./data.in" dataFileOut = "./data.out" # Create Test Data File if it doesn't exist if not os.path.isfile(dataFileIn): with open(dataFileIn, "wb") as dataIn: dataIn.write(os.urandom(1024)) # Read in Data from Test File size = os.path.getsize(dataFileIn) with open(dataFileIn, "rb") as dataIn: data = list(struct.unpack("b" * size, dataIn.read(size))) # Create Components and Connections comp = sb.launch("../FileWriter.spd.xml") comp.destination_uri = dataFileOut comp.advanced_properties.existing_file = "TRUNCATE" source = sb.DataSource(bytesPerPush=64, dataFormat="8t") source.connect(comp, providesPortName="dataChar_in") # Start Components & Push Data sb.start() source.push(data) time.sleep(2) sb.stop() # Check that the input and output files are the same try: self.assertEqual(filecmp.cmp(dataFileIn, dataFileOut), True) except self.failureException as e: comp.releaseObject() source.releaseObject() os.remove(dataFileIn) os.remove(dataFileOut) raise e # Release the components and remove the generated files comp.releaseObject() source.releaseObject() os.remove(dataFileIn) os.remove(dataFileOut) print "........ PASSED\n" return
def ntestUShortPort(self): ####################################################################### # Test USHORT Functionality print "\n**TESTING USHORT PORT" #Define test files dataFileIn = './data.in' #Create Test Data File if it doesn't exist if not os.path.isfile(dataFileIn): with open(dataFileIn, 'wb') as dataIn: dataIn.write(os.urandom(1024)) #Read in Data from Test File size = os.path.getsize(dataFileIn) with open(dataFileIn, 'rb') as dataIn: data = list(struct.unpack('H' * (size / 2), dataIn.read(size))) #Create Components and Connections comp = sb.launch('../FileReader.spd.xml') comp.source_uri = dataFileIn comp.file_format = 'USHORT' sink = sb.DataSink() comp.connect(sink, usesPortName='dataUshort_out') #Start Components & Push Data sb.start() comp.playback_state = 'PLAY' time.sleep(2) readData = sink.getData() sb.stop() #Check that the input and output files are the same try: self.assertEqual(data, readData) except self.failureException as e: comp.releaseObject() sink.releaseObject() os.remove(dataFileIn) raise e #Release the components and remove the generated files comp.releaseObject() sink.releaseObject() os.remove(dataFileIn) print "........ PASSED\n" return
def testBPSOverride(self): self.source = sb.StreamSource(self.id(), 'octet') self.source.connect(self.comp, usesPortName='octetOut') self.comp.override_sdds_header.enabled = True for bps in range(32): time.sleep(0.1) self.comp.override_sdds_header.bps = bps sb.start() fakeData = 1024 * [1] self.source.write(fakeData) rcv = self.getPacket() sdds_header = self.getHeader(rcv) self.assertEqual(bps, sum(sdds_header.bps), "Received BPS that did not match expected") sb.stop()
def addRTL(self): listOfRTL = [] # determine which rtl is new for myDev in [self.dom.devices][0]: if myDev.name == "rtl_sdr_device": listOfRTL.append(myDev) for rtl in listOfRTL: if rtl._get_identifier() not in self.rtl_list: rtlObject = rtl #break # populate gui newBox = gtk.HBox(False, 0) rtlBox = gtk.VBox(False, 0) rtlBox = self.addLabel(rtlBox, "RTL " + str(len(self.rtl_list))) rtlBox, rtl_freq = self.addDouble(rtlBox, "Frequency: ", 10, "462637500") rtlBox, rtl_samp = self.addDouble(rtlBox, "Sample Rate: ", 5, "200") newBox.pack_start(rtlBox) self.table.attach(newBox, len(self.rtl_list)+1, len(self.rtl_list)+2, 0, 1) self.window.show_all() sb.stop() redhawk.Device myDemod = sb.launch("AmFmPmBasebandDemod") #plot = sb.LinePSD() rtlObject.connect(myDemod) #myDemod.connect(plot, usesPortName="fm_dataFloat_out") sb.start() sb.show() self.box_list.append(newBox) self.rtl_list.append(rtlObject._get_identifier()) self.demod_list.append(myDemod) self.freq_list.append(rtl_freq) self.samp_list.append(rtl_samp)
def testCxOverride(self): self.octetConnect() self.comp.override_sdds_header.enabled = True for cx in range(2): time.sleep(0.1) self.comp.override_sdds_header.cx = cx sb.start() fakeData = 1024 * [1] self.source.push(fakeData, EOS=False, streamID=self.id(), sampleRate=1.0, complexData=False, loop=False) rcv = self.getPacket() self.assertEqual(self.getCx(rcv), cx, "Received CX that did not match expected") sb.stop()
def testStandardFormat(self): self.octetConnect() for sf in range(2): time.sleep(0.1) self.comp.sdds_settings.standard_format = sf sb.start() fakeData = 1024 * [1] self.source.push(fakeData, EOS=False, streamID=self.id(), sampleRate=1.0, complexData=False, loop=False) rcv = self.getPacket() sdds_header = self.getHeader(rcv) self.assertEqual(sdds_header.SF, sf, "Received SF that did not match expected") sb.stop()
def testSpectralSense(self): self.octetConnect() for ss in range(2): time.sleep(0.1) self.comp.sdds_settings.spectral_sense = ss sb.start() fakeData = 1024 * [1] self.source.push(fakeData, EOS=False, streamID=self.id(), sampleRate=1.0, complexData=False, loop=False) rcv = self.getPacket() sdds_header = self.getHeader(rcv) self.assertEqual(sdds_header.SS, ss, "Received SS that did not match expected") sb.stop()
def testXmlPort(self): ####################################################################### # Test XML Functionality print "\n**TESTING XML PORT" dataFileIn = './data.xml' with open(dataFileIn, 'rb') as file: data = file.read() #Set up FileReader comp = sb.launch('../FileReader.spd.xml') comp.source_uri = dataFileIn comp.file_format = 'XML' sink = sb.DataSink() comp.connect(sink, usesPortName='dataXML_out') #Start Components & Push Data sb.start() comp.playback_state = 'PLAY' time.sleep(2) readData = sink.getData() sb.stop() #Convert list of strings into a string readData = readData[0] #Check that the input and output files are the same try: self.assertEqual(data, readData) except self.failureException as e: comp.releaseObject() sink.releaseObject() raise e #Release the components and remove the generated files comp.releaseObject() sink.releaseObject() print "........ PASSED\n" return
def testOriginalFormat(self): self.octetConnect() sink = sb.DataSinkSDDS() for of in range(2): time.sleep(0.1) self.comp.sdds_settings.original_format = of sb.start() fakeData = 1024 * [1] self.source.push(fakeData, EOS=False, streamID=self.id(), sampleRate=1.0, complexData=False, loop=False) rcv = self.getPacket() sdds_header = self.getHeader(rcv) self.assertEqual(sdds_header.OF, of, "Received OF that did not match expected") sb.stop()
def testFrequencyOverride(self): self.octetConnect() self.comp.override_sdds_header.enabled = True for freq in [x * .1 for x in range(10)]: time.sleep(0.1) self.comp.override_sdds_header.frequency = freq sb.start() fakeData = 1024 * [1] self.source.push(fakeData, EOS=False, streamID=self.id(), sampleRate=1.0, complexData=False, loop=False) rcv = self.getPacket() sdds_header = self.getHeader(rcv) self.assertEqual(sdds_header.freq, int(73786976294.838211 * freq), "Received freq that did not match expected") sb.stop()
def testDfdtOverride(self): self.octetConnect() self.comp.override_sdds_header.enabled = True for dfdt in [x * .1 for x in range(10)]: time.sleep(0.1) self.comp.override_sdds_header.dfdt = dfdt sb.start() fakeData = 1024 * [1] self.source.push(fakeData, EOS=False, streamID=self.id(), sampleRate=1.0, complexData=False, loop=False) rcv = self.getPacket() sdds_header = self.getHeader(rcv) self.assertEqual(sdds_header.dfdt, int(1073741824 * dfdt), "Received MSdelta that did not match expected") sb.stop()
def testXmlPort(self): ####################################################################### # Test XML Functionality print "\n**TESTING XML PORT" # Create Test Data dataFileOut = "./data.out" with open("data.xml", "rb") as file: inputData = file.read() # Connect DataSource to FileWriter comp = sb.launch("../FileWriter.spd.xml") comp.destination_uri = dataFileOut comp.advanced_properties.existing_file = "TRUNCATE" source = sb.DataSource(bytesPerPush=64, dataFormat="xml") source.connect(comp, providesPortName="dataXML_in") # Start Components & Push Data sb.start() source.push(inputData) time.sleep(2) sb.stop() # Check that the input and output files are the same try: self.assertEqual(filecmp.cmp("./data.xml", dataFileOut), True) except self.failureException as e: comp.releaseObject() source.releaseObject() os.remove(dataFileOut) raise e # Release the components and remove the generated files comp.releaseObject() source.releaseObject() os.remove(dataFileOut) print "........ PASSED\n" return
def testBPSOverride(self): self.octetConnect() sink = sb.DataSinkSDDS() self.comp.override_sdds_header.enabled = True for bps in range(32): time.sleep(0.1) self.comp.override_sdds_header.bps = bps sb.start() fakeData = 1024 * [1] self.source.push(fakeData, EOS=False, streamID=self.id(), sampleRate=1.0, complexData=False, loop=False) rcv = self.getPacket() sdds_header = self.getHeader(rcv) self.assertEqual(bps, sum(sdds_header.bps), "Received BPS that did not match expected") sb.stop()
def testOne(self): outData = [] count = 0 while True: outData = self.sink.getData() if outData: break if count == 100: break sleep(.1) count += 1 sb.stop() sleep(.5) for x in outData: print "%i " % x, print "" complexData = [] for x in xrange(len(outData) / 2): complexData.append(complex(outData[2 * x], outData[x * 2 + 1])) complexData = [x + 0.1 * random.random() for x in complexData] plotFFT(complexData)
def testMsdelOverride(self): self.octetConnect() self.comp.override_sdds_header.enabled = True for i in range(10): msdel = random.randint(0, 65535) time.sleep(0.1) self.comp.override_sdds_header.msdel = msdel sb.start() fakeData = 1024 * [1] self.source.push(fakeData, EOS=False, streamID=self.id(), sampleRate=1.0, complexData=False, loop=False) rcv = self.getPacket() sdds_header = self.getHeader(rcv) self.assertEqual(sdds_header.timeCode1msDelta, msdel, "Received MSdelta that did not match expected") sb.stop()
def testOne(self): outData = [] count = 0 while True: outData = self.sink.getData() if outData: break if count == 100: break sleep(.1) count+=1 sb.stop() sleep(.5) for x in outData: print "%i " %x, print "" complexData = [] for x in xrange(len(outData)/2): complexData.append(complex(outData[2*x], outData[x*2+1])) complexData = [x + 0.1*random.random() for x in complexData] plotFFT(complexData)
def testMsptrOverride(self): self.octetConnect() self.comp.override_sdds_header.enabled = True for i in range(10): msptr = random.randint(0, 2047) time.sleep(0.1) self.comp.override_sdds_header.msptr = msptr sb.start() fakeData = 1024 * [1] self.source.push(fakeData, EOS=False, streamID=self.id(), sampleRate=1.0, complexData=False, loop=False) rcv = self.getPacket() rcv_msptr = self.getMsptr(rcv) self.assertEqual(rcv_msptr, msptr, "Received msptr that did not match expected") sb.stop()
def test_push_packet(self): ##print self.ctx dsource=sb.DataSource() dsink=sb.DataSink() c_spd_xml = test_dir + self.c_dir + '/' + self.c_name + '/' + self.c_name + '.spd.xml' print c_spd_xml test_comp=sb.launch( c_spd_xml, execparams=self.execparams) if self.seq: data=self.seq cmp_data = data if self.cmpData: cmp_data = self.cmpData dsource.connect(test_comp, providesPortName=self.c_inport ) test_comp.connect(dsink, providesPortName=self.sink_inport, usesPortName=self.c_outport) sb.start() dsource.push(data,EOS=True) dest_data=dsink.getData(eos_block=True) sb.stop() self.assertEqual(data, dest_data)
def test_bpsk_decode(self): nbits = 6000 samples_per_symbol = 4 # Generate random bit sequence and convert to BPSK symbols bits_in = [random.randint(0,1) for x in range(nbits)] samples_in = symbols_to_samples(bits_to_symbols(bits_in), samples_per_symbol) # Add Gaussian noise and a slow rotation to the symbols sig_in = apply_rotation(add_noise(samples_in, 0.10), 0.01) # Convert from a list of complex pairs to a single list of floats sig_in = expand_complex(sig_in) source = sb.DataSource() sink = sb.DataSink() # FLL fll_ntaps = 55 freq_recov = sb.Component('../components/fll_band_edge_cc_4o/fll_band_edge_cc_4o.spd.xml',execparams=execparams) freq_recov.samples_per_symbol = samples_per_symbol freq_recov.rolloff = 0.35 freq_recov.filter_size = fll_ntaps freq_recov.bandwidth = 2.0*math.pi/100.0 # Timing recovery nfilts = 32 time_recov = sb.Component('../components/pfb_clock_sync_ccf_4o/pfb_clock_sync_ccf_4o.spd.xml', execparams=execparams) time_recov.sps = samples_per_symbol time_recov.loop_bw = 2*math.pi/100.0 # Note: taps are hard-coded time_recov.taps = list(bpsk_taps.taps) time_recov.filter_size = nfilts time_recov.init_phase = nfilts/2 time_recov.max_rate_deviation = 1.5 time_recov.osps = 1 # BPSK symbol decode receiver = sb.Component('../components/psk_demod_cb/psk_demod_cb.spd.xml', execparams=execparams) receiver.constellation = 1 receiver.loop_bw = 2*math.pi/100.0 receiver.fmin = -0.25 receiver.fmax = 0.25 # Connect components source.connect(freq_recov) freq_recov.connect(time_recov, usesPortName='data_complex_out') time_recov.connect(receiver, usesPortName='data_complex_out') receiver.connect(sink) # Push data through components, waiting for completion sb.start() source.push(sig_in, EOS=True, complexData=True) sym_out = sink.getData(eos_block=True) sb.stop() # The symbol is equivalent to the bit value; unpack from a char to # a number. bits_out = map(lambda x: struct.unpack('b', x)[0], sym_out) # The output data is delayed by 34 samples delay = 34 # Verify that our delayed output data matches the input bit_errors = 0 for ii in range(len(bits_out)-delay): if bits_out[ii+delay] != bits_in[ii]: bit_errors += 1 self.failUnless(bit_errors == 0, '%d bit errors' % (bit_errors,))
def main(): f = open('unit_test.log', 'w') display(f, "*********************************") display(f, "******** BPSK Unit Test *********") display(f, "*********************************") # Launch the component and the input sources and output sink display(f, "\n******* Creating Component ******") test_component = sb.launch('../BPSK.spd.xml', execparams={'DEBUG_LEVEL': 5}) clockSource = sb.DataSource() dataSource = sb.DataSource() dataSink = sb.DataSink() # Connect the output of the clock source and the data source # to the inputs of the BPSK. Connect the output of the BPSK # to the input of the data sink display(f, "\n****** Creating Connections *****") clockSource.connect(test_component, providesPortName='clockFloat_in') dataSource.connect(test_component, providesPortName='dataFloat_in') test_component.connect(dataSink, providesPortName='shortIn') display(f, "Connections created") display(f, "\n******** Generating Data ********") # Generate a simple sine wave for use as the clock and the # data convenient_time_data = linspace(0, 48 * pi, 2400) clock = sin(convenient_time_data).tolist() display(f, "Single Packet Case...") # Use 24 bits to generate a BPSK modulated signal single_packet_data = [ 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1 ] single_packet_keyed_data = [] i = 0 for j in single_packet_data: for k in range(i, i + 100): if j == 1: single_packet_keyed_data.append(clock[k]) else: single_packet_keyed_data.append(-clock[k]) i += 100 display(f, "Two Packet Case...") # Use a 16 bit packet and an 8 bit packet to generate two # BPSK modulated signals using the same clock two_packet_data1 = [0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1] two_packet_data2 = [0, 1, 0, 1, 0, 1, 1, 1] two_packet_keyed_data1 = [] two_packet_keyed_data2 = [] i = 0 for j in two_packet_data1: for k in range(i, i + 100): if j == 1: two_packet_keyed_data1.append(clock[k]) else: two_packet_keyed_data1.append(-clock[k]) i += 100 for j in two_packet_data2: for k in range(i, i + 100): if j == 1: two_packet_keyed_data2.append(clock[k]) else: two_packet_keyed_data2.append(-clock[k]) i += 100 display(f, "Two Packets, Unaligned Case...") # Reuse the one packet from above, but send it as two # that aren't lined up on the period boundary two_packet_unaligned_keyed_data1 = [] two_packet_unaligned_keyed_data2 = [] i = 0 for j in single_packet_data[:14]: for k in range(i, i + 100): if j == 1: two_packet_unaligned_keyed_data1.append(clock[k]) else: two_packet_unaligned_keyed_data1.append(-clock[k]) i += 100 for k in range(i, i + 100): # Put the first 27 samples into the first packet and the next # 73 into the second packet if k < (i + 27): if single_packet_data[14] == 1: two_packet_unaligned_keyed_data1.append(clock[k]) else: two_packet_unaligned_keyed_data1.append(-clock[k]) else: if single_packet_data[14] == 1: two_packet_unaligned_keyed_data2.append(clock[k]) else: two_packet_unaligned_keyed_data2.append(-clock[k]) i += 100 for j in single_packet_data[15:]: for k in range(i, i + 100): if j == 1: two_packet_unaligned_keyed_data2.append(clock[k]) else: two_packet_unaligned_keyed_data2.append(-clock[k]) i += 100 display(f, "\n******* Starting Components ******") sb.start() display(f, "Component started") display(f, "** Testing Single Packet Case **") # For now, the only accepted output rate of the BPSK is # 1187.5 bps. Since 100 samples of the clock represents # a period, this will force the output to be one bit per # period clockSource.push(clock, False, 'Test', (100 * 1187.5), False, [], None) dataSource.push(single_packet_keyed_data, False, 'Test', (100 * 1187.5), False, [], None) time.sleep(1) received_data = dataSink.getData() passed_test_1 = True test_1_message = "" displayList(f, "Received Data: ", received_data) displayList(f, "Original Data: ", single_packet_data) # Make sure that the received data and original data # are of the same length and that they match if len(received_data) == len(single_packet_data): for i in range(0, len(received_data)): if received_data[i] != single_packet_data[i]: passed_test_1 = False test_1_message = "received_data[" + str( i) + "] != original_data[" + str(i) + "]" break else: passed_test_1 = False test_1_message = "len(received_data) != len(original_data)" #****************************************************** display(f, "\n*** Testing Two Packet Case ****") clockSource.push(clock[:len(two_packet_keyed_data1)], False, 'Test', (100 * 1187.5), False, [], None) dataSource.push(two_packet_keyed_data1, False, 'Test', (100 * 1187.5), False, [], None) time.sleep(1) received_data = dataSink.getData() clockSource.push(clock[len(two_packet_keyed_data1):], False, 'Test', (100 * 1187.5), False, [], None) dataSource.push(two_packet_keyed_data2, False, 'Test', (100 * 1187.5), False, [], None) time.sleep(1) received_data += dataSink.getData() passed_test_2 = True test_2_message = "" displayList(f, "Received Data: ", received_data) displayList(f, "Original Data1: ", two_packet_data1) displayList(f, "Original Data2: ", two_packet_data2) # Make sure that the received data and original data # are of the same length and that they match if len(received_data) == (len(two_packet_data1) + len(two_packet_data2)): for i in range(0, len(received_data)): if i < len(two_packet_data1): if received_data[i] != two_packet_data1[i]: passed_test_2 = False test_2_message = "received_data[" + str( i) + "] != original_data1[" + str(i) + "]" break else: if received_data[i] != two_packet_data2[i - len(two_packet_data1)]: passed_test_2 = False test_2_message = "received_data[" + str( i) + "] != original_data2[" + str( i - len(two_packet_data1)) + "]" else: passed_test_2 = False test_2_message = "len(received_data) != len(original_data1) + len(original_data2)" #****************************************************** display(f, "\n** Testing Two Packet, Unaligned Case **") clockSource.push(clock[:len(two_packet_unaligned_keyed_data1)], False, 'Test', (100 * 1187.5), False, [], None) dataSource.push(two_packet_unaligned_keyed_data1, False, 'Test', (100 * 1187.5), False, [], None) time.sleep(1) received_data = dataSink.getData() clockSource.push(clock[len(two_packet_unaligned_keyed_data1):], False, 'Test', (100 * 1187.5), False, [], None) dataSource.push(two_packet_unaligned_keyed_data2, False, 'Test', (100 * 1187.5), False, [], None) time.sleep(1) received_data += dataSink.getData() passed_test_3 = True test_3_message = "" displayList(f, "Received Data: ", received_data) displayList(f, "Original Data: ", single_packet_data) # Make sure that the received data and original data # are of the same length and that they match if len(received_data) == len(single_packet_data): for i in range(0, len(received_data)): if received_data[i] != single_packet_data[i]: passed_test_3 = False test_3_message = "received_data[" + str( i) + "] != original_data[" + str(i) + "]" break else: passed_test_3 = False test_3_message = "len(received_data) != len(original_data1) + len(original_data2)" display(f, "\n******* Stopping Components ******") sb.stop() display(f, "Components stopped") # Display the results of the unit test if passed_test_1: display( f, "\nSingle Packet Test ...................." + u'\u2714'.encode('utf8')) else: display( f, "\nSingle Packet Test ...................." + u'\u2718'.encode('utf8') + '\t' + test_1_message) if passed_test_2: display( f, "Two Packet Test ......................." + u'\u2714'.encode('utf8')) else: display( f, "Two Packet Test ......................." + u'\u2718'.encode('utf8') + '\t' + test_2_message) if passed_test_3: display( f, "Two Packet, Unaligned Test ............" + u'\u2714'.encode('utf8')) else: display( f, "Two Packet, Unaligned Test ............" + u'\u2718'.encode('utf8') + '\t' + test_3_message) display(f, '\n') display(f, "Unit Test Complete") f.close()
def main(argv): sadfile = '' inputfile = '' dataformat = '' samplerate = '' iscomplex = False outputfile = '' try: opts, args = getopt.getopt(argv, "hs:i:f:r:co:", [ "sadfile=", "ifile=", "dataformat=", "samplerate=", "complex", "ofile=" ]) except getopt.GetoptError: print 'runWaveform.py -s <sadfile> -i <inputfile> -f <dataFormat> -r <sampleRate> -c -o <outputfile>' sys.exit(2) for opt, arg in opts: #print 'evaluating opt - ',opt,' arg - ',arg if opt == '-h': print 'runWaveform.py -s <sadfile> -i <inputfile> -f <dataFormat> -r <sampleRate> -c o <outputfile>' sys.exit() elif opt in ("-s", "--sadfile"): sadfile = arg elif opt in ("-i", "--ifile"): inputfile = arg elif opt in ("-f", "--dataformat"): dataformat = arg elif opt in ("-r", "--samplerate"): samplerate = arg elif opt in ("-c", "--complex"): iscomplex = True elif opt in ("-o", "--ofile"): outputfile = arg print 'setting outputfile', outputfile print 'Processing ', inputfile, " through waveform - ", sadfile sadFile = open(sadfile) sadFileString = sadFile.read() usesPort = '' usesComponent = '' providesPort = '' providesComponent = '' sadXML = parsers.sad.parseString(sadFileString) if sadXML.get_externalports(): for port in sadXML.get_externalports().get_port(): if port.get_usesidentifier(): usesPort = port.get_usesidentifier() usesComponent = port.get_componentinstantiationref() elif port.get_providesidentifier(): providesPort = port.get_providesidentifier() providesComponent = port.get_componentinstantiationref() if not usesPort and not providesPort: print 'Need uses and provides external ports' sys.exit() else: print 'No external ports' sys.exit() print usesPort, providesPort if not usesPort or not providesPort: print 'Require external uses & provides port' sys.exit() sb.loadSADFile(sadfile) fileSource = sb.FileSource(filename=inputfile, dataFormat=dataformat, sampleRate=samplerate) fileSink = sb.FileSink(filename=outputfile) #FIXME check file type matches external port fileSource.connect(sb.getComponent(providesComponent.get_refid()), providesPortName=providesPort) sb.getComponent(usesComponent.get_refid()).connect(fileSink, usesPortName=usesPort) sb.start() fileSink.waitForEOS() sb.stop() sb.release()
def test_bpsk_decode(self): nbits = 6000 samples_per_symbol = 4 # Generate random bit sequence and convert to BPSK symbols bits_in = [random.randint(0, 1) for x in range(nbits)] samples_in = symbols_to_samples(bits_to_symbols(bits_in), samples_per_symbol) # Add Gaussian noise and a slow rotation to the symbols sig_in = apply_rotation(add_noise(samples_in, 0.10), 0.01) # Convert from a list of complex pairs to a single list of floats sig_in = expand_complex(sig_in) source = sb.DataSource() sink = sb.DataSink() # FLL fll_ntaps = 55 freq_recov = sb.Component( '../components/fll_band_edge_cc_4o/fll_band_edge_cc_4o.spd.xml', execparams=execparams) freq_recov.samples_per_symbol = samples_per_symbol freq_recov.rolloff = 0.35 freq_recov.filter_size = fll_ntaps freq_recov.bandwidth = 2.0 * math.pi / 100.0 # Timing recovery nfilts = 32 time_recov = sb.Component( '../components/pfb_clock_sync_ccf_4o/pfb_clock_sync_ccf_4o.spd.xml', execparams=execparams) time_recov.sps = samples_per_symbol time_recov.loop_bw = 2 * math.pi / 100.0 # Note: taps are hard-coded time_recov.taps = list(bpsk_taps.taps) time_recov.filter_size = nfilts time_recov.init_phase = nfilts / 2 time_recov.max_rate_deviation = 1.5 time_recov.osps = 1 # BPSK symbol decode receiver = sb.Component( '../components/psk_demod_cb/psk_demod_cb.spd.xml', execparams=execparams) receiver.constellation = 1 receiver.loop_bw = 2 * math.pi / 100.0 receiver.fmin = -0.25 receiver.fmax = 0.25 # Connect components source.connect(freq_recov) freq_recov.connect(time_recov, usesPortName='data_complex_out') time_recov.connect(receiver, usesPortName='data_complex_out') receiver.connect(sink) # Push data through components, waiting for completion sb.start() source.push(sig_in, EOS=True, complexData=True) sym_out = sink.getData(eos_block=True) sb.stop() # The symbol is equivalent to the bit value; unpack from a char to # a number. bits_out = map(lambda x: struct.unpack('b', x)[0], sym_out) # The output data is delayed by 34 samples delay = 34 # Verify that our delayed output data matches the input bit_errors = 0 for ii in range(len(bits_out) - delay): if bits_out[ii + delay] != bits_in[ii]: bit_errors += 1 self.failUnless(bit_errors == 0, '%d bit errors' % (bit_errors, ))
def stop(self): # TODO: consider removing this sb.stop()
#figure(2) #title('Input Signal Time Plot') #plot(t, signal, 'y') # #figure(3) #title('Component & NumPy Output Plot') #plot(t_dec, py_dec, 'b') #plot(t_dec, received_data, 'g') # #grid(True) #show() #------------------------------------------------ # Stop Component #------------------------------------------------ sb.stop() ######################################################################################### # UNIT TEST 2 - Bandpass - Real Data # ######################################################################################### display(f,'****************************************************************************\n') display(f,'******************** Unit Test 2 - Bandpass - Real Data ********************\n') display(f,'****************************************************************************\n\n') #------------------------------------------------ # Create components and connections #------------------------------------------------ display(f,'* Creating Components and Connections\n') filt = sb.launch('../FilterDecimate.spd.xml',execparams={"DEBUG_LEVEL":3})
def tearDown(self): """Finish the unit test - this is run after every method that starts with test""" sb.stop() self.comp.releaseObject() ossie.utils.testing.ScaComponentTestCase.tearDown(self)
def stop(self): sb.stop()
def testBaseUri(self): ####################################################################### # Test base uri w/ keyword substitution print "\n**TESTING URI w/ KW Substitution" # Define test files dataFileIn = "./data.in" STREAMID = "baseuritest" COL_RF = 1.2e6 CHAN_RF1 = 1.25e6 CHAN_RF2 = 1.15e6 COLRF_HZ = "1200000Hz" CF_HZ1 = CHANRF_HZ1 = "1250000Hz" CF_HZ2 = CHANRF_HZ2 = "1150000Hz" MY_KEYWORD = "customkw" dataFileOut_template = "./%s.%s.%s.%s.%s.out" dataFileOut1 = dataFileOut_template % (STREAMID, CF_HZ1, COLRF_HZ, CHANRF_HZ1, MY_KEYWORD) dataFileOut2 = dataFileOut_template % (STREAMID, CF_HZ2, COLRF_HZ, CHANRF_HZ2, MY_KEYWORD) keywords1 = [ sb.io_helpers.SRIKeyword("COL_RF", COL_RF, "double"), sb.io_helpers.SRIKeyword("CHAN_RF", CHAN_RF1, "double"), sb.io_helpers.SRIKeyword("MY_KEYWORD", MY_KEYWORD, "string"), ] keywords2 = [ sb.io_helpers.SRIKeyword("COL_RF", COL_RF, "double"), sb.io_helpers.SRIKeyword("CHAN_RF", CHAN_RF2, "double"), sb.io_helpers.SRIKeyword("MY_KEYWORD", MY_KEYWORD, "string"), ] # Create Test Data File if it doesn't exist if not os.path.isfile(dataFileIn): with open(dataFileIn, "wb") as dataIn: dataIn.write(os.urandom(1024)) # Read in Data from Test File size = os.path.getsize(dataFileIn) with open(dataFileIn, "rb") as dataIn: data = list(struct.unpack("f" * (size / 4), dataIn.read(size))) # Create Components and Connections comp = sb.launch("../FileWriter.spd.xml") comp.destination_uri = dataFileOut_template % ( "%STREAMID%", "%CF_HZ%", "%COLRF_HZ%", "%CHANRF_HZ%", "%MY_KEYWORD%", ) comp.advanced_properties.existing_file = "TRUNCATE" source = sb.DataSource(bytesPerPush=64, dataFormat="32f") source.connect(comp, providesPortName="dataFloat_in") # Start Components & Push Data sb.start() source.push(data, streamID=STREAMID, SRIKeywords=keywords1) time.sleep(2) source.push(data, streamID=STREAMID, SRIKeywords=keywords2) time.sleep(2) sb.stop() # Check that the input and output files are the same try: dataFileOut = dataFileOut1 self.assertEqual(filecmp.cmp(dataFileIn, dataFileOut), True) dataFileOut = dataFileOut2 self.assertEqual(filecmp.cmp(dataFileIn, dataFileOut), True) except self.failureException as e: # unpacked bytes may be NaN, which could cause test to fail unnecessarily size = os.path.getsize(dataFileOut) with open(dataFileOut, "rb") as dataOut: data2 = list(struct.unpack("f" * (size / 4), dataOut.read(size))) for a, b in zip(data, data2): if a != b: if a != a and b != b: print "Difference in NaN format, ignoring..." else: print "FAILED:", a, "!=", b raise e # Release the components and remove the generated files finally: comp.releaseObject() source.releaseObject() os.remove(dataFileIn) os.remove(dataFileOut1) os.remove(dataFileOut2) print "........ PASSED\n" return
def timerTests(self, pkt_ts=False): ####################################################################### # Test multiple recording timers # Define test files dataFileIn = "./data.in" dataFileOut = "./data.out" resultsFileOut = "./results.out" sample_rate = 128.0 start_delay = 0.5 stop_delay = 2.0 # Create Test Data File if it doesn't exist if not os.path.isfile(dataFileIn): with open(dataFileIn, "wb") as dataIn: dataIn.write(os.urandom(1024)) # Read in Data from Test File size = os.path.getsize(dataFileIn) with open(dataFileIn, "rb") as dataIn: data = list(struct.unpack("f" * (size / 4), dataIn.read(size))) # Create Components and Connections comp = sb.launch("../FileWriter.spd.xml") comp.destination_uri = dataFileOut comp.recording_enabled = False # Create timers ts_start = bulkio.bulkio_helpers.createCPUTimestamp() start1_wsec = ts_start.twsec + 2.0 stop1_wsec = start1_wsec + 2.0 start2_wsec = stop1_wsec + 2.0 stop2_wsec = start2_wsec + 2.0 timers = [ {"recording_enable": True, "use_pkt_timestamp": pkt_ts, "twsec": start1_wsec, "tfsec": ts_start.tfsec}, {"recording_enable": False, "use_pkt_timestamp": pkt_ts, "twsec": stop1_wsec, "tfsec": ts_start.tfsec}, {"recording_enable": True, "use_pkt_timestamp": pkt_ts, "twsec": start2_wsec, "tfsec": ts_start.tfsec}, {"recording_enable": False, "use_pkt_timestamp": pkt_ts, "twsec": stop2_wsec, "tfsec": ts_start.tfsec}, ] # print timers comp.recording_timer = timers source = sb.DataSource( bytesPerPush=64.0, dataFormat="32f", startTime=ts_start.twsec + ts_start.tfsec + start_delay ) source.connect(comp, providesPortName="dataFloat_in") # results will be shifted due to start_delay results_offset = int((start1_wsec - ts_start.twsec - start_delay) * sample_rate) # Start Components & Push Data sb.start() if pkt_ts: source.push(data * 5, sampleRate=sample_rate) # 5*256 samples per push time.sleep(2) else: # meter to actual sample rate since based on cpu time end_ws = stop2_wsec + stop_delay num_samps = 16 loop_delay = num_samps / sample_rate idx = results_offset # necessary to achieve same results as pkt_ts, accounting for start_delay ts_now = bulkio.bulkio_helpers.createCPUTimestamp() while ts_now.twsec < end_ws: source.push(data[idx : idx + num_samps], sampleRate=sample_rate) # 256 samples per push idx = (idx + num_samps) % len(data) time.sleep(loop_delay) ts_now = bulkio.bulkio_helpers.createCPUTimestamp() sb.stop() # Create Test Results Files results = data[results_offset:] + data[:results_offset] with open(resultsFileOut, "wb") as dataIn: dataIn.write(struct.pack("f" * len(results), *results)) # Check that the input and output files are the same try: try: self.assertEqual(filecmp.cmp(resultsFileOut, dataFileOut), True) except self.failureException as e: # unpacked bytes may be NaN, which could cause test to fail unnecessarily size1 = os.path.getsize(dataFileOut) with open(dataFileOut, "rb") as dataOut1: data1 = list(struct.unpack("f" * (size1 / 4), dataOut1.read(size1))) offset1 = results.index(max(results)) - data1.index(max(data1)) # print 'offset1 is', offset1 if offset1 != 0: if abs(offset1) > num_samps: # allow it to be off by one data push print "FAILED: offset1 =", offset1 raise e shifted_res1 = results[offset1:] + results[:offset1] else: shifted_res1 = results for a, b in zip(shifted_res1, data1): if a != b: if a != a and b != b: print "Difference in NaN format, ignoring..." else: print "1st FAILED:", a, "!=", b raise e try: self.assertEqual(filecmp.cmp(resultsFileOut, dataFileOut + "-1"), True) except self.failureException as e: # unpacked bytes may be NaN, which could cause test to fail unnecessarily size2 = os.path.getsize(dataFileOut + "-1") with open(dataFileOut + "-1", "rb") as dataOut: data2 = list(struct.unpack("f" * (size2 / 4), dataOut.read(size2))) offset2 = results.index(max(results)) - data2.index(max(data2)) # print 'offset2 is', offset2 if offset2 != 0: if abs(offset2) > num_samps: # allow it to be off by one data push print "FAILED: offset2 =", offset2 raise e shifted_res2 = results[offset2:] + results[:offset2] else: shifted_res2 = results for a, b in zip(shifted_res2, data2): if a != b: if a != a and b != b: print "Difference in NaN format, ignoring..." else: print "2nd FAILED:", a, "!=", b raise e except: raise e # Release the components and remove the generated files finally: comp.releaseObject() source.releaseObject() os.remove(dataFileIn) os.remove(dataFileOut) os.remove(dataFileOut + "-1") os.remove(resultsFileOut) # TODO - validate timestamps, perhaps using BLUEFILEs print "........ PASSED\n" return
def startFlow(self): sb.start() self.comp.playback_state = 'PLAY' time.sleep(2) sb.stop() return self.sink.getData()
data1 = [0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0] data2 = [0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1] print 'Pushing data' #Send data across the wave #Do two pushes to verify that we are storing the last bit of each packet src.push(data1) time.sleep(.05) received_data = sink.getData() src.push(data2) time.sleep(.05) received_data.extend(sink.getData()) print '\n*********** Stopping Sandbox ************' #Stop sandbox env sb.stop() print 'Components stopped' #Check expected values against the received values expected = [ 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1 ] passed = True for i in xrange(len(received_data)): if received_data[i] != expected[i]: passed = False print '\n************** Results ****************' if passed: print "Unit Test 1 .........................", u'\u2714'
def load_and_run_scenario(json_file, time_inc=1, wfm=""): """Load a scenario and run Parameters ---------- json_file : str, dict The path to a JSON specifying the scenario. This should include "components", "connections", "simulation" time_inc : float Time increment to run simulation. After each increment, check the debug (throughput) wfm : str Specify a file to save the scenario to waveform. Don't save if empty string """ if isinstance(json_file, str): settings = json.load(open(json_file), encoding='ascii') settings = convert_dict(settings) elif isinstance(json_file, dict): settings = json_file else: raise ValueError("Expecting a string json filepath or dict") # extract from dictionary (verify keys exist) comp_specs = settings.get("components", {}) wave_specs = settings.get("waveforms", {}) domain_specs = settings.get("domains", {}) conns = settings["connections"] simm = settings["simulation"] debug = settings.get("debug", {}) if domain_specs: setup_domains(domain_specs) # --------------------------- load components ------------------------- comp_dict = component_helper.launch_components(sb, comp_specs) # -------------------------- load waveforms --------------------------- wfm_dict = waveform_helper.launch_waveforms(wave_specs) # ---------------------- connect message sinks ------------------------ msg_sinks, msg_store = message_helper.connect_msg_sinks( sb, comp_dict, wfm_dict, debug) # ------------------------- setup connections ------------------------- for conn in conns: try: obj_1 = get_instance(conn[0], comp_dict, wfm_dict) port_1 = obj_1.getPort(str(conn[1])) obj_2 = get_instance(conn[2], comp_dict, wfm_dict) port_2 = obj_2.getPort(str(conn[3])) port_1.connectPort(port_2, "conn_%s_to_%s_"%(str(conn[0]), str(conn[2]))\ + str(uuid.uuid1())) except Exception as e: print("Error running connection %s" % str(conn)) raise # --------------------------- setup debug --------------------------- throughput_ports = throughput_helper.setup_throughput(debug.get( "throughput", []), comp_dict=comp_dict, wfm_dict=wfm_dict) # -------------------------- save waveform ---------------------------- if wfm: raise NotImplementedError("Waveform Generation is not working") # NOTE: Generated waveform does not track component settings with open(wfm + ".sad.xml", "w") as fid: fid.write(sb.generateSADXML(wfm)) # -------------------------- run simulation --------------------------- if simm["type"].lower() in ["time"]: print("In time simulation") waveform_helper.start_waveforms(wfm_dict) component_helper.start_in_reverse_order(comp_dict) tic = time.time() while time.time() - tic < simm["value"]["duration"]: # show message being passed message_helper.show_messages(msg_sinks, msg_store) # show port throughput statistics throughput_helper.show_throughput(throughput_ports) # sleep a little time.sleep(time_inc) component_helper.stop_in_order(comp_dict) waveform_helper.stop_waveforms(wfm_dict) #sb.stop() elif simm["type"].lower() in ["user"]: # run till user hits enter sb.start() resp = user_prompt("Hit enter to exit") sb.stop() else: raise RuntimeError("Unexpected type of simulation") # save messages if msg_store: message_helper.save_messages(msg_store) # TODO: release components/waveforms/devices/domains waveform_helper.release_waveforms(wfm_dict) throughput_helper.close(throughput_ports)
def testBlueShortPortSwapped(self): ####################################################################### # Test Bluefile Swapped SHORT Functionality print "\n**TESTING BLUEFILE Swapped + SHORT PORT" #Define test files dataFileIn = './bluefile.in' dataFileInSwap = './bluefile.in.swap' #Create Test Data File if it doesn't exist if not os.path.isfile(dataFileIn): tmpSink = bluefile_helpers.BlueFileWriter(dataFileIn, BULKIO__POA.dataShort) tmpSink.start() tmpSri = createSri('bluefileShortSwapped', 5000) #kwVal = 1234 #kwSwap = swap([kwVal], 'long')[0] #tmpSri.keywords = props_from_dict({'TEST_KW':kwSwap}) tmpSri.keywords = props_from_dict({'TEST_KW': 1234}) tmpSink.pushSRI(tmpSri) tmpTs = createTs() #tmpSink.pushPacket(swap(range(1024),'short'), tmpTs, True, 'bluefileShortSwapped') tmpSink.pushPacket(range(1024), tmpTs, True, 'bluefileShortSwapped') #Read in Data from Test File, modify header, and rewrite hdr, d = bluefile.read(dataFileIn, dict) hdr['file_name'] = dataFileInSwap hdr['head_rep'] = 'IEEE' hdr['data_rep'] = 'IEEE' bluefile.write(dataFileInSwap, hdr, d) #Read in Data from Swapped Test File hdr, d = bluefile.read(dataFileInSwap, dict) data = list(d) keywords = hdr['ext_header'] #Create Components and Connections comp = sb.launch('../FileReader.spd.xml') comp.source_uri = dataFileInSwap comp.file_format = 'BLUEFILE' sink = sb.DataSink() comp.connect(sink, usesPortName='dataShort_out') #Start Components & Push Data sb.start() comp.playback_state = 'PLAY' time.sleep(2) readData = sink.getData() readKeywords = props_to_dict(sink.sri().keywords) sb.stop() #Check that the input and output files are the same try: self.assertEqual(data, readData) except self.failureException as e: comp.releaseObject() sink.releaseObject() os.remove(dataFileIn) os.remove(dataFileInSwap) raise e #Check that the keywords are the same try: self.assertEqual(keywords, readKeywords) except self.failureException as e: comp.releaseObject() sink.releaseObject() os.remove(dataFileIn) os.remove(dataFileInSwap) raise e #Release the components and remove the generated files comp.releaseObject() sink.releaseObject() os.remove(dataFileIn) os.remove(dataFileInSwap) print "........ PASSED\n" return
def main(): f = open('unit_test.log', 'w') display(f, "*********************************") display(f, "******** BPSK Unit Test *********") display(f, "*********************************") # Launch the component and the input sources and output sink display(f, "\n******* Creating Component ******") test_component = sb.launch('../BPSK.spd.xml', execparams={'DEBUG_LEVEL':5}) clockSource = sb.DataSource() dataSource = sb.DataSource() dataSink = sb.DataSink() # Connect the output of the clock source and the data source # to the inputs of the BPSK. Connect the output of the BPSK # to the input of the data sink display(f, "\n****** Creating Connections *****") clockSource.connect(test_component, providesPortName='clockFloat_in') dataSource.connect(test_component, providesPortName='dataFloat_in') test_component.connect(dataSink, providesPortName='shortIn') display(f, "Connections created") display(f, "\n******** Generating Data ********") # Generate a simple sine wave for use as the clock and the # data convenient_time_data = linspace(0, 48*pi, 2400) clock = sin(convenient_time_data).tolist() display(f, "Single Packet Case...") # Use 24 bits to generate a BPSK modulated signal single_packet_data = [0,1,0,1,0,0,0,0,0,1,0,0,0,0,1,1,0,1,0,1,0,1,1,1] single_packet_keyed_data = [] i = 0 for j in single_packet_data: for k in range(i, i+100): if j == 1: single_packet_keyed_data.append(clock[k]) else: single_packet_keyed_data.append(-clock[k]) i += 100 display(f, "Two Packet Case...") # Use a 16 bit packet and an 8 bit packet to generate two # BPSK modulated signals using the same clock two_packet_data1 = [0,1,0,1,0,0,0,0,0,1,0,0,0,0,1,1] two_packet_data2 = [0,1,0,1,0,1,1,1] two_packet_keyed_data1 = [] two_packet_keyed_data2 = [] i = 0 for j in two_packet_data1: for k in range(i, i+100): if j == 1: two_packet_keyed_data1.append(clock[k]) else: two_packet_keyed_data1.append(-clock[k]) i += 100 for j in two_packet_data2: for k in range(i, i+100): if j == 1: two_packet_keyed_data2.append(clock[k]) else: two_packet_keyed_data2.append(-clock[k]) i += 100 display(f, "Two Packets, Unaligned Case...") # Reuse the one packet from above, but send it as two # that aren't lined up on the period boundary two_packet_unaligned_keyed_data1 = [] two_packet_unaligned_keyed_data2 = [] i = 0 for j in single_packet_data[:14]: for k in range(i, i+100): if j == 1: two_packet_unaligned_keyed_data1.append(clock[k]) else: two_packet_unaligned_keyed_data1.append(-clock[k]) i += 100 for k in range(i, i+100): # Put the first 27 samples into the first packet and the next # 73 into the second packet if k < (i+27): if single_packet_data[14] == 1: two_packet_unaligned_keyed_data1.append(clock[k]) else: two_packet_unaligned_keyed_data1.append(-clock[k]) else: if single_packet_data[14] == 1: two_packet_unaligned_keyed_data2.append(clock[k]) else: two_packet_unaligned_keyed_data2.append(-clock[k]) i += 100 for j in single_packet_data[15:]: for k in range(i, i+100): if j == 1: two_packet_unaligned_keyed_data2.append(clock[k]) else: two_packet_unaligned_keyed_data2.append(-clock[k]) i += 100 display(f, "\n******* Starting Components ******") sb.start() display(f, "Component started") display(f, "** Testing Single Packet Case **") # For now, the only accepted output rate of the BPSK is # 1187.5 bps. Since 100 samples of the clock represents # a period, this will force the output to be one bit per # period clockSource.push(clock, False, 'Test', (100 * 1187.5), False, [], None) dataSource.push(single_packet_keyed_data, False, 'Test', (100 * 1187.5), False, [], None) time.sleep(1) received_data = dataSink.getData() passed_test_1 = True test_1_message = "" displayList(f, "Received Data: ",received_data) displayList(f, "Original Data: ", single_packet_data) # Make sure that the received data and original data # are of the same length and that they match if len(received_data) == len(single_packet_data): for i in range(0, len(received_data)): if received_data[i] != single_packet_data[i]: passed_test_1 = False test_1_message = "received_data[" + str(i) + "] != original_data[" + str(i) + "]" break else: passed_test_1 = False test_1_message = "len(received_data) != len(original_data)" #****************************************************** display(f, "\n*** Testing Two Packet Case ****") clockSource.push(clock[:len(two_packet_keyed_data1)], False, 'Test', (100 * 1187.5), False, [], None) dataSource.push(two_packet_keyed_data1, False, 'Test', (100 * 1187.5), False, [], None) time.sleep(1) received_data = dataSink.getData() clockSource.push(clock[len(two_packet_keyed_data1):], False, 'Test', (100 * 1187.5), False, [], None) dataSource.push(two_packet_keyed_data2, False, 'Test', (100 * 1187.5), False, [], None) time.sleep(1) received_data += dataSink.getData() passed_test_2 = True test_2_message = "" displayList(f, "Received Data: ", received_data) displayList(f, "Original Data1: ", two_packet_data1) displayList(f, "Original Data2: ", two_packet_data2) # Make sure that the received data and original data # are of the same length and that they match if len(received_data) == (len(two_packet_data1) + len(two_packet_data2)): for i in range(0, len(received_data)): if i < len(two_packet_data1): if received_data[i] != two_packet_data1[i]: passed_test_2 = False test_2_message = "received_data[" + str(i) + "] != original_data1[" + str(i) + "]" break else: if received_data[i] != two_packet_data2[i-len(two_packet_data1)]: passed_test_2 = False test_2_message = "received_data[" + str(i) + "] != original_data2[" + str(i - len(two_packet_data1)) + "]" else: passed_test_2 = False test_2_message = "len(received_data) != len(original_data1) + len(original_data2)" #****************************************************** display(f, "\n** Testing Two Packet, Unaligned Case **") clockSource.push(clock[:len(two_packet_unaligned_keyed_data1)], False, 'Test', (100 * 1187.5), False, [], None) dataSource.push(two_packet_unaligned_keyed_data1, False, 'Test', (100 * 1187.5), False, [], None) time.sleep(1) received_data = dataSink.getData() clockSource.push(clock[len(two_packet_unaligned_keyed_data1):], False, 'Test', (100 * 1187.5), False, [], None) dataSource.push(two_packet_unaligned_keyed_data2, False, 'Test', (100 * 1187.5), False, [], None) time.sleep(1) received_data += dataSink.getData() passed_test_3 = True test_3_message = "" displayList(f, "Received Data: ", received_data) displayList(f, "Original Data: ", single_packet_data) # Make sure that the received data and original data # are of the same length and that they match if len(received_data) == len(single_packet_data): for i in range(0, len(received_data)): if received_data[i] != single_packet_data[i]: passed_test_3 = False test_3_message = "received_data[" + str(i) + "] != original_data[" + str(i) + "]" break else: passed_test_3 = False test_3_message = "len(received_data) != len(original_data1) + len(original_data2)" display(f, "\n******* Stopping Components ******") sb.stop() display(f, "Components stopped") # Display the results of the unit test if passed_test_1: display(f, "\nSingle Packet Test ...................." + u'\u2714'.encode('utf8')) else: display(f, "\nSingle Packet Test ...................." + u'\u2718'.encode('utf8') + '\t' + test_1_message) if passed_test_2: display(f, "Two Packet Test ......................." + u'\u2714'.encode('utf8')) else: display(f, "Two Packet Test ......................." + u'\u2718'.encode('utf8') + '\t' + test_2_message) if passed_test_3: display(f, "Two Packet, Unaligned Test ............" + u'\u2714'.encode('utf8')) else: display(f, "Two Packet, Unaligned Test ............" + u'\u2718'.encode('utf8') + '\t' + test_3_message) display(f, '\n') display(f, "Unit Test Complete") f.close()