def test_002_normal(self): tnow = time.time() in_data = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1] meta = pmt.dict_add(pmt.make_dict(), pmt.intern( 'system_time'), pmt.from_double(tnow - 10.0)) in_pdu = pmt.cons(meta, pmt.init_c32vector(len(in_data), in_data)) e_data = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1] e_meta = pmt.dict_add(pmt.make_dict(), pmt.intern( 'system_time'), pmt.from_double(tnow)) e_meta = pmt.dict_add(e_meta, pmt.intern( 'sys time delta (ms)'), pmt.from_double(10000.0)) e_pdu = pmt.cons(e_meta, pmt.init_c32vector(len(e_data), e_data)) # set up fg self.tb.start() self.time_delta.to_basic_block()._post(pmt.intern("pdu"), in_pdu) self.waitFor(lambda: self.debug.num_messages() == 1, timeout=1.0, poll_interval=0.01) self.tb.stop() self.tb.wait() # check data self.assertEqual(1, self.debug.num_messages()) a_meta = pmt.car(self.debug.get_message(0)) time_tag = pmt.dict_ref(a_meta, pmt.intern("system_time"), pmt.PMT_NIL) delta_tag = pmt.dict_ref(a_meta, pmt.intern( "sys time delta (ms)"), pmt.PMT_NIL) self.assertAlmostEqual(tnow, pmt.to_double(time_tag), delta=60) self.assertAlmostEqual(10000, pmt.to_double(delta_tag), delta=10)
def test_003_double_eob_rej_tt_update (self): self.tb = gr.top_block () start_time = 0.0 sob_tag = gr.tag_utils.python_to_tag((51, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) eob_tag = gr.tag_utils.python_to_tag((51+(8*11), pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) time_tuple = pmt.make_tuple(pmt.from_uint64(4), pmt.from_double(0.125), pmt.from_uint64(10000000), pmt.from_double(4000000.0)) time_tag = gr.tag_utils.python_to_tag((360, pmt.intern("rx_time"), time_tuple, pmt.intern("src"))) sob_tag2 = gr.tag_utils.python_to_tag((400, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) eob_tag2e = gr.tag_utils.python_to_tag((409, pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) eob_tag2 = gr.tag_utils.python_to_tag((416, pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) vs = blocks.vector_source_s(range(500), False, 1, [sob_tag, eob_tag, time_tag, sob_tag2, eob_tag2e, eob_tag2]) t2p = pdu_utils.tags_to_pdu_s(pmt.intern('SOB'), pmt.intern('EOB'), 1024, 1000000, ([]), False, 0, start_time) t2p.set_eob_parameters(8, 0) dbg = blocks.message_debug() self.tb.connect(vs, t2p) self.tb.msg_connect((t2p, 'pdu_out'), (dbg, 'store')) expected_vec1 = pmt.init_s16vector((8*11), range(51,51+(8*11))) expected_vec2 = pmt.init_s16vector(16, list(range(400,409)) + [0]*7) expected_time1 = start_time + (51 / 1000000.0) expected_time2 = 4.125 + ((400-360) / 1000000.0) self.tb.run () self.assertEqual(dbg.num_messages(), 2) self.assertTrue(pmt.equal(pmt.cdr(dbg.get_message(0)), expected_vec1)) self.assertTrue(pmt.equal(pmt.cdr(dbg.get_message(1)), expected_vec2)) time_tuple1 = pmt.dict_ref(pmt.car(dbg.get_message(0)), pmt.intern("burst_time"), pmt.PMT_NIL) time_tuple2 = pmt.dict_ref(pmt.car(dbg.get_message(1)), pmt.intern("burst_time"), pmt.PMT_NIL) self.assertAlmostEqual(pmt.to_uint64(pmt.tuple_ref(time_tuple1,0)) + pmt.to_double(pmt.tuple_ref(time_tuple1,1)), expected_time1) self.assertAlmostEqual(pmt.to_uint64(pmt.tuple_ref(time_tuple2,0)) + pmt.to_double(pmt.tuple_ref(time_tuple2,1)), expected_time2) self.tb = None
def test_002_timing(self): self.tb.start() self.add_sys_time.to_basic_block()._post(pmt.intern("pdu"), pmt.intern("BAD PDU")) self.add_sys_time.to_basic_block()._post( pmt.intern("pdu"), pmt.cons(pmt.make_dict(), pmt.init_u8vector(1, [0]))) time.sleep( 1.0 ) # wait for one second to provide a time difference between messages self.add_sys_time.to_basic_block()._post( pmt.intern("pdu"), pmt.cons(pmt.make_dict(), pmt.init_u8vector(1, [0]))) self.waitFor(lambda: self.debug.num_messages() == 2, timeout=1.0, poll_interval=0.01) self.tb.stop() self.tb.wait() t0 = pmt.to_double( pmt.dict_ref(pmt.car(self.debug.get_message(0)), pmt.intern("systime"), pmt.from_double(0.0))) t1 = pmt.to_double( pmt.dict_ref(pmt.car(self.debug.get_message(1)), pmt.intern("systime"), pmt.from_double(0.0))) self.assertTrue( ((t1 - t0) - 1) < 0.05) # should be sufficient tolerance
def test_simple(self): # make the data and expected results data = [x + x * 1j for x in range(10)] pdu_in = pmt.cons(pmt.make_dict(), pmt.init_c32vector(len(data), data)) expected_energy = sum([abs(x)**2 for x in data]) expected_power = 10 * np.log10(expected_energy / len(data)) # run flowgraph self.tb.start() time.sleep(.001) self.emitter.emit(pmt.intern("BAD PDU")) time.sleep(.001) self.emitter.emit(pdu_in) time.sleep(.01) self.tb.stop() self.tb.wait() # don't wait...may not return in time # extract results rcv_pdu = self.debug.get_message(0) rcv_meta = pmt.car(rcv_pdu) rcv_data = pmt.c32vector_elements(pmt.cdr(rcv_pdu)) rcv_energy = pmt.to_double( pmt.dict_ref(rcv_meta, pmt.intern("energy"), pmt.PMT_NIL)) rcv_power = pmt.to_double( pmt.dict_ref(rcv_meta, pmt.intern("power"), pmt.PMT_NIL)) # assert expectations precision = 1e-3 self.assertTrue(abs(rcv_energy - expected_energy) < precision) self.assertTrue(abs(rcv_power - expected_power) < precision)
def test_004_boost_time (self): self.tb = gr.top_block () start_time = 0.1 sob_tag = gr.tag_utils.python_to_tag((34, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) eob_tag = gr.tag_utils.python_to_tag((34+(8*31), pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) vs = blocks.vector_source_s(range(350), False, 1, [sob_tag, eob_tag]) t2p = pdu_utils.tags_to_pdu_s(pmt.intern('SOB'), pmt.intern('EOB'), 1024, 512000, ([]), False, 0, start_time) t2p.enable_time_debug(True) t2p.set_eob_parameters(8, 0) dbg = blocks.message_debug() td = pdu_utils.time_delta("TIME CHECKER") self.tb.connect(vs, t2p) self.tb.msg_connect((t2p, 'pdu_out'), (dbg, 'store')) self.tb.msg_connect((t2p, 'pdu_out'), (td, 'pdu_in')) expected_vec = pmt.init_s16vector((8*31), range(34,34+(8*31))) expected_time = start_time + (34 / 512000.0) ts = time.time() self.tb.run () self.assertEqual(dbg.num_messages(), 1) self.assertTrue(pmt.equal(pmt.cdr(dbg.get_message(0)), expected_vec)) time_tuple1 = pmt.dict_ref(pmt.car(dbg.get_message(0)), pmt.intern("burst_time"), pmt.PMT_NIL) self.assertAlmostEqual(pmt.to_uint64(pmt.tuple_ref(time_tuple1,0)) + pmt.to_double(pmt.tuple_ref(time_tuple1,1)), expected_time) wct = pmt.to_double(pmt.dict_ref(pmt.car(dbg.get_message(0)), pmt.intern("wall_clock_time"), pmt.PMT_NIL)) self.assertTrue((wct - ts) < 1.0) self.tb = None
def handle_command(self, msg): # incoming message will be a dictionary that should contain the items # freq and lo_offset at a minimum - if this is met, issue a command # that can be handled by the freq_xlating_fir_filter_ccf block try: #print "got a message!" # we don't care about the frequency since we are CORDIC tuning lo_offset = pmt.dict_ref(msg, self.dict_key, pmt.PMT_NIL) if not pmt.eqv(lo_offset, pmt.PMT_NIL): offset = pmt.to_python(lo_offset) #print "lo offset is " + repr(offset*-1.0) self.message_port_pub(pmt.intern("freq"), pmt.cons(pmt.intern("freq"), pmt.from_double(-1.0*offset))) #print "published msg, offset = " + repr(-1.0*offset) # if the dictionary has a time value, use it time_tag = pmt.dict_ref(msg, pmt.intern("time"), pmt.PMT_NIL) if not pmt.eqv(time_tag, pmt.PMT_NIL): secs = pmt.to_uint64(pmt.car(time_tag)) - self.origin_time['secs'] frac = pmt.to_double(pmt.cdr(time_tag)) - self.origin_time['frac'] tune_sample = long(secs * self.sample_rate) + long(frac * self.sample_rate) else: tune_sample = TAG_IMMEDIATELY # we will also set the block to tag the output when it is time self.tag_offset = tune_sample self.tag_value = pmt.from_double(-1.0*offset) except Exception as e: print "exception: " + repr(e)
def write_data(self, msg): snr = pmt.to_double(pmt.dict_ref(msg, pmt.intern("snr"), pmt.from_double(0))) encoding = pmt.to_long(pmt.dict_ref(msg, pmt.intern("encoding"), pmt.from_long(0))) time_now = time() * 1000 delay = str(time_now - self.last_time) self.last_time = time_now if self.snr_file != "": f_snr = open(self.snr_file, 'a') f_snr.write(str(snr) + '\n') f_snr.close() if self.enc_file != "": f_enc = open(self.enc_file, 'a') f_enc.write(str(encoding) + '\n') f_enc.close() if self.delay_file != "": f_delay = open(self.delay_file, 'a') f_delay.write(delay + '\n') f_delay.close() if self.debug: print("SNR:" + str(snr)) print("Encoding:" + str(encoding)) print("Delay in millis: " + delay)
def msg_handler(self, m): if not pmt.is_pair(m): return meta = pmt.car(m) if not pmt.is_dict(meta): return blockstart = pmt.to_long( pmt.dict_ref(meta, pmt.intern('blockstart'), pmt.from_long(-1024))) blockend = pmt.to_long( pmt.dict_ref(meta, pmt.intern('blockend'), pmt.from_long(-1024))) if blockstart == -1024 or blockend == -1024: return rel_cfreq = pmt.to_double( pmt.dict_ref(meta, pmt.intern('rel_cfreq'), pmt.from_double(-1.0))) rel_bw = pmt.to_double( pmt.dict_ref(meta, pmt.intern('rel_bw'), pmt.from_double(-1.0))) if rel_cfreq < 0.0 or rel_bw < 0.0: return blockleft = int(self.normwidth * (rel_cfreq - rel_bw / 2.0)) blockright = int( numpy.ceil(self.normwidth * (rel_cfreq + rel_bw / 2.0))) #print('new msg: {} {} {} {} {} {}'.format(blockstart, blockend, rel_cfreq, rel_bw, blockleft, blockright)) self.msg_puffer += [(blockstart, blockend, blockleft, blockright)]
def msg_handler_frame(self, msg_in): ## print('-------------------- msg_handler_frame --------------------') ## print(msg_in) symbols = pmt.to_python( pmt.dict_ref(msg_in, pmt.intern('symbols'), pmt.PMT_NIL)) soft_dec = pmt.to_python( pmt.dict_ref(msg_in, pmt.intern('soft_dec'), pmt.PMT_NIL)) symb, constellation_idx, do_continue, save_soft_dec = self._obj.get_next_frame( symbols) if do_continue and len(soft_dec) != 0: d = self._obj.decode_soft_dec(soft_dec) msg_out = pmt.make_dict() msg_out = pmt.dict_add(msg_out, pmt.intern('packet_len'), pmt.to_pmt(len(d))) d = np.array(d, dtype=np.float32) d[abs(d) == np.Inf] = 0 vv = pmt.to_pmt(d) msg = pmt.cons(msg_out, vv) self.message_port_pub(self._port_soft_dec, msg) ## TODO: publish the bits if success ##print('symb=', symb, symb['symb'], symb['scramble']) msg_out = pmt.make_dict() msg_out = pmt.dict_add(msg_out, pmt.intern('symb'), pmt.to_pmt(symb['symb'])) msg_out = pmt.dict_add(msg_out, pmt.intern('scramble'), pmt.to_pmt(symb['scramble'])) msg_out = pmt.dict_add(msg_out, pmt.intern('constellation_idx'), pmt.to_pmt(constellation_idx)) msg_out = pmt.dict_add(msg_out, pmt.intern('do_continue'), pmt.to_pmt(np.bool(do_continue))) msg_out = pmt.dict_add(msg_out, pmt.intern('save_soft_dec'), pmt.to_pmt(np.bool(save_soft_dec))) ## print(msg_out) self.message_port_pub(self._port_frame_info, msg_out)
def msg_handler_analyzed_data_in(self, msg): print("in msg_handler_analyzed_data_in") self.lock() gate_params = pmt.vector_ref(msg, 0) gate_type_PMT = pmt.dict_ref( gate_params, pmt.from_float( quantum_gate_param_type.quantum_gate_param_type.GATE_TYPE), pmt.PMT_NIL) if (pmt.eq(gate_type_PMT, pmt.PMT_NIL)): return gate_type = pmt.to_float(gate_type_PMT) print("gate_params.gate_type=" + str(gate_type)) qubit_id_PMT = pmt.dict_ref( gate_params, pmt.from_float( quantum_gate_param_type.quantum_gate_param_type.QUBIT_ID), pmt.PMT_NIL) if (pmt.eq(qubit_id_PMT, pmt.PMT_NIL)): return qubit_id = pmt.to_float(qubit_id_PMT) print("gate_params.qubit_id=" + str(qubit_id)) if (gate_type == quantum_gate_type.quantum_gate_type.X): print("in msg_handler_analyzed_data_in X gate") #回路を作る RO_STATE = self._qubit_stat_map[qubit_id] if (float(RO_STATE.angle) == 0.0): RO_STATE.angle = 180.0 else: RO_STATE.angle = 0.0 self._qubit_stat_map[qubit_id] = RO_STATE elif (gate_type == quantum_gate_type.quantum_gate_type.RO): print("in msg_handler_analyzed_data_in RO") #回路を実行する RO_STATE = self._qubit_stat_map[qubit_id] SIM_msg = pmt.make_dict() SIM_msg = pmt.dict_add( SIM_msg, pmt.from_float( quantum_qubit_param_type.quantum_qubit_param_type.ID), pmt.from_float(qubit_id)) SIM_msg = pmt.dict_add( SIM_msg, pmt.from_float( quantum_qubit_param_type.quantum_qubit_param_type.ANGLE), pmt.from_float(float(RO_STATE.angle))) SIM_msg = pmt.dict_add( SIM_msg, pmt.from_float( quantum_qubit_param_type.quantum_qubit_param_type.STATE), pmt.from_float(quantum_qubit_RO_state_type. quantum_qubit_RO_state_type.START)) self.message_port_pub(pmt.intern('simulated_data'), SIM_msg) RO_STATE.state = quantum_qubit_RO_state_type.quantum_qubit_RO_state_type.START self._qubit_stat_map[qubit_id] = RO_STATE self.unlock()
def msg_handler_QOBJ_in(self, msg): print("in msg_handler_QOBJ_in") self.lock() qubit_id_PMT = pmt.dict_ref( msg, pmt.from_float( quantum_qubit_param_type.quantum_qubit_param_type.ID), pmt.PMT_NIL) if (pmt.eq(qubit_id_PMT, pmt.PMT_NIL)): return qubit_id = pmt.to_float(qubit_id_PMT) print("quantum_qubit_param_type.qubit_id=" + str(qubit_id)) if (this._qubit_id != qubit_id): return qubit_angle_PMT = pmt.dict_ref( msg, pmt.from_float( quantum_qubit_param_type.quantum_qubit_param_type.ANGLE), pmt.PMT_NIL) if (pmt.eq(qubit_angle_PMT, pmt.PMT_NIL)): return qubit_angle = pmt.to_float(qubit_angle_PMT) print("quantum_qubit_param_type.qubit_angle=" + str(qubit_angle)) qubit_pole_PMT = pmt.dict_ref( msg, pmt.from_float( quantum_qubit_param_type.quantum_qubit_param_type.POLE), pmt.PMT_NIL) if (pmt.eq(qubit_pole_PMT, pmt.PMT_NIL)): return qubit_pole = pmt.to_float(qubit_pole_PMT) print("quantum_qubit_param_type.qubit_pole=" + str(qubit_pole)) e_ops = [sigmax(), sigmay(), sigmaz()] if (qubit_pole == 1.0): Z = sigmaz() else: Z = -sigmaz() if (qubit_angle == 0.0): Q = Z elif (qubit_angle > 0.0): Q = sigmax() * self.angle_converter(qubit_angle) Q = Q + Z elif (): Q = sigmax() * self.angle_converter(-qubit_angle) Q = Q + (-Z) # self._block_view.clear() self._block_view.add_vectors(expect(Q.unit(), e_ops)) self._block_view.make_sphere() self._block_view.show()
def extract_pdu_header(header): d = pmt.to_long(pmt.dict_ref(header, pmt.intern('dest_id'), pmt.PMT_NIL)) s = pmt.to_long(pmt.dict_ref(header, pmt.intern('src_id'), pmt.PMT_NIL)) f = pmt.to_long(pmt.dict_ref(header, pmt.intern('frame_num'), pmt.PMT_NIL)) c = pmt.dict_ref(header, pmt.intern('checksum'), pmt.PMT_NIL) if pmt.is_u8vector(c): c = pmt_u8vector_to_ndarray(c) elif pmt.eq(c, pmt.PMT_T): c = True else: c = False return d, s, f, c
def test_002_normal(self): tnow = time.time() in_data = [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1 ] meta = pmt.dict_add(pmt.make_dict(), pmt.intern('wall_clock_time'), pmt.from_double(tnow - 10)) in_pdu = pmt.cons(meta, pmt.init_c32vector(len(in_data), in_data)) e_data = [ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1 ] e_meta = pmt.dict_add(pmt.make_dict(), pmt.intern('wall_clock_time'), pmt.from_double(tnow)) e_pdu = pmt.cons(e_meta, pmt.init_c32vector(len(e_data), e_data)) # set up fg self.tb.start() time.sleep(.001) self.emitter.emit(in_pdu) time.sleep(.01) self.tb.stop() self.tb.wait() # check data self.assertEqual(1, self.debug.num_messages()) #print("test_002_normal2:") #print("pdu expected: " + repr(pmt.car(e_pdu))) #print("pdu got: " + repr(pmt.car(self.debug.get_message(0)))) #print("data expected: " + repr(pmt.to_python(pmt.cdr(e_pdu)))) #print("data got: " + repr(pmt.to_python(pmt.cdr(self.debug.get_message(0))))) #print a_meta = pmt.car(self.debug.get_message(0)) time_tag = pmt.dict_ref(a_meta, pmt.intern("wall_clock_time"), pmt.PMT_NIL) if not pmt.eqv(time_tag, pmt.PMT_NIL): self.assertAlmostEqual(tnow, pmt.to_double(time_tag), delta=60) else: self.assertTrue(False) delta_tag = pmt.dict_ref(a_meta, pmt.intern("time_delta_ms"), pmt.PMT_NIL) if not pmt.eqv(delta_tag, pmt.PMT_NIL): self.assertAlmostEqual(10000, pmt.to_double(delta_tag), delta=10) else: self.assertTrue(False)
def dict_from_pdu(self, pdu): # build a simple dictionary out of burst metadata meta = pmt.car(pdu) burst_dict = {} burst_id = -1 try: burst_id = pmt.to_uint64(pmt.dict_ref(meta, self.pmt_burst_id, pmt.PMT_NIL)) burst_dict["start"] = pmt.to_uint64(pmt.dict_ref(meta, self.pmt_start_offset, pmt.PMT_NIL)) burst_dict["end"] = pmt.to_uint64(pmt.dict_ref(meta, self.pmt_end_offset, pmt.PMT_NIL)) burst_dict["rel_cf"] = pmt.to_float(pmt.dict_ref(meta, self.pmt_relative_frequency, pmt.PMT_NIL)) burst_dict["bw"] = pmt.to_float(pmt.dict_ref(meta, self.pmt_bandwidth, pmt.PMT_NIL)) except Exception as e: print(f"malformed burst (red) in the jpeg_convertor, {e}") return None, {} return burst_id, burst_dict
def test_packet_parse_default(self): ac = packet_utils.default_access_code length = '0000000000000001' hdr_format_1bps = digital.header_format_default(ac, 0) hdr_format_4bps = digital.header_format_default(ac, 0, 4) ac_bits = [int(x) & 1 for x in ac] length_bits = [int(x) & 1 for x in length] header_bits = ac_bits + length_bits + length_bits src_hdr = blocks.vector_source_b(header_bits) parser_1bps = digital.protocol_parser_b(hdr_format_1bps) parser_4bps = digital.protocol_parser_b(hdr_format_4bps) snk_hdr_1bps = blocks.message_debug() snk_hdr_4bps = blocks.message_debug() self.tb.connect(src_hdr, parser_1bps) self.tb.connect(src_hdr, parser_4bps) self.tb.msg_connect(parser_1bps, 'info', snk_hdr_1bps, 'store') self.tb.msg_connect(parser_4bps, 'info', snk_hdr_4bps, 'store') self.tb.start() while (snk_hdr_1bps.num_messages() < 1) or (snk_hdr_4bps.num_messages() < 1): time.sleep(0.1) self.tb.stop() self.tb.wait() result_1bps = snk_hdr_1bps.get_message(0) result_4bps = snk_hdr_4bps.get_message(0) self.assertTrue( pmt.dict_has_key(result_1bps, pmt.intern('payload symbols'))) self.assertEqual( pmt.to_long( pmt.dict_ref(result_1bps, pmt.intern('payload symbols'), pmt.PMT_F)), 8) self.assertTrue( pmt.dict_has_key(result_4bps, pmt.intern('payload symbols'))) self.assertEqual( pmt.to_long( pmt.dict_ref(result_4bps, pmt.intern('payload symbols'), pmt.PMT_F)), 2)
def test_001_t (self): # set up fg self.tb.start() # Create N messages with an id field p = pmt.make_dict() num_msgs = 20 for i in range(num_msgs): pc = pmt.dict_add(p,pmt.intern("id"), pmt.from_uint64(i)) self.emitter.emit(pc) # Sleep for a little bit to let the messages finish propagating time.sleep(.05) self.tb.stop() self.tb.wait() msg_count = 0 for i in range(self.num_paths): target = i msg_count += self.debug[i].num_messages() for m in range(self.debug[i].num_messages()): msg = self.debug[i].get_message(m) msg_id = pmt.to_uint64(pmt.dict_ref(msg, pmt.intern("id"), pmt.PMT_NIL)) assert(msg_id == target and msg_id < num_msgs) target += self.num_paths assert(msg_count == num_msgs)
def test_005_two_sobs_misaligned (self): # Two SOB tags and the SOB-to-EOB length is not aligned self.tb = gr.top_block () start_time = 0.1 sob_tag = gr.tag_utils.python_to_tag((34, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) sob_tag2 = gr.tag_utils.python_to_tag((35, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) eob_tag = gr.tag_utils.python_to_tag((34+(8*31), pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) vs = blocks.vector_source_s(range(1350), False, 1, [sob_tag, sob_tag2, eob_tag]) #vs = blocks.vector_source_s(range(350), False, 1, [sob_tag, eob_tag]) t2p = pdu_utils.tags_to_pdu_s(pmt.intern('SOB'), pmt.intern('EOB'), 1024, 512000, ([]), False, 0, start_time) t2p.set_eob_parameters(8, 0) dbg = blocks.message_debug() self.tb.connect(vs, t2p) self.tb.msg_connect((t2p, 'pdu_out'), (dbg, 'store')) expected_vec = pmt.init_s16vector((8*31), list(range(35,34+(8*31))) + [0]) expected_time = start_time + (35 / 512000.0) self.tb.run () self.assertEqual(dbg.num_messages(), 1) #print "got ", dbg.get_message(0) #print "expected", expected_vec #print "len is {}".format(len(pmt.to_python(pmt.cdr(dbg.get_message(0))))) self.assertTrue(pmt.equal(pmt.cdr(dbg.get_message(0)), expected_vec)) time_tuple1 = pmt.dict_ref(pmt.car(dbg.get_message(0)), pmt.intern("burst_time"), pmt.PMT_NIL) self.assertAlmostEqual(pmt.to_uint64(pmt.tuple_ref(time_tuple1,0)) + pmt.to_double(pmt.tuple_ref(time_tuple1,1)), expected_time) self.tb = None
def test_003_update_time(self): # This test checks that we can update the hardware time self.tb.start() time.sleep(.01) t0 = .2 self.emitter.emit(self.timemsg(t0, "pair")) time.sleep(.01) start_time = .16 self.utag.update_tags(self.makeTimeDict(start_time)) for i in range(15): if self.msg_dbg.num_messages() == 1: break time.sleep(0.02) # DO NOT call wait!!!! It won't return because the emitter block doesn't have any inputs. self.tb.stop() time.sleep(.01) tag = self.utag.last_tag() sample = pmt.to_uint64( pmt.dict_ref(tag, pmt.intern("rx_sample"), pmt.PMT_NIL)) if (self.msg_dbg.num_messages() != 1): raise Exception("Did not send required messages") self.checkmsgtime(self.msg_dbg.get_message(0), t0, (t0 - start_time) * self.rate + sample)
def checkmsgtime(self, msg, expected_time, expected_sample): sample = pmt.to_uint64(pmt.dict_ref(msg, self.skey, pmt.PMT_NIL)) trig = pmt.dict_ref(msg, self.tkey, pmt.PMT_NIL) trig_int, trig_frac = pmt.to_uint64(pmt.car(trig)), pmt.to_double( pmt.cdr(trig)) trig_time = trig_int + trig_frac self.assertAlmostEqual( float(sample) / self.rate, float(expected_sample) / self.rate, 3, "Incorrect Sample from message: expected {}, received {}".format( expected_sample, sample)) self.assertAlmostEqual( trig_time, expected_time, 3, "Incorrect interrupt time from message: expected {}, received {}". format(expected_time, trig_time))
def test_001_t(self): msg = u"Sample message for frame formatter Yihhaaa" message = string_to_int_list(msg) payload = get_pdu_payload(message) meta = pmt.make_dict() pdu = pmt.cons(meta, payload) formatter = latency.pdu_time_stamper("time", "pdu_timestamp_debug") dbg = blocks.message_debug() self.tb.msg_connect(formatter, "PDUout", dbg, "store") self.tb.msg_connect(formatter, "PDUout", dbg, "print_pdu") self.tb.start() # eww, what's that smell? formatter.to_basic_block()._post(pmt.intern("PDUin"), pdu) while dbg.num_messages() < 1: pass self.tb.stop() self.tb.wait() result_msg = dbg.get_message(0) # print(result_msg) print('finished test') # print(result_msg) meta = pmt.car(result_msg) # bits = pmt.cdr(result_msg) print(meta) t = pmt.dict_ref(meta, pmt.intern('time'), pmt.PMT_NIL) self.assertFalse(t == pmt.PMT_NIL) print(t)
def test_002_secondSOB(self): self.tb = gr.top_block() start_time = 4.999999999 sob_tag = gr.tag_utils.python_to_tag( (34, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) sob_tag2 = gr.tag_utils.python_to_tag( (51, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) eob_tag = gr.tag_utils.python_to_tag( (51 + (8 * 26), pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) vs = blocks.vector_source_s(range(350), False, 1, [sob_tag, sob_tag2, eob_tag]) t2p = pdu_utils.tags_to_pdu_s(pmt.intern('SOB'), pmt.intern('EOB'), 1024, 460800, ([]), False, 0, start_time) t2p.set_eob_parameters(8, 0) dbg = blocks.message_debug() self.tb.connect(vs, t2p) self.tb.msg_connect((t2p, 'pdu_out'), (dbg, 'store')) expected_vec = pmt.init_s16vector((8 * 26), range(51, 51 + (8 * 26))) expected_time = start_time + (51 / 460800.0) self.tb.run() self.assertEqual(dbg.num_messages(), 1) self.assertTrue(pmt.equal(pmt.cdr(dbg.get_message(0)), expected_vec)) time_tuple1 = pmt.dict_ref(pmt.car(dbg.get_message(0)), pmt.intern("burst_time"), pmt.PMT_NIL) self.assertAlmostEqual( pmt.to_uint64(pmt.tuple_ref(time_tuple1, 0)) + pmt.to_double(pmt.tuple_ref(time_tuple1, 1)), expected_time) self.tb = None
def test_007_max_pdu_size_SOBs (self): # two SOB tags exactly max_pdu_size samples apart self.tb = gr.top_block () start_time = 0.1 max_size = 100 sob_tag = gr.tag_utils.python_to_tag((10, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) sob_tag3 = gr.tag_utils.python_to_tag((10+max_size, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) vs = blocks.vector_source_s(range(1350), False, 1, [sob_tag, sob_tag3]) t2p = pdu_utils.tags_to_pdu_s(pmt.intern('SOB'), pmt.intern('EOB'), 1024, 512000, ([]), False, 0, start_time) t2p.set_eob_parameters(10, 0) t2p.set_max_pdu_size(max_size) dbg = blocks.message_debug() self.tb.connect(vs, t2p) self.tb.msg_connect((t2p, 'pdu_out'), (dbg, 'store')) expected_vec = pmt.init_s16vector((max_size), range(10,10+max_size)) expected_time = start_time + (10 / 512000.0) self.tb.run () # assertions for the first PDU only, second PDU will exist self.assertEqual(dbg.num_messages(), 2) #print "got ", dbg.get_message(0) #print "expected", expected_vec self.assertTrue(pmt.equal(pmt.cdr(dbg.get_message(0)), expected_vec)) time_tuple1 = pmt.dict_ref(pmt.car(dbg.get_message(0)), pmt.intern("burst_time"), pmt.PMT_NIL) self.assertAlmostEqual(pmt.to_uint64(pmt.tuple_ref(time_tuple1,0)) + pmt.to_double(pmt.tuple_ref(time_tuple1,1)), expected_time) self.tb = None
def process_fn_time_reference(self, msg): time_hint = pmt.to_python( pmt.dict_ref(msg, pmt.intern("time_hint"), pmt.PMT_NIL)) fn_time = pmt.to_python( pmt.dict_ref(msg, pmt.intern("fn_time"), pmt.PMT_NIL)) if time_hint is not None: self.time_hint = time_hint elif fn_time is not None: self.fn_ref = fn_time[0][0] self.ts = fn_time[0][1] full = fn_time[1][0] frac = fn_time[1][1] self.time_ref = full + frac self.time_hint = self.time_ref
def handler(self, msg): # is pair() will pass both dictionaries and pairs if not pmt.is_pair(msg): return try: # will fail if msg is not a dictionary or pdu fpmt = pmt.dict_ref(msg, self.filename_tag, pmt.PMT_NIL) except: return if pmt.equal(fpmt, pmt.PMT_NIL): return fname = pmt.symbol_to_string(fpmt) print "received file {}".format(fname) with self.mutex: self.file_queue.append(fname) if self.copy: self.copy_queue.append(fname) if len(self.file_queue) > self.nfiles_max: oldest = self.file_queue.popleft() self.delete(oldest)
def test_monte_carlo(self): emitter = pdu_utils.message_emitter() clock_rec = pdu_utils.pdu_clock_recovery(True) msg_debug = blocks.message_debug() # make connections self.tb.msg_connect((emitter, 'msg'), (clock_rec, 'pdu_in')) self.tb.msg_connect((clock_rec, 'pdu_out'), (msg_debug, 'store')) # run self.tb.start() time.sleep(.05) # generate and emit for i in range(100): n_symbols = 100 sps = 8 noise_power = 0.02 * i original_bits = np.random.randint(0, 2, n_symbols) original_samples = original_bits * 2 - 1 sample_rate = 1e6 symbol_rate = sample_rate / sps data = np.repeat(original_samples, sps) + ( np.random.rand(n_symbols * sps) * np.sqrt(noise_power)) meta = pmt.make_dict() meta = pmt.dict_add(meta, self.pmt_sample_rate, pmt.from_double(1e6)) vector = pmt.init_f32vector(len(data), data) emitter.emit(pmt.cons(meta, vector)) time.sleep(.05) result = msg_debug.get_message(i) result_meta = pmt.car(result) result_vector = pmt.to_python(pmt.cdr(result)) n_errors = sum(original_bits[:len(result_vector)] ^ result_vector[:len(original_bits)]) result_rate = pmt.to_double( pmt.dict_ref(result_meta, self.pmt_symbol_rate, pmt.PMT_NIL)) #print("result is ", result_rate) #print("we expected ", symbol_rate) #print("result vector is", result_vector) #print("we expected ", original_bits) #print("num errors", n_errors) # assert some stuff if n_errors != 0: print("got bad data", i) if (result_rate - symbol_rate) > 100: print("got bad rate", i) # shut down self.tb.stop() self.tb.wait() self.assertTrue(True)
def test_timing(self): self.tb.start() self.emitter.emit(pmt.intern("BAD PDU")) time.sleep(.01) self.emitter.emit(pmt.cons(pmt.make_dict(), pmt.init_u8vector(1, [0]))) time.sleep(1.0) self.emitter.emit(pmt.cons(pmt.make_dict(), pmt.init_u8vector(1, [0]))) time.sleep(.05) self.tb.stop() self.tb.wait() t0 = pmt.to_double(pmt.dict_ref(pmt.car(self.debug.get_message(0)), pmt.intern("wall_clock_time"), pmt.from_double(0.0))) t1 = pmt.to_double(pmt.dict_ref(pmt.car(self.debug.get_message(1)), pmt.intern("wall_clock_time"), pmt.from_double(0.0))) self.assertTrue(((t1 - t0) - 1) < 0.05)
def test_coerce(self): samp_rate = 1e6 freq_offset = -400e3 center_freq = 911e6 # blocks self.emitter = pdu_utils.message_emitter() self.cf = fhss_utils.cf_estimate(fhss_utils.COERCE, [x * 1e6 for x in range(900, 930)]) self.debug = blocks.message_debug() # connections self.tb.msg_connect((self.emitter, 'msg'), (self.cf, 'in')) self.tb.msg_connect((self.cf, 'out'), (self.debug, 'store')) # data in_data = (1 + 0j, ) * 2048 i_vec = pmt.init_c32vector(len(in_data), in_data) out_data = np.exp(1j * np.arange(0, 2 * np.pi * (freq_offset / samp_rate * len(in_data)), 2 * np.pi * (freq_offset / samp_rate), dtype=np.complex64)) e_vec = pmt.init_c32vector(len(out_data), out_data.tolist( )) # pmt doesn't play nice with numpy sometimes, convert to list meta = pmt.make_dict() meta = pmt.dict_add(meta, pmt.intern("sample_rate"), pmt.from_float(samp_rate)) meta = pmt.dict_add(meta, pmt.intern("center_frequency"), pmt.from_float(center_freq + freq_offset)) in_pdu = pmt.cons(meta, i_vec) e_pdu = pmt.cons(meta, e_vec) # flowgraph self.tb.start() time.sleep(.001) self.emitter.emit(in_pdu) time.sleep(.01) self.tb.stop() self.tb.wait() # parse output #print "got ", list(pmt.to_python(pmt.cdr(self.debug.get_message(0)))) #print "got ", self.debug.get_message(0) rcv = self.debug.get_message(0) rcv_meta = pmt.car(rcv) rcv_data = pmt.cdr(rcv) rcv_cf = pmt.dict_ref(rcv_meta, pmt.intern("center_frequency"), pmt.PMT_NIL) # asserts self.assertComplexTuplesAlmostEqual( tuple(pmt.c32vector_elements(rcv_data)), tuple(out_data), 2) self.assertTrue(pmt.equal(rcv_cf, pmt.from_float(911e6)))
def write_data(self, msg): snr = pmt.f64vector_elements( pmt.dict_ref(msg, pmt.intern("snr"), pmt.make_vector(0, pmt.from_long(0)))) encoding = pmt.s32vector_elements( pmt.dict_ref(msg, pmt.intern("encoding"), pmt.make_vector(0, pmt.from_long(0)))) puncturing = pmt.to_long( pmt.dict_ref(msg, pmt.intern("puncturing"), pmt.from_long(-1))) time_now = time() * 1000 delay = str(time_now - self.last_time) self.last_time = time_now snr_str = "" enc_str = "" for i in range(len(snr)): snr_str += str(snr[i]) enc_str += str(encoding[i]) + ", " if i != len(snr) - 1: snr_str += ", " enc_str += str(puncturing) if self.snr_file != "": f_snr = open(self.snr_file, 'a') f_snr.write(snr_str + '\n') f_snr.close() if self.enc_file != "": f_enc = open(self.enc_file, 'a') f_enc.write(enc_str + '\n') f_enc.close() if self.delay_file != "": f_delay = open(self.delay_file, 'a') f_delay.write(delay + '\n') f_delay.close() if self.debug: print("SNR: " + snr_str) print("Encoding: " + enc_str) print("Delay in millis: " + delay)
def test_packet_parse_default(self): ac = packet_utils.default_access_code length = '0000000000000001' hdr_format_1bps = digital.header_format_default(ac, 0) hdr_format_4bps = digital.header_format_default(ac, 0, 4) ac_bits = [int(x) & 1 for x in ac] length_bits = [int(x) & 1 for x in length] header_bits = ac_bits + length_bits + length_bits src_hdr = blocks.vector_source_b(header_bits) parser_1bps = digital.protocol_parser_b(hdr_format_1bps) parser_4bps = digital.protocol_parser_b(hdr_format_4bps) snk_hdr_1bps = blocks.message_debug() snk_hdr_4bps = blocks.message_debug() self.tb.connect(src_hdr, parser_1bps) self.tb.connect(src_hdr, parser_4bps) self.tb.msg_connect(parser_1bps, 'info', snk_hdr_1bps, 'store') self.tb.msg_connect(parser_4bps, 'info', snk_hdr_4bps, 'store') self.tb.start() while (snk_hdr_1bps.num_messages() < 1) and (snk_hdr_4bps.num_messages() < 1): time.sleep(0.1) self.tb.stop() self.tb.wait() result_1bps = snk_hdr_1bps.get_message(0) result_4bps = snk_hdr_4bps.get_message(0) self.assertTrue(pmt.dict_has_key( result_1bps, pmt.intern('payload symbols'))) self.assertEqual(pmt.to_long(pmt.dict_ref( result_1bps, pmt.intern('payload symbols'), pmt.PMT_F)), 8) self.assertTrue(pmt.dict_has_key( result_4bps, pmt.intern('payload symbols'))) self.assertEqual(pmt.to_long(pmt.dict_ref( result_4bps, pmt.intern('payload symbols'), pmt.PMT_F)), 2)
def handler(self, msg): # get input meta = pmt.car(msg); samples = pmt.cdr(msg); # ensure we have a dictionary assert(pmt.is_dict(meta)) #print pmt.to_python(pmt.dict_keys(meta)); # get the value from dict and publish it val = pmt.dict_ref(meta, self.key, pmt.PMT_NIL) self.message_port_pub(self.outport, val);
def handler(self, msg): # get input meta = pmt.car(msg) samples = pmt.cdr(msg) # ensure we have a dictionary assert (pmt.is_dict(meta)) #print pmt.to_python(pmt.dict_keys(meta)); # get the value from dict and publish it val = pmt.dict_ref(meta, self.key, pmt.PMT_NIL) self.message_port_pub(self.outport, val)
def test_rms(self): self.emitter = pdu_utils.message_emitter() self.cf = fhss_utils.cf_estimate(fhss_utils.RMS, []) self.debug = blocks.message_debug() self.tb.msg_connect((self.emitter, 'msg'), (self.cf, 'in')) self.tb.msg_connect((self.cf, 'out'), (self.debug, 'store')) # original data in_data = np.exp(1j * np.array(np.linspace(0, 1 * np.pi * .02, 20))) i_vec = pmt.init_c32vector(len(in_data), in_data) out_data = [(1 + 0j), (0.9999966 + 0.0026077442j), (0.9999864 + 0.0052154697j), (0.9999694 + 0.007823161j), (0.99994564 + 0.010430798j), (0.99991506 + 0.013038365j), (0.99987763 + 0.015645843j), (0.99983346 + 0.018253215j), (0.99978244 + 0.020860463j), (0.9997247 + 0.023467569j), (0.99966 + 0.026074518j), (0.99958867 + 0.028681284j), (0.9995105 + 0.03128786j), (0.9994256 + 0.033894222j), (0.99933374 + 0.03650035j), (0.99923515 + 0.03910623j), (0.9991298 + 0.04171185j), (0.99901766 + 0.044317182j), (0.9988987 + 0.046922214j), (0.9987729 + 0.04952693j)] e_vec = pmt.init_c32vector(len(out_data), out_data) meta = pmt.make_dict() meta = pmt.dict_add(meta, pmt.intern("sample_rate"), pmt.from_float(1e6)) meta = pmt.dict_add(meta, pmt.intern("center_frequency"), pmt.from_float(910.6e6)) in_pdu = pmt.cons(meta, i_vec) e_pdu = pmt.cons(meta, e_vec) self.tb.start() time.sleep(.001) self.emitter.emit(in_pdu) time.sleep(.01) self.tb.stop() self.tb.wait() # parse output #print("got ", list(pmt.to_python(pmt.cdr(self.debug.get_message(0))))) #print("got ", self.debug.get_message(0)) rcv = self.debug.get_message(0) rcv_meta = pmt.car(rcv) rcv_data = pmt.cdr(rcv) rcv_cf = pmt.to_double( pmt.dict_ref(rcv_meta, pmt.intern("center_frequency"), pmt.PMT_NIL)) # asserts self.assertComplexTuplesAlmostEqual( tuple(pmt.c32vector_elements(rcv_data)), tuple(out_data), 2) self.assertTrue(abs(rcv_cf - 910.6001e6) < 100)
def update_timestamp(hdr,seg_size): if pmt.dict_has_key(hdr, pmt.string_to_symbol("rx_time")): r = pmt.dict_ref(hdr, pmt.string_to_symbol("rx_time"), pmt.PMT_NIL) secs = pmt.tuple_ref(r, 0) fracs = pmt.tuple_ref(r, 1) secs = float(pmt.to_uint64(secs)) fracs = pmt.to_double(fracs) t = secs + fracs else: sys.stderr.write("Could not find key 'time': \ invalid or corrupt data file.\n") sys.exit(1) new_hdr = pmt.dict_delete(hdr, pmt.intern("rx_time")) if pmt.dict_has_key(hdr, pmt.intern("rx_rate")): r = pmt.dict_ref(hdr, pmt.intern("rx_rate"), pmt.PMT_NIL) rate = pmt.to_double(r) new_t = t + float(seg_size)/rate new_secs = long(new_t) new_fracs = new_t - new_secs time_val = pmt.make_tuple(pmt.from_uint64(new_secs), pmt.from_double(new_fracs)) new_hdr = pmt.dict_add(new_hdr, pmt.intern("rx_time"), time_val) return new_hdr
def handle_msg(self, msg): if pmt.dict_has_key(msg, pmt.to_pmt("log_msg")): log_msg = pmt.dict_ref(msg, pmt.to_pmt("log_msg"), pmt.PMT_NIL) self.console_msg = pmt.to_python(log_msg) self.emit(QtCore.SIGNAL("console_update"))
def parse_header(p, VERBOSE=False): dump = pmt.PMT_NIL info = dict() if(pmt.is_dict(p) is False): sys.stderr.write("Header is not a PMT dictionary: invalid or corrupt data file.\n") sys.exit(1) # GET FILE FORMAT VERSION NUMBER if(pmt.dict_has_key(p, pmt.string_to_symbol("version"))): r = pmt.dict_ref(p, pmt.string_to_symbol("version"), dump) version = pmt.to_long(r) if(VERBOSE): print("Version Number: {0}".format(version)) else: sys.stderr.write("Could not find key 'version': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT SAMPLE RATE if(pmt.dict_has_key(p, pmt.string_to_symbol("rx_rate"))): r = pmt.dict_ref(p, pmt.string_to_symbol("rx_rate"), dump) samp_rate = pmt.to_double(r) info["rx_rate"] = samp_rate if(VERBOSE): print("Sample Rate: {0:.2f} sps".format(samp_rate)) else: sys.stderr.write("Could not find key 'sr': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT TIME STAMP if(pmt.dict_has_key(p, pmt.string_to_symbol("rx_time"))): r = pmt.dict_ref(p, pmt.string_to_symbol("rx_time"), dump) secs = pmt.tuple_ref(r, 0) fracs = pmt.tuple_ref(r, 1) secs = float(pmt.to_uint64(secs)) fracs = pmt.to_double(fracs) t = secs + fracs info["rx_time"] = t if(VERBOSE): print("Seconds: {0:.6f}".format(t)) else: sys.stderr.write("Could not find key 'time': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT ITEM SIZE if(pmt.dict_has_key(p, pmt.string_to_symbol("size"))): r = pmt.dict_ref(p, pmt.string_to_symbol("size"), dump) dsize = pmt.to_long(r) info["size"] = dsize if(VERBOSE): print("Item size: {0}".format(dsize)) else: sys.stderr.write("Could not find key 'size': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT DATA TYPE if(pmt.dict_has_key(p, pmt.string_to_symbol("type"))): r = pmt.dict_ref(p, pmt.string_to_symbol("type"), dump) dtype = pmt.to_long(r) stype = ftype_to_string[dtype] info["type"] = stype if(VERBOSE): print("Data Type: {0} ({1})".format(stype, dtype)) else: sys.stderr.write("Could not find key 'type': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT COMPLEX if(pmt.dict_has_key(p, pmt.string_to_symbol("cplx"))): r = pmt.dict_ref(p, pmt.string_to_symbol("cplx"), dump) cplx = pmt.to_bool(r) info["cplx"] = cplx if(VERBOSE): print("Complex? {0}".format(cplx)) else: sys.stderr.write("Could not find key 'cplx': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT WHERE CURRENT SEGMENT STARTS if(pmt.dict_has_key(p, pmt.string_to_symbol("strt"))): r = pmt.dict_ref(p, pmt.string_to_symbol("strt"), dump) seg_start = pmt.to_uint64(r) info["hdr_len"] = seg_start info["extra_len"] = seg_start - HEADER_LENGTH info["has_extra"] = info["extra_len"] > 0 if(VERBOSE): print("Header Length: {0} bytes".format(info["hdr_len"])) print("Extra Length: {0}".format((info["extra_len"]))) print("Extra Header? {0}".format(info["has_extra"])) else: sys.stderr.write("Could not find key 'strt': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT SIZE OF DATA if(pmt.dict_has_key(p, pmt.string_to_symbol("bytes"))): r = pmt.dict_ref(p, pmt.string_to_symbol("bytes"), dump) nbytes = pmt.to_uint64(r) nitems = nbytes / dsize info["nitems"] = nitems info["nbytes"] = nbytes if(VERBOSE): print("Size of Data: {0} bytes".format(nbytes)) print(" {0} items".format(nitems)) else: sys.stderr.write("Could not find key 'size': invalid or corrupt data file.\n") sys.exit(1) return info
def parse_header(p, VERBOSE=False): dump = pmt.PMT_NIL info = dict() if(pmt.is_dict(p) is False): sys.stderr.write("Header is not a PMT dictionary: invalid or corrupt data file.\n") sys.exit(1) # GET FILE FORMAT VERSION NUMBER if(pmt.dict_has_key(p, pmt.string_to_symbol("version"))): r = pmt.dict_ref(p, pmt.string_to_symbol("version"), dump) version = pmt.to_long(r) if(VERBOSE): print "Version Number: {0}".format(version) else: sys.stderr.write("Could not find key 'version': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT SAMPLE RATE if(pmt.dict_has_key(p, pmt.string_to_symbol("rx_rate"))): r = pmt.dict_ref(p, pmt.string_to_symbol("rx_rate"), dump) samp_rate = pmt.to_double(r) info["rx_rate"] = samp_rate if(VERBOSE): print "Sample Rate: " + eng_notation.num_to_str(samp_rate) + "SPS" else: sys.stderr.write("Could not find key 'sr': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT TIME STAMP if(pmt.dict_has_key(p, pmt.string_to_symbol("rx_time"))): r = pmt.dict_ref(p, pmt.string_to_symbol("rx_time"), dump) secs = pmt.tuple_ref(r, 0) fracs = pmt.tuple_ref(r, 1) secs = float(pmt.to_uint64(secs)) fracs = pmt.to_double(fracs) t = secs + fracs info["rx_time"] = t if(VERBOSE): time = datetime.fromtimestamp(t).strftime('%m/%d/%Y %H:%M:%S') print "Timestamp (Unix Epoch): " + time print "Integer Seconds: " + repr(secs) print "Fractional Seconds: " + repr(fracs) #print "Linux Epoch: {0:.6f}".format(t) + " Seconds" else: sys.stderr.write("Could not find key 'time': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT ITEM SIZE if(pmt.dict_has_key(p, pmt.string_to_symbol("size"))): r = pmt.dict_ref(p, pmt.string_to_symbol("size"), dump) dsize = pmt.to_long(r) info["size"] = dsize if(VERBOSE): print "Item Size: " + eng_notation.num_to_str(dsize) + " Bytes" else: sys.stderr.write("Could not find key 'size': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT DATA TYPE if(pmt.dict_has_key(p, pmt.string_to_symbol("type"))): r = pmt.dict_ref(p, pmt.string_to_symbol("type"), dump) dtype = pmt.to_long(r) stype = ftype_to_string[dtype] info["type"] = stype if(VERBOSE): print "Data Type: {0} ({1})".format(stype, dtype) else: sys.stderr.write("Could not find key 'type': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT COMPLEX if(pmt.dict_has_key(p, pmt.string_to_symbol("cplx"))): r = pmt.dict_ref(p, pmt.string_to_symbol("cplx"), dump) #global cplx cplx = pmt.to_bool(r) info["cplx"] = cplx if(VERBOSE): print "Complex? {0}".format(cplx) global vecchk global tsize #print cplx #print dtype #print dsize if(cplx==False): if(dtype==0): tsize=1 elif(dtype==1): tsize=4 elif(dtype==2): tsize=4 elif(dtype==3): tsize=4 elif(dtype==5): tsize=4 elif(dtype==6): tsize=8 else: tsize=64 #print tsize vecchk = dsize/tsize #print vecchk if(vecchk>1): print "The data is a vector containing {0} elements.".format(vecchk) else: print "The data is not a vector." '''else: sys.stderr.write("Could not find key 'cplx': invalid or corrupt data file.\n") sys.exit(1) ''' # EXTRACT WHERE CURRENT SEGMENT STARTS if(pmt.dict_has_key(p, pmt.string_to_symbol("strt"))): r = pmt.dict_ref(p, pmt.string_to_symbol("strt"), dump) seg_start = pmt.to_uint64(r) info["hdr_len"] = seg_start info["extra_len"] = seg_start - HEADER_LENGTH info["has_extra"] = info["extra_len"] > 0 if(VERBOSE): print "Header Length: {0} bytes".format(info["hdr_len"]) print "Extra Length: {0}".format((info["extra_len"])) print "Extra Header? {0}".format(info["has_extra"]) else: sys.stderr.write("Could not find key 'strt': invalid or corrupt data file.\n") sys.exit(1) # EXTRACT SIZE OF DATA if(pmt.dict_has_key(p, pmt.string_to_symbol("bytes"))): r = pmt.dict_ref(p, pmt.string_to_symbol("bytes"), dump) nbytes = pmt.to_uint64(r) nitems = nbytes/dsize info["nitems"] = nitems info["nbytes"] = nbytes #info["types"] = types if(VERBOSE): #print "Size of Data: {0:2.1e} bytes".format(nbytes) print "Segment Size (bytes): " + eng_notation.num_to_str(nbytes) #print " {0:2.1e} items".format(nitems) print "Segment Size (items): " + eng_notation.num_to_str(nitems) else: sys.stderr.write("Could not find key 'size': invalid or corrupt data file.\n") sys.exit(1) return info