Beispiel #1
0
    def handle_msg(self, msg_pmt):
        msg = pmt.cdr(msg_pmt)
        if not pmt.is_u8vector(msg):
            print "[ERROR] Received invalid message type. Expected u8vector"
            return

        if pmt.length(msg) + 2 > self.mtu:
            print "[ERROR] Transmitted frame is too long (%d bytes).  Cannot exceed %d bytes." % (pmt.length(msg), self.mtu - 2)
            return

        #length = struct.pack('h', pmt.length(msg))
        #print length, pmt.length(msg)

        buff = list()
        #buff.extend([x for x in length])
        #buff.extend(pmt.u8vector_elements(msg))
        length = pmt.length(msg)
        buff.append(length >> 8) # MSB
        buff.append(length & 0xFF) # LSB
        buff.extend(pmt.u8vector_elements(msg))

        pad_length = self.mtu - len(buff)
        if pad_length:
            buff.extend([self.pad_byte] * pad_length)

        if debug:
            print "Pushing a packet of length %d bytes" % length

        self.message_port_pub(pmt.intern('out'), pmt.cons(pmt.PMT_NIL, pmt.init_u8vector(len(buff), buff)))
Beispiel #2
0
    def handle_msg(self, msg_pmt):
        msg = pmt.cdr(msg_pmt)
        if not pmt.is_u8vector(msg):
            print "[ERROR] Received invalid message type. Expected u8vector"
            return

        if pmt.length(msg) > self.mtu:
            print "[ERROR] Received frame is too long (%d bytes).  Cannot exceed %d bytes." % (
                pmt.length(msg), self.mtu)
            return

        #print pmt.u8vector_elements(msg)[0:2]
        #length = struct.unpack('h', pmt.u8vector_elements(msg)[0:2])
        length_bytes = pmt.u8vector_elements(msg)[0:2]
        length = length_bytes[0] << 8 | length_bytes[1]
        #print length, pmt.length(msg)

        if length == 0:  # caught a Filler packet, drop it
            return

        buff = list()
        buff.extend(pmt.u8vector_elements(msg)[2:2 + length])
        #print buff

        # TODO: Check for pad byte if there are any

        #print pmt.length(buff)
        buff = array.array('B', buff)

        if debug:
            print "Received a packet of length %d bytes" % length

        self.message_port_pub(
            pmt.intern('out'),
            pmt.cons(pmt.PMT_NIL, pmt.init_u8vector(len(buff), buff)))
Beispiel #3
0
    def test_001_t(self):
        # set up fg
        test_len = 1024

        packet_len = test_len
        samp_rate = 2000

        center_freq = 1e9
        velocity = (5, 15, 20)

        src = radar.signal_generator_cw_c(packet_len, samp_rate, (0, 0), 1)
        head = blocks.head(8, test_len)
        sim = radar.static_target_simulator_cc(
            (10, 10, 10), velocity, (1e12, 1e12, 1e12), (0, 0, 0), (0, ),
            samp_rate, center_freq, 1, True, False)
        mult = blocks.multiply_cc()
        fft = radar.ts_fft_cc(packet_len)
        cfar = radar.os_cfar_c(samp_rate, 5, 0, 0.78, 10, True)
        est = radar.estimator_cw(center_freq)
        res1 = radar.print_results()
        res2 = radar.print_results()
        gate = radar.msg_gate(('velocity', 'bla'), (8, 8), (17, 17))
        debug1 = blocks.message_debug()
        debug2 = blocks.message_debug()

        self.tb.connect(src, head, (mult, 1))
        self.tb.connect(head, sim, (mult, 0))
        self.tb.connect(mult, fft, cfar)
        self.tb.msg_connect(cfar, 'Msg out', est, 'Msg in')
        self.tb.msg_connect(est, 'Msg out', res1, 'Msg in')
        self.tb.msg_connect(est, 'Msg out', debug1, 'store')
        self.tb.msg_connect(est, 'Msg out', gate, 'Msg in')
        self.tb.msg_connect(gate, 'Msg out', debug2, 'store')
        self.tb.msg_connect(gate, 'Msg out', res2, 'Msg in')

        self.tb.start()
        sleep(0.5)
        self.tb.stop()
        self.tb.wait()

        # check data
        msg1 = debug1.get_message(0)  # msg without gate
        msg2 = debug2.get_message(0)  # msg with gate
        self.assertEqual(
            "velocity", pmt.symbol_to_string(pmt.nth(0, (pmt.nth(
                1, msg1)))))  # check velocity message part (symbol), 1
        self.assertEqual(
            "velocity", pmt.symbol_to_string(pmt.nth(0, (pmt.nth(
                1, msg2)))))  # check velocity message part (symbol), 2
        self.assertEqual(pmt.length(pmt.nth(1, pmt.nth(1, msg1))),
                         3)  # check number of targets without gate
        self.assertEqual(pmt.length(pmt.nth(1, pmt.nth(1, msg2))),
                         1)  # check nubmer of targets with gate
        self.assertAlmostEqual(
            1, velocity[1] / pmt.f32vector_ref(pmt.nth(1,
                                                       (pmt.nth(1, msg2))), 0),
            1)  # check velocity value
Beispiel #4
0
    def test_000(self):
        # Just run some data through and make sure it doesn't puke.
        src_data = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

        src = pdu.pdu_to_tagged_stream(gr.types.byte_t)
        snk3 = pdu.tagged_stream_to_pdu(gr.types.byte_t)
        snk2 = blocks.vector_sink_b()
        snk = blocks.tag_debug(1, "test")
        snk.set_display(False)

        dbg = blocks.message_debug()

        # Test that the right number of ports exist.
        pi = snk3.message_ports_in()
        po = snk3.message_ports_out()
        # system port is defined automatically
        self.assertEqual(pmt.length(pi), 1)
        self.assertEqual(pmt.length(po), 1)

        self.tb.connect(src, snk)
        self.tb.connect(src, snk2)
        self.tb.connect(src, snk3)
        self.tb.msg_connect(snk3, "pdus", dbg, "store")

        # make our reference and message pmts
        port = pmt.intern("pdus")
        msg = pmt.cons(pmt.PMT_NIL, pmt.make_u8vector(16, 0xFF))

        # post the message
        src.to_basic_block()._post(port, msg)
        src.to_basic_block()._post(
            pmt.intern("system"), pmt.cons(pmt.intern("done"),
                                           pmt.from_long(1)))

        self.tb.start()
        self.tb.wait()

        # Get the vector of data from the vector sink
        result_data = snk2.data()

        # Get the vector of data from the message sink
        # Convert the message PMT as a pair into its vector
        result_msg = dbg.get_message(0)
        msg_vec = pmt.cdr(result_msg)
        # pmt.print(msg_vec)

        # Convert the PMT vector into a Python list
        msg_data = []
        for i in range(16):
            msg_data.append(pmt.u8vector_ref(msg_vec, i))

        actual_data = 16 * [
            0xFF,
        ]
        self.assertEqual(actual_data, list(result_data))
        self.assertEqual(actual_data, msg_data)
Beispiel #5
0
    def test_001_t(self):
        # set up fg
        test_len = 1024

        packet_len = test_len
        samp_rate = 2000

        center_freq = 1e9
        velocity = (5, 15, 20)

        src = radar.signal_generator_cw_c(packet_len, samp_rate, (0, 0), 1)
        head = blocks.head(8, test_len)
        sim = radar.static_target_simulator_cc(
            (10, 10, 10), velocity, (1e12, 1e12, 1e12), (0, 0, 0), (0,), samp_rate, center_freq, 1, True, False
        )
        mult = blocks.multiply_cc()
        fft = radar.ts_fft_cc(packet_len)
        cfar = radar.os_cfar_c(samp_rate, 5, 0, 0.78, 10, True)
        est = radar.estimator_cw(center_freq)
        res1 = radar.print_results()
        res2 = radar.print_results()
        gate = radar.msg_gate(("velocity", "bla"), (8, 8), (17, 17))
        debug1 = blocks.message_debug()
        debug2 = blocks.message_debug()

        self.tb.connect(src, head, (mult, 1))
        self.tb.connect(head, sim, (mult, 0))
        self.tb.connect(mult, fft, cfar)
        self.tb.msg_connect(cfar, "Msg out", est, "Msg in")
        self.tb.msg_connect(est, "Msg out", res1, "Msg in")
        self.tb.msg_connect(est, "Msg out", debug1, "store")
        self.tb.msg_connect(est, "Msg out", gate, "Msg in")
        self.tb.msg_connect(gate, "Msg out", debug2, "store")
        self.tb.msg_connect(gate, "Msg out", res2, "Msg in")

        self.tb.start()
        sleep(0.5)
        self.tb.stop()
        self.tb.wait()

        # check data
        msg1 = debug1.get_message(0)  # msg without gate
        msg2 = debug2.get_message(0)  # msg with gate
        self.assertEqual(
            "velocity", pmt.symbol_to_string(pmt.nth(0, (pmt.nth(1, msg1))))
        )  # check velocity message part (symbol), 1
        self.assertEqual(
            "velocity", pmt.symbol_to_string(pmt.nth(0, (pmt.nth(1, msg2))))
        )  # check velocity message part (symbol), 2
        self.assertEqual(pmt.length(pmt.nth(1, pmt.nth(1, msg1))), 3)  # check number of targets without gate
        self.assertEqual(pmt.length(pmt.nth(1, pmt.nth(1, msg2))), 1)  # check nubmer of targets with gate
        self.assertAlmostEqual(
            1, velocity[1] / pmt.f32vector_ref(pmt.nth(1, (pmt.nth(1, msg2))), 0), 1
        )  # check velocity value
Beispiel #6
0
    def test_000(self):
        # Just run some data through and make sure it doesn't puke.
        src_data = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

        src = blocks.pdu_to_tagged_stream(blocks.byte_t)
        snk3 = blocks.tagged_stream_to_pdu(blocks.byte_t)
        snk2 = blocks.vector_sink_b()
        snk = blocks.tag_debug(1, "test")
        snk.set_display(False)

        dbg = blocks.message_debug()

        # Test that the right number of ports exist.
        pi = snk3.message_ports_in()
        po = snk3.message_ports_out()
        self.assertEqual(pmt.length(pi), 0)
        self.assertEqual(pmt.length(po), 1)

        self.tb.connect(src, snk)
        self.tb.connect(src, snk2)
        self.tb.connect(src, snk3)
        self.tb.msg_connect(snk3, "pdus", dbg, "store")
        self.tb.start()

        # make our reference and message pmts
        port = pmt.intern("pdus")
        msg = pmt.cons( pmt.PMT_NIL, pmt.make_u8vector(16, 0xFF))

        # post the message
        src.to_basic_block()._post(port, msg) # eww, what's that smell?

        while dbg.num_messages() < 1:
            time.sleep(0.1)
        self.tb.stop()
        self.tb.wait()

        # Get the vector of data from the vector sink
        result_data = snk2.data()

        # Get the vector of data from the message sink
        # Convert the message PMT as a pair into its vector
        result_msg = dbg.get_message(0)
        msg_vec = pmt.cdr(result_msg)
        #pmt.print(msg_vec)

        # Convert the PMT vector into a Python list
        msg_data = []
        for i in xrange(16):
            msg_data.append(pmt.u8vector_ref(msg_vec, i))

        actual_data = 16*[0xFF,]
        self.assertEqual(actual_data, list(result_data))
        self.assertEqual(actual_data, msg_data)
Beispiel #7
0
    def msg_handler(self, p):

        length = pmt.length(p)

        for i in range(0,length):
           element = pmt.nth(i, p)

           key = pmt.nth(0, element)
           value = pmt.nth(1, element)

           if str(key) == "power":
               output = pmt.f32vector_elements(value)[0]


               output = 10 * math.log(output, 10)           
               output = pmt.make_f32vector(1, output)

               if i==0:
                   outpmt = pmt.list1(pmt.list2(pmt.string_to_symbol(str(key) + "_dB"), output))
               else:
                   outpmt = pmt.list_add(outpmt, pmt.list2(pmt.string_to_symbol(str(key) + "_dB"), output))



           output = pmt.nth(1, element)

           if i==0:
               outpmt = pmt.list1(pmt.list2(key, output))
           else:
               outpmt = pmt.list_add(outpmt, pmt.list2(key, output))

       
        self.message_port_pub(pmt.string_to_symbol("out"), outpmt)
    def test_001_t (self):
        src = analog.sig_source_c(32000, analog.GR_COS_WAVE,
                                  12500, 1)

        detector = inspector.signal_detector_cvf(32000,  1024,
                    firdes.WIN_BLACKMAN_hARRIS, -80, 0.6, False, 0.5, 0.0001)
        dst1 = blocks.null_sink(gr.sizeof_float*1024)
        dst2 = blocks.null_sink(gr.sizeof_float*1024)
        msg_dst = blocks.message_debug()
        self.tb.connect(src, detector)
        self.tb.connect((detector, 0), dst1)
        self.tb.connect((detector, 1), dst2)
        self.tb.msg_connect((detector, 'map_out'), (msg_dst, 'store'))
        self.tb.start()
        time.sleep(0.5)
        self.tb.stop()
        self.tb.wait()

        msg = msg_dst.get_message(1)
        res_vector = numpy.empty([0, 2])
        for i in range(pmt.length(msg)):
            row = pmt.vector_ref(msg, i)
            res_vector = numpy.vstack((res_vector, numpy.array(
                [pmt.f32vector_ref(row, 0), pmt.f32vector_ref(row, 1)]
            )))

        self.assertAlmostEqual(12500.0, res_vector[0][0], delta=100)
        self.assertAlmostEqual(0.0, res_vector[0][1], delta=200)
 def test_001_t (self):
     """ Simplest possible test: put in zeros, then header,
     then payload, trigger signal, try to demux.
     The return signal from the header parser is faked via _post()
     Add in some tags for fun.
     """
     n_zeros = 1
     header = (1, 2, 3)
     payload = tuple(range(5, 20))
     data_signal = (0,) * n_zeros + header + payload
     trigger_signal = [0,] * len(data_signal)
     trigger_signal[n_zeros] = 1
     # This is dropped:
     testtag1 = make_tag('tag1', 0, 0)
     # This goes on output 0, item 0:
     testtag2 = make_tag('tag2', 23, n_zeros)
     # This goes on output 0, item 2:
     testtag3 = make_tag('tag3', 42, n_zeros + len(header) - 1)
     # This goes on output 1, item 3:
     testtag4 = make_tag('tag4', 314, n_zeros + len(header) + 3)
     data_src = blocks.vector_source_f(
             data_signal,
             False,
             tags=(testtag1, testtag2, testtag3, testtag4)
     )
     trigger_src = blocks.vector_source_b(trigger_signal, False)
     hpd = digital.header_payload_demux(
         len(header), 1, 0, "frame_len", "detect", False, gr.sizeof_float
     )
     mock_header_demod = HeaderToMessageBlock(
             numpy.float32,
             len(header),
             [len(payload)]
     )
     self.assertEqual(pmt.length(hpd.message_ports_in()), 2) #extra system port defined for you
     payload_sink = blocks.vector_sink_f()
     header_sink = blocks.vector_sink_f()
     self.connect_all_blocks(data_src, trigger_src, hpd, mock_header_demod, payload_sink, header_sink)
     self.run_tb(payload_sink, len(payload), header_sink, len(header))
     self.assertEqual(header_sink.data(), header)
     self.assertEqual(payload_sink.data(), payload)
     ptags_header = []
     for tag in header_sink.tags():
         ptag = gr.tag_to_python(tag)
         ptags_header.append({'key': ptag.key, 'offset': ptag.offset})
     expected_tags_header = [
             {'key': 'tag2', 'offset': 0},
             {'key': 'tag3', 'offset': 2},
     ]
     self.assertEqual(expected_tags_header, ptags_header)
     ptags_payload = []
     for tag in payload_sink.tags():
         ptag = gr.tag_to_python(tag)
         ptags_payload.append({'key': ptag.key, 'offset': ptag.offset})
     expected_tags_payload = [
             {'key': 'frame_len', 'offset': 0},
             {'key': 'tag4', 'offset': 3},
     ]
     self.assertEqual(expected_tags_payload, ptags_payload)
 def test_001_t (self):
     """ Simplest possible test: put in zeros, then header,
     then payload, trigger signal, try to demux.
     The return signal from the header parser is faked via _post()
     Add in some tags for fun.
     """
     n_zeros = 1
     header = (1, 2, 3)
     payload = tuple(range(5, 20))
     data_signal = (0,) * n_zeros + header + payload
     trigger_signal = [0,] * len(data_signal)
     trigger_signal[n_zeros] = 1
     # This is dropped:
     testtag1 = make_tag('tag1', 0, 0)
     # This goes on output 0, item 0:
     testtag2 = make_tag('tag2', 23, n_zeros)
     # This goes on output 0, item 2:
     testtag3 = make_tag('tag3', 42, n_zeros + len(header) - 1)
     # This goes on output 1, item 3:
     testtag4 = make_tag('tag4', 314, n_zeros + len(header) + 3)
     data_src = blocks.vector_source_f(
             data_signal,
             False,
             tags=(testtag1, testtag2, testtag3, testtag4)
     )
     trigger_src = blocks.vector_source_b(trigger_signal, False)
     hpd = digital.header_payload_demux(
         len(header), 1, 0, "frame_len", "detect", False, gr.sizeof_float
     )
     mock_header_demod = HeaderToMessageBlock(
             numpy.float32,
             len(header),
             [len(payload)]
     )
     self.assertEqual(pmt.length(hpd.message_ports_in()), 2) #extra system port defined for you
     payload_sink = blocks.vector_sink_f()
     header_sink = blocks.vector_sink_f()
     self.connect_all_blocks(data_src, trigger_src, hpd, mock_header_demod, payload_sink, header_sink)
     self.run_tb(payload_sink, len(payload), header_sink, len(header))
     self.assertEqual(header_sink.data(), header)
     self.assertEqual(payload_sink.data(), payload)
     ptags_header = []
     for tag in header_sink.tags():
         ptag = gr.tag_to_python(tag)
         ptags_header.append({'key': ptag.key, 'offset': ptag.offset})
     expected_tags_header = [
             {'key': 'tag2', 'offset': 0},
             {'key': 'tag3', 'offset': 2},
     ]
     self.assertEqual(expected_tags_header, ptags_header)
     ptags_payload = []
     for tag in payload_sink.tags():
         ptag = gr.tag_to_python(tag)
         ptags_payload.append({'key': ptag.key, 'offset': ptag.offset})
     expected_tags_payload = [
             {'key': 'frame_len', 'offset': 0},
             {'key': 'tag4', 'offset': 3},
     ]
     self.assertEqual(expected_tags_payload, ptags_payload)
Beispiel #11
0
    def msg_handler(self, p):

        length = pmt.length(p)

        # iterate over all elements
        for i in range(0, length):
            element = pmt.nth(i, p)

            key = pmt.nth(0, element)
            value = pmt.nth(1, element)

            initial_phase = None

            # when we found the phase key
            if str(key) == "phase" and pmt.length(value) >= 1:
                # print "length of vector: ", pmt.length(value)
                value = pmt.f32vector_elements(value)[0]
                self.last_val = value

                # save that value
                initial_phase = value

                value = value - self.subtract
                while value < -numpy.pi:
                    value = value + numpy.pi
                while value > numpy.pi:
                    value = value - numpy.pi

                initial_phase = pmt.make_f32vector(1, initial_phase)
                initial_phase = pmt.list2(pmt.string_to_symbol("phase_initial"), initial_phase)

                outvalue = pmt.make_f32vector(1, value)
                output = pmt.list2(pmt.string_to_symbol(str(key)), outvalue)

            else:
                output = element

            if i == 0:
                outpmt = pmt.list1(output)
            else:
                outpmt = pmt.list_add(outpmt, output)

            if initial_phase != None:
                outpmt = pmt.list_add(outpmt, initial_phase)

        self.message_port_pub(pmt.string_to_symbol("out"), outpmt)
Beispiel #12
0
def zmq_msg_payload_to_str(raw_msg):
    msg = pmt.deserialize_str(raw_msg)
    cdr = pmt.cdr(msg)

    packet_len = pmt.length(cdr)
    cdr_str = pmt.serialize_str(cdr)
    output_str = cdr_str[-1 * packet_len:]
    return output_str
Beispiel #13
0
 def test_001_t_tags(self):
     """ Like the previous test, but use a trigger tag instead of
     a trigger signal.
     """
     n_zeros = 1
     header = (1, 2, 3)
     payload = tuple(range(5, 20))
     data_signal = (0,) * n_zeros + header + payload
     # Trigger tag
     trigger_tag = make_tag('detect', True, n_zeros)
     # This is dropped:
     testtag1 = make_tag('tag1', 0, 0)
     # This goes on output 0, item 0:
     testtag2 = make_tag('tag2', 23, n_zeros)
     # This goes on output 0, item 2:
     testtag3 = make_tag('tag3', 42, n_zeros + len(header) - 1)
     # This goes on output 1, item 3:
     testtag4 = make_tag('tag4', 314, n_zeros + len(header) + 3)
     data_src = blocks.vector_source_f(
         data_signal,
         False,
         tags=(trigger_tag, testtag1, testtag2, testtag3, testtag4)
     )
     hpd = digital.header_payload_demux(
         len(header), 1, 0, "frame_len", "detect", False, gr.sizeof_float
     )
     self.assertEqual(pmt.length(hpd.message_ports_in()), 2) #extra system port defined for you
     header_sink = blocks.vector_sink_f()
     payload_sink = blocks.vector_sink_f()
     mock_header_demod = HeaderToMessageBlock(
         numpy.float32,
         len(header),
         [len(payload)]
     )
     self.connect_all_blocks(data_src, None, hpd, mock_header_demod, payload_sink, header_sink)
     self.run_tb(payload_sink, len(payload), header_sink, len(header))
     # Check results
     self.assertEqual(header_sink.data(), header)
     self.assertEqual(payload_sink.data(), payload)
     ptags_header = []
     for tag in header_sink.tags():
         ptag = gr.tag_to_python(tag)
         ptags_header.append({'key': ptag.key, 'offset': ptag.offset})
     expected_tags_header = [
         {'key': 'tag2', 'offset': 0},
         {'key': 'tag3', 'offset': 2},
     ]
     self.assertEqual(expected_tags_header, ptags_header)
     ptags_payload = []
     for tag in payload_sink.tags():
         ptag = gr.tag_to_python(tag)
         ptags_payload.append({'key': ptag.key, 'offset': ptag.offset})
     expected_tags_payload = [
         {'key': 'frame_len', 'offset': 0},
         {'key': 'tag4', 'offset': 3},
     ]
     self.assertEqual(expected_tags_payload, ptags_payload)
 def test_001_t_tags (self):
     """ Like the previous test, but use a trigger tag instead of
     a trigger signal.
     """
     n_zeros = 1
     header = (1, 2, 3)
     payload = tuple(range(5, 20))
     data_signal = (0,) * n_zeros + header + payload
     # Trigger tag
     trigger_tag = make_tag('detect', True, n_zeros)
     # This is dropped:
     testtag1 = make_tag('tag1', 0, 0)
     # This goes on output 0, item 0:
     testtag2 = make_tag('tag2', 23, n_zeros)
     # This goes on output 0, item 2:
     testtag3 = make_tag('tag3', 42, n_zeros + len(header) - 1)
     # This goes on output 1, item 3:
     testtag4 = make_tag('tag4', 314, n_zeros + len(header) + 3)
     data_src = blocks.vector_source_f(
             data_signal,
             False,
             tags=(trigger_tag, testtag1, testtag2, testtag3, testtag4)
     )
     hpd = digital.header_payload_demux(
         len(header), 1, 0, "frame_len", "detect", False, gr.sizeof_float
     )
     self.assertEqual(pmt.length(hpd.message_ports_in()), 2) #extra system port defined for you
     header_sink = blocks.vector_sink_f()
     payload_sink = blocks.vector_sink_f()
     mock_header_demod = HeaderToMessageBlock(
             numpy.float32,
             len(header),
             [len(payload)]
     )
     self.connect_all_blocks(data_src, None, hpd, mock_header_demod, payload_sink, header_sink)
     self.run_tb(payload_sink, len(payload), header_sink, len(header))
     # Check results
     self.assertEqual(header_sink.data(),  header)
     self.assertEqual(payload_sink.data(), payload)
     ptags_header = []
     for tag in header_sink.tags():
         ptag = gr.tag_to_python(tag)
         ptags_header.append({'key': ptag.key, 'offset': ptag.offset})
     expected_tags_header = [
             {'key': 'tag2', 'offset': 0},
             {'key': 'tag3', 'offset': 2},
     ]
     self.assertEqual(expected_tags_header, ptags_header)
     ptags_payload = []
     for tag in payload_sink.tags():
         ptag = gr.tag_to_python(tag)
         ptags_payload.append({'key': ptag.key, 'offset': ptag.offset})
     expected_tags_payload = [
             {'key': 'frame_len', 'offset': 0},
             {'key': 'tag4', 'offset': 3},
     ]
     self.assertEqual(expected_tags_payload, ptags_payload)
Beispiel #15
0
    def app_in(self, msg):  # Generate messages
        global d_msg_len, d_mac_id, d_seq_nr, d_msg

        if self.debug:
            print "******************************** \nGenerating messages ...\n******************************** "
            print ""
            print "MAC:app_in: got something:", msg
        data = msg

        if (pmt.is_pair(msg)):
            data = pmt.cdr(msg)
            #if self.debug: print  "mac.py:app_in: pmt_is_pair \n"
        elif (pmt.is_eof_object(msg)):
            if self.debug: print "MAC: exiting"
            return
        elif (pmt.is_blob(msg)):
            data = pmt.cdr(msg)
            if self.debug: print "data is blob"
        else:
            if self.debug: print "MAC: unknown input"
            return
        if pmt.is_u8vector(data):
            "data is u8vector"
            data_elements = pmt.u8vector_elements(data)
            if self.debug:
                print "Data from Application Layer: ", data_elements, "\n"
                print "Data length :", len(data_elements), "\n"

        d_msg = []

        if pmt.is_symbol(data):
            dataString = pmt.symbol_to_string(data)
            if self.debug:
                print "len(pmt.symbol_to_string(data)): ", len(
                    dataString), "pmt.symbol_to_string(data): ", dataString
            generate_mac(data, len(dataString), self.debug, d_mac_id, d_seq_nr,
                         self.no_self_loop)
        else:
            generate_mac(data, pmt.length(data), self.debug, d_mac_id,
                         d_seq_nr, self.no_self_loop)

        generatedMacPayload = pmt.make_u8vector(len(d_msg), 0)
        for i in range(len(d_msg)):
            #if (pmt.is_vector(data)):
            #print "d_msg[",i,"]: ", d_msg[i], " ; type: ", type(d_msg[i])
            #    pmt.vector_set(generatedMacPayload, i, pmt.to_pmt(d_msg[i]))
            pmt.u8vector_set(generatedMacPayload, i, d_msg[i])
            #else: pmt.u8vector_set(generatedMacPayload, i, d_msg[i])

        self.message_port_pub(pmt.intern("pdu out"),
                              pmt.cons(pmt.PMT_NIL, generatedMacPayload))
        print
        print "**********************************"
        print
        if self.debug:
            print "Data Published to physical Layer: ", pmt.u8vector_elements(
                generatedMacPayload), "\n"
Beispiel #16
0
    def map_handler(self, msg):
        content = pmt.to_python(msg)  #type:float
        length = pmt.length(msg)

        #list of signals (their freqs and bandwidths)
        self.freq_list = []
        self.bw_list = []
        for i in range(0, length):
            self.freq_list.append(content[i][0])
            self.bw_list.append(content[i][1])
Beispiel #17
0
 def print_msg(self, msg):
     """ Print the rx'd message. """
     meta = pmt.to_python(pmt.car(msg))
     vect = pmt.cdr(msg)
     msg_str = ''.join([
         chr(pmt.u8vector_ref(vect, i)) for i in range(pmt.length(vect))
     ]).strip()
     if len(msg_str):
         print 'Incoming message: ', msg_str
     print meta
    def assert_has_num_subscriptions(self, block, port, number):
        """assert that the given block has the given number of subscriptions
        on the given port

        :param block: a block sptr
        :param string port: the port name
        :param number: the number of subscriptions expected
        """
        subs = block.message_subscribers(pmt.intern(port))
        self.assertEqual(pmt.length(subs), number)
    def assert_has_num_subscriptions(self, block, port, number):
        """assert that the given block has the given number of subscriptions
        on the given port

        :param block: a block sptr
        :param string port: the port name
        :param number: the number of subscriptions expected
        """
        subs = block.message_subscribers(pmt.intern(port))
        self.assertEqual(pmt.length(subs), number)
    def map_handler(self, msg):
        content = pmt.to_python(msg)  #type:float
        length = pmt.length(msg)

        #update freq/bandwidth information of the signals
        self.freq_list = []
        self.bw_list = []
        for i in range(0, length):
            self.freq_list.append(content[i][0])
            self.bw_list.append(content[i][1])
  def pdu_in(self, msg): # consume messages
	global d_mac_id

	if self.debug: print "****************************** \nConsuming messages...\n******************************** "
	data = 0
	if(pmt.is_eof_object(msg)):
                self.message_port_pub(pmt.intern('pdu out'), pmt.PMT_EOF)
		return
	elif(pmt.is_pair(msg)): 
		#if self.debug: print  "pmt_is_pair" 
		data = pmt.cdr(msg)					
	elif(pmt.is_bool(msg)):
                if self.debug: print  "mac.py:pdu in: got a busy notification" 
		return
	data_len = pmt.length(data) 
	if self.debug:
		print ""
		print "Data received from pdusical Layer: ", pmt.u8vector_elements(data)
		print ""	
	if (data_len < 13): 
		if self.debug: 	print  "MAC: frame too short. Dropping! \n"
		return
	else: 
       		if self.no_self_loop:    # Compare to our own "mac ID" and reject if we are self routing packets.
 		    macId = pmt.u8vector_elements(data)[0]   
		    if self.debug: 	
		    	print "macId of the packet: ", macId 	
		    	print "our macId: 	    ", d_mac_id 
		    	print "data_len: ", data_len
		    if (macId != d_mac_id): 
			    crc = crc16(pmt.u8vector_elements(data), data_len) 
			    if self.debug: print  "#### CRC at Reception: #### " , crc.get_crc(), "\n"
			    if (crc.get_crc()):
	        		    print  "MAC: wrong crc. Dropping packet! \n" 
				    return	
			    macPayload = pmt.make_u8vector(data_len - 13, 0)
			    #Because of the iperf 'E' issue	
			    #macPayload = pmt.make_u8vector(data_len - 14, 0)
			    #for i in range(data_len - 14):	
			    for i in range(data_len - 13):			    
				    pmt.u8vector_set(macPayload, i, pmt.u8vector_elements(data)[i+11]) 	
			    self.message_port_pub(pmt.intern('app out'), pmt.cons(pmt.PMT_NIL, macPayload))
			    if self.debug: print "Data sent up to Application Layer : ", pmt.u8vector_elements(macPayload), "\n"	
		else:
		    crc = crc16(pmt.u8vector_elements(data), data_len) 
		    if self.debug: print  "#### CRC at Reception: #### " , crc.get_crc(), "\n"
		    if(crc.get_crc()):
        		    if self.debug: print  "MAC: wrong crc. Dropping packet! \n" 
			    return	

		    macPayload = pmt.make_u8vector(data_len - 14, 0)
		    for i in range(data_len - 14):	
			    pmt.u8vector_set(macPayload, i, pmt.u8vector_elements(data)[i+10]) 	
		    self.message_port_pub(pmt.intern('app out'), pmt.cons(pmt.PMT_NIL, macPayload))
		    if self.debug: print "Data sent up to Application Layer : ", pmt.u8vector_elements(macPayload), "\n"	
Beispiel #22
0
def zmq_msg_payload_to_bytes(raw_msg):
    msg = pmt.deserialize_str(raw_msg)
    cdr = pmt.cdr(msg)

    packet_len = pmt.length(cdr)
    cdr_str = pmt.serialize_str(cdr)
    output_str = cdr_str[-1 * packet_len:]
    byte_list = list()
    for i in xrange(len(output_str)):
        byte_list.append(ord(output_str[i]))
    return byte_list
Beispiel #23
0
 def test_003_t (self):
     """
     Like test 1, but twice, plus one fail
     """
     n_zeros = 5
     header = (1, 2, 3)
     header_fail = (-1, -2, -4) # Contents don't really matter
     payload1 = tuple(range(5, 20))
     payload2 = (42,)
     data_signal = (0,) * n_zeros + header + payload1
     trigger_signal = [0,] * len(data_signal) * 2
     trigger_signal[n_zeros] = 1
     trigger_signal[len(data_signal)] = 1
     trigger_signal[len(data_signal)+len(header_fail)+n_zeros] = 1
     tx_signal = data_signal + header_fail + (0,) * n_zeros + header + payload2 + (0,) * 1000
     data_src = blocks.vector_source_f(tx_signal, False)
     trigger_src = blocks.vector_source_b(trigger_signal, False)
     hpd = digital.header_payload_demux(
         len(header), 1, 0, "frame_len", "detect", False, gr.sizeof_float
     )
     self.assertEqual(pmt.length(hpd.message_ports_in()), 1)
     header_sink = blocks.vector_sink_f()
     payload_sink = blocks.vector_sink_f()
     self.tb.connect(data_src,    (hpd, 0))
     self.tb.connect(trigger_src, (hpd, 1))
     self.tb.connect((hpd, 0), header_sink)
     self.tb.connect((hpd, 1), payload_sink)
     self.tb.start()
     time.sleep(.2) # Need this, otherwise, the next message is ignored
     hpd.to_basic_block()._post(
             pmt.intern('header_data'),
             pmt.from_long(len(payload1))
     )
     while len(payload_sink.data()) < len(payload1):
         time.sleep(.2)
     hpd.to_basic_block()._post(
             pmt.intern('header_data'),
             pmt.PMT_F
     )
     # This next command is a bit of a showstopper, but there's no condition to check upon
     # to see if the previous msg handling is finished
     time.sleep(.7)
     hpd.to_basic_block()._post(
             pmt.intern('header_data'),
             pmt.from_long(len(payload2))
     )
     while len(payload_sink.data()) < len(payload1) + len(payload2):
         time.sleep(.2)
     self.tb.stop()
     self.tb.wait()
     self.assertEqual(header_sink.data(),  header + header_fail + header)
     self.assertEqual(payload_sink.data(), payload1 + payload2)
Beispiel #24
0
    def msg_handler(self, p):

        if self.filename != "":
            self.fdout = open(self.filename, "a")

        length = pmt.length(p)

        if self.key == "all":
            #if all keys are printed, they need however be printed once above
            if self.counter == 0:
                for i in range(0, length):
                    element = pmt.nth(i, p)
                    current_key = str(pmt.nth(0, element))
                    self.fdout.write(current_key + ",")
                self.fdout.write("\n")
                self.counter=1

            #print all
            for i in range(0, length):
                element = pmt.nth(i, p)
                current_key = str(pmt.nth(0, element))
                current_value = pmt.nth(1, element)

                if current_key=="rx_time":
                    number = pmt.to_uint64(pmt.tuple_ref(current_value,0)) + \
                             pmt.to_double(pmt.tuple_ref(current_value,1))
                    
                    self.fdout.write(str(number) + ",")
                else:
                    self.fdout.write(str(pmt.f32vector_elements(current_value)[0]) + ",")

        else:
            #print all values that correspond to keys
            for key in self.key:
                for i in range(0, length):
                    element = pmt.nth(i, p)
                    current_key = str(pmt.nth(0, element))
                    current_value = pmt.nth(1, element)

                    if current_key == key:
                        if key=="rx_time":
                            number = pmt.to_uint64(pmt.tuple_ref(current_value,0)) + \
                                     pmt.to_double(pmt.tuple_ref(current_value,1))
                            
                            self.fdout.write(str(number) + ",")
                        else:
                            self.fdout.write(str(pmt.f32vector_elements(current_value)[0]) + ",")

        self.fdout.write("\n")
        self.fdout.close()
def parse_extra_dict(p, info, VERBOSE=False):
    if(pmt.is_dict(p) is False):
        sys.stderr.write("Extra header is not a PMT dictionary: invalid or corrupt data file.\n")
        sys.exit(1)

    items = pmt.dict_items(p)
    nitems = pmt.length(items)
    for i in xrange(nitems):
        item = pmt.nth(i, items)
        key = pmt.symbol_to_string(pmt.car(item))
        val = pmt.cdr(item)
        info[key] = val
        if(VERBOSE):
            print "{0}: {1}".format(key, val)

    return info
Beispiel #26
0
    def sched_pdu(self, pdu):
        sched_time = self.nproduced_val + 10000
        # pick a time in the future
        if sched_time < self.sched_barrier:
            sched_time = self.sched_barrier
            print "delaying packet to sched barrier"

        sched_time = sched_time - sched_time % 1000
        # round to nearest slot
        event_length = pmt.length(pmt.cdr(pdu))
        # event_length = pmt.to_long(pmt.dict_ref(pmt.car(pdu), pmt.intern("event_length"), pmt.PMT_NIL));
        self.sched_barrier = sched_time + event_length + 1000
        print "SCHED_EVENT: time=%d, len=%d  " % (sched_time, event_length)

        pdu = pdulib.pdu_arg_add(pdu, pmt.intern("event_time"), pmt.from_uint64(sched_time))
        self.message_port_pub(pmt.intern("sched_pdu"), pdu)
Beispiel #27
0
def parse_extra_dict(p, info, VERBOSE=False):
    if(pmt.is_dict(p) is False):
        sys.stderr.write("Extra header is not a PMT dictionary: invalid or corrupt data file.\n")
        sys.exit(1)

    items = pmt.dict_items(p)
    nitems = pmt.length(items)
    for i in range(nitems):
        item = pmt.nth(i, items)
        key = pmt.symbol_to_string(pmt.car(item))
        val = pmt.cdr(item)
        info[key] = val
        if(VERBOSE):
            print("{0}: {1}".format(key, val))

    return info
    def sched_pdu(self, pdu):
        sched_time = (self.nproduced_val + 10000)
        # pick a time in the future
        if (sched_time < self.sched_barrier):
            sched_time = self.sched_barrier
            print "delaying packet to sched barrier"

        sched_time = sched_time - sched_time % 1000
        # round to nearest slot
        event_length = pmt.length(pmt.cdr(pdu))
        #event_length = pmt.to_long(pmt.dict_ref(pmt.car(pdu), pmt.intern("event_length"), pmt.PMT_NIL));
        self.sched_barrier = sched_time + event_length + 1000
        print "SCHED_EVENT: time=%d, len=%d  " % (sched_time, event_length)

        pdu = pdulib.pdu_arg_add(pdu, pmt.intern("event_time"),
                                 pmt.from_uint64(sched_time))
        self.message_port_pub(pmt.intern("sched_pdu"), pdu)
Beispiel #29
0
    def handle_msg(self, msg):
        d_size_msg = pmt.length(msg)
        # rx_time, frequency, power, phase

        time_tuple = pmt.nth(1, pmt.nth(0, msg))
        time_s = pmt.to_uint64(pmt.tuple_ref(time_tuple, 0))
        time_ms = pmt.to_double(pmt.tuple_ref(time_tuple, 1))
        timestamp = time_s + time_ms

        phase_val_vec = pmt.nth(1, pmt.nth(d_size_msg - 1, msg))
        phase_val = pmt.f32vector_elements(phase_val_vec)[0]

        #plt.scatter(timestamp, phase_val)
        #plt.pause(0.05)

        #power_val_vec = pmt.nth(1, pmt.nth(d_size_msg-2, msg))
        #power_val = pmt.f32vector_elements(power_val_vec)[0]

        self.phase = phase_val
        self.time = timestamp
Beispiel #30
0
def main():
    src_id = 42
    dest_id = 84
    frame_num = 4711
    checksum = range(16)
    raw_payload = range(16)
    payload = get_pdu_payload(raw_payload)
    print(payload, pmt.length(payload))
    meta = get_pdu_header(dest_id, src_id, frame_num)
    # pl = pmt.u
    print(meta)
    print(pmt.dict_keys(meta))
    print(pmt.dict_values(meta))
    meta = set_pdu_header_checksum(meta, checksum)
    print(meta)

    K = "00010203 04050607 08090A0B 0C0D0E0F "
    K += "10111213 14151617 18191A1B 1C1D1E1F"
    print(K)
    vals = hex_string_to_int_list(K)
    print(get_hex_char_string(vals))
Beispiel #31
0
    def test_001_t (self):
        """ Simplest possible test: put in zeros, then header,
        then payload, trigger signal, try to demux.
        The return signal from the header parser is faked via _post()
        """
        n_zeros = 100
        header = (1, 2, 3)
        payload = tuple(range(17))
        data_signal = (0,) * n_zeros + header + payload
        trigger_signal = [0,] * len(data_signal)
        trigger_signal[n_zeros] = 1

        data_src = blocks.vector_source_f(data_signal, False)
        trigger_src = blocks.vector_source_b(trigger_signal, False)
        hpd = digital.header_payload_demux(
            len(header), 1, 0, "frame_len", "detect", False, gr.sizeof_float
        )
        self.assertEqual(pmt.length(hpd.message_ports_in()), 1)
        header_sink = blocks.vector_sink_f()
        payload_sink = blocks.vector_sink_f()

        self.tb.connect(data_src,    (hpd, 0))
        self.tb.connect(trigger_src, (hpd, 1))
        self.tb.connect((hpd, 0), header_sink)
        self.tb.connect((hpd, 1), payload_sink)
        self.tb.start()
        time.sleep(.2) # Need this, otherwise, the next message is ignored
        hpd.to_basic_block()._post(
                pmt.intern('header_data'),
                pmt.from_long(len(payload))
        )
        while len(payload_sink.data()) < len(payload):
            time.sleep(.2)
        self.tb.stop()
        self.tb.wait()

        self.assertEqual(header_sink.data(),  header)
        self.assertEqual(payload_sink.data(), payload)
    def test_001_t(self):
        src1 = analog.sig_source_c(32000, analog.GR_COS_WAVE, 12500, 3)

        src2 = analog.sig_source_c(32000, analog.GR_COS_WAVE, 9800, 3)

        add = blocks.add_cc()
        detector = inspector.signal_detector_cvf(32000, 4096,
                                                 firdes.WIN_BLACKMAN_hARRIS,
                                                 -80, 0.6, False, 0.5, 0.001)
        dst1 = blocks.null_sink(gr.sizeof_float * 4096)
        msg_dst = blocks.message_debug()

        # connections
        self.tb.connect(src1, (add, 0))
        self.tb.connect(src2, (add, 1))
        self.tb.connect(add, detector)
        self.tb.connect((detector, 0), dst1)
        self.tb.msg_connect((detector, 'map_out'), (msg_dst, 'store'))
        self.tb.start()
        time.sleep(0.5)
        self.tb.stop()
        self.tb.wait()

        # take most recent message
        msg = msg_dst.get_message(msg_dst.num_messages() - 1)
        res_vector = numpy.empty([0, 2])
        for i in range(pmt.length(msg)):
            row = pmt.vector_ref(msg, i)
            res_vector = numpy.vstack(
                (res_vector,
                 numpy.array(
                     [pmt.f32vector_ref(row, 0),
                      pmt.f32vector_ref(row, 1)])))

        self.assertAlmostEqual(9800.0, res_vector[0][0], delta=50)
        self.assertAlmostEqual(0.0, res_vector[0][1], delta=100)
        self.assertAlmostEqual(12500.0, res_vector[1][0], delta=50)
        self.assertAlmostEqual(0.0, res_vector[1][1], delta=100)
    def test_001_t (self):
        src1 = analog.sig_source_c(32000, analog.GR_COS_WAVE,
                                  12500, 3)

        src2 = analog.sig_source_c(32000, analog.GR_COS_WAVE,
                                   9800, 3)

        add = blocks.add_cc()
        detector = inspector.signal_detector_cvf(32000,  4096,
                    firdes.WIN_BLACKMAN_hARRIS, -80, 0.6, False, 0.5, 0.001)
        dst1 = blocks.null_sink(gr.sizeof_float*4096)
        msg_dst = blocks.message_debug()

        #connections
        self.tb.connect(src1, (add, 0))
        self.tb.connect(src2, (add, 1))
        self.tb.connect(add, detector)
        self.tb.connect((detector, 0), dst1)
        self.tb.msg_connect((detector, 'map_out'), (msg_dst, 'store'))
        self.tb.start()
        time.sleep(0.5)
        self.tb.stop()
        self.tb.wait()

        #take most recent message
        msg = msg_dst.get_message(msg_dst.num_messages()-1)
        res_vector = numpy.empty([0, 2])
        for i in range(pmt.length(msg)):
            row = pmt.vector_ref(msg, i)
            res_vector = numpy.vstack((res_vector, numpy.array(
                [pmt.f32vector_ref(row, 0), pmt.f32vector_ref(row, 1)]
            )))

        self.assertAlmostEqual(9800.0, res_vector[0][0], delta=50)
        self.assertAlmostEqual(0.0, res_vector[0][1], delta=100)
        self.assertAlmostEqual(12500.0, res_vector[1][0], delta=50)
        self.assertAlmostEqual(0.0, res_vector[1][1], delta=100)
Beispiel #34
0
    def check_file(self, fname, expected, has_header=False, data_type='uint8'):
        # instantiate objects
        debug = blocks.message_debug()
        reader = csv_reader(fname=fname,
                            has_header=has_header,
                            period=10,
                            repeat=False,
                            start_delay=0,
                            data_type=data_type)

        tb = gr.top_block()
        tb.msg_connect((reader, 'out'), (debug, 'store'))
        tb.start()
        time.sleep(.25)
        tb.stop()
        tb.wait()

        # collect results
        got = debug.get_message(0)
        got_car = pmt.car(got)

        print("got: {}".format(got))
        print("expected: {}".format(expected))

        # do a manual equal on elements because pmt equal is not the best
        expected_items = pmt.dict_items(pmt.car(expected))
        valid = True
        for i in range(pmt.length(expected_items)):
            key = pmt.car(pmt.nth(i, expected_items))
            value = pmt.cdr(pmt.nth(i, expected_items))
            got_value = pmt.dict_ref(got_car, key, pmt.PMT_NIL)
            if not pmt.equal(got_value, value):
                valid = False
                break

        return (valid and pmt.equal(pmt.cdr(got), pmt.cdr(expected)))
 def test_003_t (self):
     """
     Like test 1, but twice, plus one fail
     """
     ### Tx Data
     n_zeros = 5
     header = (1, 2, 3)
     header_fail = (-1, -2, -4) # Contents don't really matter
     payload1 = tuple(range(5, 20))
     payload2 = (42,)
     sampling_rate = 2
     data_signal = (0,) * n_zeros + header + payload1
     trigger_signal = [0,] * len(data_signal) * 2
     trigger_signal[n_zeros] = 1
     trigger_signal[len(data_signal)] = 1
     trigger_signal[len(data_signal)+len(header_fail)+n_zeros] = 1
     print("Triggers at: {0} {1} {2}".format(
         n_zeros,
         len(data_signal),
         len(data_signal)+len(header_fail)+n_zeros)
     )
     tx_signal = data_signal + \
             header_fail + (0,) * n_zeros + \
             header + payload2 + (0,) * 1000
     # Timing tag: This is preserved and updated:
     timing_tag = make_tag('rx_time', (0, 0), 0)
     # Rx freq tags:
     rx_freq_tag1 = make_tag('rx_freq', 1.0, 0)
     rx_freq_tag2 = make_tag('rx_freq', 1.5, 29)
     rx_freq_tag3 = make_tag('rx_freq', 2.0, 30)
     ### Flow graph
     data_src = blocks.vector_source_f(
         tx_signal, False,
         tags=(timing_tag, rx_freq_tag1, rx_freq_tag2, rx_freq_tag3)
     )
     trigger_src = blocks.vector_source_b(trigger_signal, False)
     hpd = digital.header_payload_demux(
         header_len=len(header),
         items_per_symbol=1,
         guard_interval=0,
         length_tag_key="frame_len",
         trigger_tag_key="detect",
         output_symbols=False,
         itemsize=gr.sizeof_float,
         timing_tag_key='rx_time',
         samp_rate=sampling_rate,
         special_tags=('rx_freq',),
     )
     self.assertEqual(pmt.length(hpd.message_ports_in()), 2) #extra system port defined for you
     header_sink = blocks.vector_sink_f()
     payload_sink = blocks.vector_sink_f()
     self.tb.connect(data_src,    (hpd, 0))
     self.tb.connect(trigger_src, (hpd, 1))
     self.tb.connect((hpd, 0), header_sink)
     self.tb.connect((hpd, 1), payload_sink)
     self.tb.start()
     time.sleep(.2) # Need this, otherwise, the next message is ignored
     hpd.to_basic_block()._post(
             pmt.intern('header_data'),
             pmt.from_long(len(payload1))
     )
     while len(payload_sink.data()) < len(payload1):
         time.sleep(.2)
     hpd.to_basic_block()._post(
             pmt.intern('header_data'),
             pmt.PMT_F
     )
     # This next command is a bit of a showstopper, but there's no condition to check upon
     # to see if the previous msg handling is finished
     time.sleep(.7)
     hpd.to_basic_block()._post(
             pmt.intern('header_data'),
             pmt.from_long(len(payload2))
     )
     while len(payload_sink.data()) < len(payload1) + len(payload2):
         time.sleep(.2)
     self.tb.stop()
     self.tb.wait()
     # Signal description:
     # 0:  5 zeros
     # 5:  header 1
     # 8:  payload 1 (length: 15)
     # 23: header 2 (fail)
     # 26: 5 zeros
     # 31: header 3
     # 34: payload 2 (length 1)
     # 35: 1000 zeros
     self.assertEqual(header_sink.data(),  header + header_fail + header)
     self.assertEqual(payload_sink.data(), payload1 + payload2)
     tags_payload = [gr.tag_to_python(x) for x in payload_sink.tags()]
     tags_payload = sorted([(x.offset, x.key, x.value) for x in tags_payload])
     tags_expected_payload = [
         (0,             'frame_len', len(payload1)),
         (len(payload1), 'frame_len', len(payload2)),
     ]
     tags_header = [gr.tag_to_python(x) for x in header_sink.tags()]
     tags_header = sorted([(x.offset, x.key, x.value) for x in tags_header])
     tags_expected_header = [
         (0,             'rx_freq', 1.0),
         (0,             'rx_time', (2, 0.5)), # Hard coded time value :( Is n_zeros/sampling_rate
         (len(header),   'rx_freq', 1.0),
         (len(header),   'rx_time', (11, .5)), # Hard coded time value :(. See above.
         (2*len(header), 'rx_freq', 2.0),
         (2*len(header), 'rx_time', (15, .5)), # Hard coded time value :(. See above.
     ]
     self.assertEqual(tags_header, tags_expected_header)
     self.assertEqual(tags_payload, tags_expected_payload)
 def test_001_headerpadding_payload_offset (self):
     """ Like test 1, but with header padding + payload offset. """
     n_zeros = 3
     header = (1, 2, 3)
     header_padding = 1
     payload_offset = -1
     payload = tuple(range(5, 20))
     data_signal = (0,) * n_zeros + header + payload + (0,) * 100
     trigger_signal = [0] * len(data_signal)
     trigger_signal[n_zeros] = 1
     # This goes on output 1, item 3 + 1 (for payload offset)
     testtag4 = make_tag('tag4', 314, n_zeros + len(header) + 3)
     data_src = blocks.vector_source_f(
             data_signal,
             False,
             tags=(testtag4,)
     )
     trigger_src = blocks.vector_source_b(trigger_signal, False)
     hpd = digital.header_payload_demux(
         len(header),
         1, # Items per symbol
         0, # Guard interval
         "frame_len", # TSB tag key
         "detect", # Trigger tag key
         False, # No symbols please
         gr.sizeof_float, # Item size
         "", # Timing tag key
         1.0, # Samp rate
         (), # No special tags
         header_padding
     )
     self.assertEqual(pmt.length(hpd.message_ports_in()), 2) #extra system port defined for you
     header_sink = blocks.vector_sink_f()
     payload_sink = blocks.vector_sink_f()
     self.tb.connect(data_src,    (hpd, 0))
     self.tb.connect(trigger_src, (hpd, 1))
     self.tb.connect((hpd, 0), header_sink)
     self.tb.connect((hpd, 1), payload_sink)
     self.tb.start()
     time.sleep(.2) # Need this, otherwise, the next message is ignored
     hpd.to_basic_block()._post(
             pmt.intern('header_data'),
             pmt.to_pmt({'frame_len': len(payload), 'payload_offset': payload_offset})
     )
     while len(payload_sink.data()) < len(payload):
         time.sleep(.2)
     self.tb.stop()
     self.tb.wait()
     # Header is now padded:
     self.assertEqual(header_sink.data(),  (0,) + header + (payload[0],))
     # Payload is now offset:
     self.assertEqual(
             payload_sink.data(),
             data_signal[n_zeros + len(header) + payload_offset:n_zeros + len(header) + payload_offset + len(payload)]
     )
     ptags_payload = {}
     for tag in payload_sink.tags():
         ptag = gr.tag_to_python(tag)
         ptags_payload[ptag.key] = ptag.offset
     expected_tags_payload = {
             'frame_len': 0,
             'payload_offset': 0,
             'tag4': 3 - payload_offset,
     }
     self.assertEqual(expected_tags_payload, ptags_payload)
 def test_003_t(self):
     """
     Like test 1, but twice, plus one fail
     """
     ### Tx Data
     n_zeros = 5
     header = (1, 2, 3)
     header_fail = (-1, -2, -4)  # Contents don't really matter
     payload1 = tuple(range(5, 20))
     payload2 = (42, )
     sampling_rate = 2
     data_signal = (0, ) * n_zeros + header + payload1
     trigger_signal = [
         0,
     ] * len(data_signal) * 2
     trigger_signal[n_zeros] = 1
     trigger_signal[len(data_signal)] = 1
     trigger_signal[len(data_signal) + len(header_fail) + n_zeros] = 1
     tx_signal = data_signal + header_fail + (
         0, ) * n_zeros + header + payload2 + (0, ) * 1000
     # Timing tag: This is preserved and updated:
     timing_tag = gr.tag_t()
     timing_tag.offset = 0
     timing_tag.key = pmt.string_to_symbol('rx_time')
     timing_tag.value = pmt.to_pmt((0, 0))
     # Rx freq tags:
     rx_freq_tag1 = gr.tag_t()
     rx_freq_tag1.offset = 0
     rx_freq_tag1.key = pmt.string_to_symbol('rx_freq')
     rx_freq_tag1.value = pmt.from_double(1.0)
     rx_freq_tag2 = gr.tag_t()
     rx_freq_tag2.offset = 29
     rx_freq_tag2.key = pmt.string_to_symbol('rx_freq')
     rx_freq_tag2.value = pmt.from_double(1.5)
     rx_freq_tag3 = gr.tag_t()
     rx_freq_tag3.offset = 30
     rx_freq_tag3.key = pmt.string_to_symbol('rx_freq')
     rx_freq_tag3.value = pmt.from_double(2.0)
     ### Flow graph
     data_src = blocks.vector_source_f(tx_signal,
                                       False,
                                       tags=(timing_tag, rx_freq_tag1,
                                             rx_freq_tag2, rx_freq_tag3))
     trigger_src = blocks.vector_source_b(trigger_signal, False)
     hpd = digital.header_payload_demux(
         header_len=len(header),
         items_per_symbol=1,
         guard_interval=0,
         length_tag_key="frame_len",
         trigger_tag_key="detect",
         output_symbols=False,
         itemsize=gr.sizeof_float,
         timing_tag_key='rx_time',
         samp_rate=sampling_rate,
         special_tags=('rx_freq', ),
     )
     self.assertEqual(pmt.length(hpd.message_ports_in()),
                      2)  #extra system port defined for you
     header_sink = blocks.vector_sink_f()
     payload_sink = blocks.vector_sink_f()
     self.tb.connect(data_src, (hpd, 0))
     self.tb.connect(trigger_src, (hpd, 1))
     self.tb.connect((hpd, 0), header_sink)
     self.tb.connect((hpd, 1), payload_sink)
     self.tb.start()
     time.sleep(.2)  # Need this, otherwise, the next message is ignored
     hpd.to_basic_block()._post(pmt.intern('header_data'),
                                pmt.from_long(len(payload1)))
     while len(payload_sink.data()) < len(payload1):
         time.sleep(.2)
     hpd.to_basic_block()._post(pmt.intern('header_data'), pmt.PMT_F)
     # This next command is a bit of a showstopper, but there's no condition to check upon
     # to see if the previous msg handling is finished
     time.sleep(.7)
     hpd.to_basic_block()._post(pmt.intern('header_data'),
                                pmt.from_long(len(payload2)))
     while len(payload_sink.data()) < len(payload1) + len(payload2):
         time.sleep(.2)
     self.tb.stop()
     self.tb.wait()
     # Signal description:
     # 0:  5 zeros
     # 5:  header 1
     # 8:  payload 1 (length: 15)
     # 23: header 2 (fail)
     # 26: 5 zeros
     # 31: header 3
     # 34: payload 2 (length 1)
     # 35: 1000 zeros
     self.assertEqual(header_sink.data(), header + header_fail + header)
     self.assertEqual(payload_sink.data(), payload1 + payload2)
     tags_payload = [gr.tag_to_python(x) for x in payload_sink.tags()]
     tags_payload = sorted([(x.offset, x.key, x.value)
                            for x in tags_payload])
     tags_expected_payload = [
         (0, 'frame_len', len(payload1)),
         (len(payload1), 'frame_len', len(payload2)),
     ]
     tags_header = [gr.tag_to_python(x) for x in header_sink.tags()]
     tags_header = sorted([(x.offset, x.key, x.value) for x in tags_header])
     tags_expected_header = [
         (0, 'rx_freq', 1.0),
         (0, 'rx_time',
          (2, 0.5)),  # Hard coded time value :( Is n_zeros/sampling_rate
         (len(header), 'rx_freq', 1.0),
         (len(header), 'rx_time',
          (11, .5)),  # Hard coded time value :(. See above.
         (2 * len(header), 'rx_freq', 2.0),
         (2 * len(header), 'rx_time',
          (15, .5)),  # Hard coded time value :(. See above.
     ]
     self.assertEqual(tags_header, tags_expected_header)
     self.assertEqual(tags_payload, tags_expected_payload)
    def test_001_t(self):
        """ Simplest possible test: put in zeros, then header,
        then payload, trigger signal, try to demux.
        The return signal from the header parser is faked via _post()
        Add in some tags for fun.
        """
        n_zeros = 1
        header = (1, 2, 3)
        payload = tuple(range(5, 20))
        data_signal = (0, ) * n_zeros + header + payload
        trigger_signal = [
            0,
        ] * len(data_signal)
        trigger_signal[n_zeros] = 1
        # This is dropped:
        testtag1 = gr.tag_t()
        testtag1.offset = 0
        testtag1.key = pmt.string_to_symbol('tag1')
        testtag1.value = pmt.from_long(0)
        # This goes on output 0, item 0:
        testtag2 = gr.tag_t()
        testtag2.offset = n_zeros
        testtag2.key = pmt.string_to_symbol('tag2')
        testtag2.value = pmt.from_long(23)
        # This goes on output 0, item 2:
        testtag3 = gr.tag_t()
        testtag3.offset = n_zeros + len(header) - 1
        testtag3.key = pmt.string_to_symbol('tag3')
        testtag3.value = pmt.from_long(42)
        # This goes on output 1, item 3:
        testtag4 = gr.tag_t()
        testtag4.offset = n_zeros + len(header) + 3
        testtag4.key = pmt.string_to_symbol('tag4')
        testtag4.value = pmt.from_long(314)
        data_src = blocks.vector_source_f(data_signal,
                                          False,
                                          tags=(testtag1, testtag2, testtag3,
                                                testtag4))
        trigger_src = blocks.vector_source_b(trigger_signal, False)
        hpd = digital.header_payload_demux(len(header), 1, 0, "frame_len",
                                           "detect", False, gr.sizeof_float)
        self.assertEqual(pmt.length(hpd.message_ports_in()),
                         2)  #extra system port defined for you
        header_sink = blocks.vector_sink_f()
        payload_sink = blocks.vector_sink_f()

        self.tb.connect(data_src, (hpd, 0))
        self.tb.connect(trigger_src, (hpd, 1))
        self.tb.connect((hpd, 0), header_sink)
        self.tb.connect((hpd, 1), payload_sink)
        self.tb.start()
        time.sleep(.2)  # Need this, otherwise, the next message is ignored
        hpd.to_basic_block()._post(pmt.intern('header_data'),
                                   pmt.from_long(len(payload)))
        while len(payload_sink.data()) < len(payload):
            time.sleep(.2)
        self.tb.stop()
        self.tb.wait()

        self.assertEqual(header_sink.data(), header)
        self.assertEqual(payload_sink.data(), payload)
        ptags_header = []
        for tag in header_sink.tags():
            ptag = gr.tag_to_python(tag)
            ptags_header.append({'key': ptag.key, 'offset': ptag.offset})
        expected_tags_header = [
            {
                'key': 'tag2',
                'offset': 0
            },
            {
                'key': 'tag3',
                'offset': 2
            },
        ]
        self.assertEqual(expected_tags_header, ptags_header)
        ptags_payload = []
        for tag in payload_sink.tags():
            ptag = gr.tag_to_python(tag)
            ptags_payload.append({'key': ptag.key, 'offset': ptag.offset})
        expected_tags_payload = [
            {
                'key': 'frame_len',
                'offset': 0
            },
            {
                'key': 'tag4',
                'offset': 3
            },
        ]
        self.assertEqual(expected_tags_payload, ptags_payload)
    def test_001_t_tags (self):
        """ Like the previous test, but use a trigger tag instead of
        a trigger signal.
        """
        n_zeros = 1
        header = (1, 2, 3)
        payload = tuple(range(5, 20))
        data_signal = (0,) * n_zeros + header + payload
        # Trigger tag
        trigger_tag = gr.tag_t()
        trigger_tag.offset = n_zeros
        trigger_tag.key = pmt.string_to_symbol('detect')
        trigger_tag.value = pmt.PMT_T
        # This is dropped:
        testtag1 = gr.tag_t()
        testtag1.offset = 0
        testtag1.key = pmt.string_to_symbol('tag1')
        testtag1.value = pmt.from_long(0)
        # This goes on output 0, item 0:
        testtag2 = gr.tag_t()
        testtag2.offset = n_zeros
        testtag2.key = pmt.string_to_symbol('tag2')
        testtag2.value = pmt.from_long(23)
        # This goes on output 0, item 2:
        testtag3 = gr.tag_t()
        testtag3.offset = n_zeros + len(header) - 1
        testtag3.key = pmt.string_to_symbol('tag3')
        testtag3.value = pmt.from_long(42)
        # This goes on output 1, item 3:
        testtag4 = gr.tag_t()
        testtag4.offset = n_zeros + len(header) + 3
        testtag4.key = pmt.string_to_symbol('tag4')
        testtag4.value = pmt.from_long(314)
        data_src = blocks.vector_source_f(
                data_signal,
                False,
                tags=(trigger_tag, testtag1, testtag2, testtag3, testtag4)
        )
        hpd = digital.header_payload_demux(
            len(header), 1, 0, "frame_len", "detect", False, gr.sizeof_float
        )
        self.assertEqual(pmt.length(hpd.message_ports_in()), 2) #extra system port defined for you
        header_sink = blocks.vector_sink_f()
        payload_sink = blocks.vector_sink_f()

        self.tb.connect(data_src,    (hpd, 0))
        self.tb.connect((hpd, 0), header_sink)
        self.tb.connect((hpd, 1), payload_sink)
        self.tb.start()
        time.sleep(.2) # Need this, otherwise, the next message is ignored
        hpd.to_basic_block()._post(
                pmt.intern('header_data'),
                pmt.from_long(len(payload))
        )
        while len(payload_sink.data()) < len(payload):
            time.sleep(.2)
        self.tb.stop()
        self.tb.wait()

        self.assertEqual(header_sink.data(),  header)
        self.assertEqual(payload_sink.data(), payload)
        ptags_header = []
        for tag in header_sink.tags():
            ptag = gr.tag_to_python(tag)
            ptags_header.append({'key': ptag.key, 'offset': ptag.offset})
        expected_tags_header = [
                {'key': 'tag2', 'offset': 0},
                {'key': 'tag3', 'offset': 2},
        ]
        self.assertEqual(expected_tags_header, ptags_header)
        ptags_payload = []
        for tag in payload_sink.tags():
            ptag = gr.tag_to_python(tag)
            ptags_payload.append({'key': ptag.key, 'offset': ptag.offset})
        expected_tags_payload = [
                {'key': 'frame_len', 'offset': 0},
                {'key': 'tag4', 'offset': 3},
        ]
        self.assertEqual(expected_tags_payload, ptags_payload)
 def test_002_symbols(self):
     """ 
     Same as before, but operate on symbols
     """
     n_zeros = 1
     items_per_symbol = 3
     gi = 1
     n_symbols = 4
     header = (1, 2, 3)
     payload = (1, 2, 3)
     data_signal = (0, ) * n_zeros + (0, ) + header + (
         (0, ) + payload) * n_symbols
     trigger_signal = [
         0,
     ] * len(data_signal)
     trigger_signal[n_zeros] = 1
     # This is dropped:
     testtag1 = gr.tag_t()
     testtag1.offset = 0
     testtag1.key = pmt.string_to_symbol('tag1')
     testtag1.value = pmt.from_long(0)
     # This goes on output 0, item 0 (from the GI)
     testtag2 = gr.tag_t()
     testtag2.offset = n_zeros
     testtag2.key = pmt.string_to_symbol('tag2')
     testtag2.value = pmt.from_long(23)
     # This goes on output 0, item 0 (middle of the header symbol)
     testtag3 = gr.tag_t()
     testtag3.offset = n_zeros + gi + 1
     testtag3.key = pmt.string_to_symbol('tag3')
     testtag3.value = pmt.from_long(42)
     # This goes on output 1, item 1 (middle of the first payload symbol)
     testtag4 = gr.tag_t()
     testtag4.offset = n_zeros + (gi + items_per_symbol) * 2 + 1
     testtag4.key = pmt.string_to_symbol('tag4')
     testtag4.value = pmt.from_long(314)
     data_src = blocks.vector_source_f(data_signal,
                                       False,
                                       tags=(testtag1, testtag2, testtag3,
                                             testtag4))
     trigger_src = blocks.vector_source_b(trigger_signal, False)
     hpd = digital.header_payload_demux(
         len(header) / items_per_symbol,  # Header length (in symbols)
         items_per_symbol,  # Items per symbols
         gi,  # Items per guard time
         "frame_len",  # Frame length tag key
         "detect",  # Trigger tag key
         True,  # Output symbols (not items)
         gr.sizeof_float  # Bytes per item
     )
     self.assertEqual(pmt.length(hpd.message_ports_in()),
                      2)  #extra system port defined for you
     header_sink = blocks.vector_sink_f(items_per_symbol)
     payload_sink = blocks.vector_sink_f(items_per_symbol)
     self.tb.connect(data_src, (hpd, 0))
     self.tb.connect(trigger_src, (hpd, 1))
     self.tb.connect((hpd, 0), header_sink)
     self.tb.connect((hpd, 1), payload_sink)
     self.tb.start()
     time.sleep(.2)  # Need this, otherwise, the next message is ignored
     hpd.to_basic_block()._post(pmt.intern('header_data'),
                                pmt.from_long(n_symbols))
     while len(payload_sink.data()) < len(payload) * n_symbols:
         time.sleep(.2)
     self.tb.stop()
     self.tb.wait()
     self.assertEqual(header_sink.data(), header)
     self.assertEqual(payload_sink.data(), payload * n_symbols)
     ptags_header = []
     for tag in header_sink.tags():
         ptag = gr.tag_to_python(tag)
         ptags_header.append({'key': ptag.key, 'offset': ptag.offset})
     expected_tags_header = [
         {
             'key': 'tag2',
             'offset': 0
         },
         {
             'key': 'tag3',
             'offset': 0
         },
     ]
     self.assertEqual(expected_tags_header, ptags_header)
     ptags_payload = []
     for tag in payload_sink.tags():
         ptag = gr.tag_to_python(tag)
         ptags_payload.append({'key': ptag.key, 'offset': ptag.offset})
     expected_tags_payload = [
         {
             'key': 'frame_len',
             'offset': 0
         },
         {
             'key': 'tag4',
             'offset': 1
         },
     ]
     self.assertEqual(expected_tags_payload, ptags_payload)
  def __init__(self, buf, len, debug, d_mac_id, d_seq_nr, no_self_loop): 

	self.debug 	= debug
	self.buf   	= buf
        self.len   	= len
	self.d_seq_nr	= d_seq_nr
	self.d_mac_id	= d_mac_id
	self.no_self_loop  = no_self_loop

	if self.no_self_loop:
	        #Insert an id here to check for self routing. This makes the packet non standard.
	        d_msg.insert(0, self.d_mac_id)	
		d_msg.insert(1, 11 + self.len + 2) 

		#FCF
		d_msg.insert(2,0x41)
		d_msg.insert(3,0x88)

		#seq nr
		d_msg.insert(4,++self.d_seq_nr)

		#addr info
		d_msg.insert(5,0xcd)
		d_msg.insert(6,0xab)
		d_msg.insert(7,0xff)
		d_msg.insert(8,0xff)
		d_msg.insert(9,0x40)
		d_msg.insert(10,0xe8)
	        #Copy the data here.
		if (pmt.is_vector(buf)): 
			for i in range(pmt.length(buf)):	
				d_msg.insert(10+i,pmt.to_long(pmt.vector_ref(buf,i)))
		elif (pmt.is_uniform_vector(buf)):
			d_msg.extend(pmt.u8vector_elements(buf))	
		else:
			bufString = pmt.symbol_to_string(buf)
			#print "pmt.symbol_to_string(buf): ", bufString
			#print "pmt.length(buf): ", pmt.length(buf)
			bytes = map(ord,bufString)
			#print "map(ord,buf): ", bytes
			d_msg.extend(bytes)

	        #Compute the CRC over the whole packet (excluding the CRC bytes themselves)
		crc = crc16(d_msg, self.len + 11) 
	        #if self.debug: print  "#### CRC at Transmission: #### ", crc.get_crc() 
       
       		#CRC goes on the end.
		d_msg.insert(11+ self.len, crc.get_crc() & 0xFF)
		d_msg.insert(12+ self.len, crc.get_crc() >> 8)

		d_msg_len = 11  + self.len + 2
		print 
		print
		if self.debug: print "d_msg: ", d_msg
		print
		print
	else:
	        #Preamble length + CRC length ( CRC at the end)
		d_msg.insert(0, 10 + self.len  + 2)

		#FCF
		d_msg.insert(1,0x41)
		d_msg.insert(2,0x88)

		#seq nr
		d_msg.insert(3,++self.d_seq_nr)

		#addr info
		d_msg.insert(4,0xcd)
		d_msg.insert(5,0xab)
		d_msg.insert(6,0xff)
		d_msg.insert(7,0xff)
		d_msg.insert(8,0x40)
		d_msg.insert(9,0xe8)

	        #Copy the data here.
		d_msg.extend(pmt.u8vector_elements(buf))
	        #Compute the CRC over the whole packet (excluding the CRC bytes themselves)
	        crc = crc16(d_msg, self.len + 10)
		if self.debug: print  "#### CRC at Transmission: #### ", crc.get_crc() 

		d_msg.insert(10 + self.len, crc.get_crc() & 0xFF)
		d_msg.insert(11 + self.len, crc.get_crc() >> 8)

	        d_msg_len = 10  + self.len + 2 # Preamble + Data + CRC

	if self.debug: print  " msg len ", d_msg_len, " len ", self.len, "\n"
Beispiel #42
0
    def msg_handler(self, p):

        verbose = False

        length = pmt.length(p)
        
        if verbose:
            print "PMT contrains " + str(length) + " key/value pairs"

        for i in range(0,length):
           element = pmt.nth(i, p)

           key = pmt.nth(0, element)
           value = pmt.nth(1, element)

           if verbose:
               print "Key of " + str(i) + "th element: " + str(key)
               print "Value of " + str(i) + "th element: " + str(value)
               print

           found = False
           for j in range(0, len(self.n)):
               if str(key) == self.kk[j]:
                   found = True

                   if verbose:
                       print "found the key " + str(key)

                   #rotate the values, the latest one disappears
                   self.prev_values[j] = numpy.roll(self.prev_values[j], -1)

                   #set the vector accordingly
                   self.prev_values[j][-1] = pmt.f32vector_elements(value)[0]
                   

                   output = sum(self.prev_values[j])/len(self.prev_values[j])
                   output = pmt.make_f32vector(1, output)

                   if i==0:
                       outpmt = pmt.list1(pmt.list2(pmt.string_to_symbol(str(key) + "_filtered"), output))
                   else:
                       outpmt = pmt.list_add(outpmt, pmt.list2(pmt.string_to_symbol(str(key) + "_filtered"), output))



           output = pmt.nth(1, element)

           if i==0:
               outpmt = pmt.list1(pmt.list2(key, output))
           else:
               outpmt = pmt.list_add(outpmt, pmt.list2(key, output))

        if verbose:
            print


        #iterate over all keys
        for i in range(0, len(self.kk)):
            minimum = self.prev_values[i][0]
            maximum = self.prev_values[i][0]
            #iterate over all saved values
            for j in range(0, self.n[i]):
                if self.prev_values[i][j] < minimum:
                    minimum = self.prev_values[i][j]
                if self.prev_values[i][j] > maximum:
                    maximum = self.prev_values[i][j]
        
        #print out a min, diff, max for every key
        difference = maximum-minimum
        outpmt = pmt.list_add(outpmt, pmt.list2(pmt.string_to_symbol("min"), pmt.make_f32vector(1, minimum)))
        outpmt = pmt.list_add(outpmt, pmt.list2(pmt.string_to_symbol("max"), pmt.make_f32vector(1, maximum)))
        outpmt = pmt.list_add(outpmt, pmt.list2(pmt.string_to_symbol("diff"), pmt.make_f32vector(1, difference)))


        self.message_port_pub(pmt.string_to_symbol("out"), outpmt)
Beispiel #43
0
 def test_001_headerpadding_payload_offset (self):
     """ Like test 1, but with header padding + payload offset. """
     n_zeros = 3
     header = (1, 2, 3)
     header_padding = 1
     payload_offset = -1
     payload = tuple(range(5, 20))
     data_signal = (0,) * n_zeros + header + payload + (0,) * 100
     trigger_signal = [0] * len(data_signal)
     trigger_signal[n_zeros] = 1
     # This goes on output 1, item 3 + 1 (for payload offset)
     testtag4 = make_tag('tag4', 314, n_zeros + len(header) + 3)
     data_src = blocks.vector_source_f(
         data_signal,
         False,
         tags=(testtag4,)
     )
     trigger_src = blocks.vector_source_b(trigger_signal, False)
     hpd = digital.header_payload_demux(
         len(header),
         1, # Items per symbol
         0, # Guard interval
         "frame_len", # TSB tag key
         "detect", # Trigger tag key
         False, # No symbols please
         gr.sizeof_float, # Item size
         "", # Timing tag key
         1.0, # Samp rate
         (), # No special tags
         header_padding
     )
     self.assertEqual(pmt.length(hpd.message_ports_in()), 2) #extra system port defined for you
     header_sink = blocks.vector_sink_f()
     payload_sink = blocks.vector_sink_f()
     self.tb.connect(data_src,    (hpd, 0))
     self.tb.connect(trigger_src, (hpd, 1))
     self.tb.connect((hpd, 0), header_sink)
     self.tb.connect((hpd, 1), payload_sink)
     self.tb.start()
     time.sleep(.2) # Need this, otherwise, the next message is ignored
     hpd.to_basic_block()._post(
         pmt.intern('header_data'),
         pmt.to_pmt({'frame_len': len(payload), 'payload_offset': payload_offset})
     )
     while len(payload_sink.data()) < len(payload):
         time.sleep(.2)
     self.tb.stop()
     self.tb.wait()
     # Header is now padded:
     self.assertEqual(header_sink.data(),  (0,) + header + (payload[0],))
     # Payload is now offset:
     self.assertEqual(
         payload_sink.data(),
         data_signal[n_zeros + len(header) + payload_offset:n_zeros + len(header) + payload_offset + len(payload)]
     )
     ptags_payload = {}
     for tag in payload_sink.tags():
         ptag = gr.tag_to_python(tag)
         ptags_payload[ptag.key] = ptag.offset
     expected_tags_payload = {
         'frame_len': 0,
         'payload_offset': 0,
         'tag4': 3 - payload_offset,
     }
     self.assertEqual(expected_tags_payload, ptags_payload)
    def test_004_long_burst(self):
        # This test processes a single burst that exceeds the maximum burst size that will be truncated

        # data
        min_data_size = 32 * 1024  # arbitrary constant in tagged_burst_to_pdu_impl.h
        src_data = (1, ) * min_data_size * 8

        new_burst_offset = 64
        new_burst_dict = pmt.make_dict()
        new_burst_dict = pmt.dict_add(new_burst_dict,
                                      fhss_utils.PMTCONSTSTR__burst_id(),
                                      pmt.from_uint64(505))
        new_burst_dict = pmt.dict_add(
            new_burst_dict, fhss_utils.PMTCONSTSTR__relative_frequency(),
            pmt.from_float(1e6 / 30.72e6))  # in [-1.0,1.0], not Hz
        new_burst_dict = pmt.dict_add(
            new_burst_dict, fhss_utils.PMTCONSTSTR__center_frequency(),
            pmt.from_float(915e6))  # of the whole signal, not the burst
        new_burst_dict = pmt.dict_add(new_burst_dict,
                                      fhss_utils.PMTCONSTSTR__magnitude(),
                                      pmt.from_float(40))
        new_burst_dict = pmt.dict_add(new_burst_dict,
                                      fhss_utils.PMTCONSTSTR__sample_rate(),
                                      pmt.from_float(30.72e6))
        new_burst_dict = pmt.dict_add(new_burst_dict,
                                      fhss_utils.PMTCONSTSTR__noise_density(),
                                      pmt.from_float(-100))  # in dBFS/Hz
        new_burst_dict = pmt.dict_add(new_burst_dict,
                                      fhss_utils.PMTCONSTSTR__bandwidth(),
                                      pmt.from_float(0.1e6))
        nb_tag = gr.tag_utils.python_to_tag([
            new_burst_offset,
            fhss_utils.PMTCONSTSTR__new_burst(), new_burst_dict,
            pmt.intern("qa_test")
        ])

        duration = 1024
        gone_burst_offset = new_burst_offset + duration
        gone_burst_dict = pmt.make_dict()
        gone_burst_dict = pmt.dict_add(gone_burst_dict,
                                       fhss_utils.PMTCONSTSTR__burst_id(),
                                       pmt.from_uint64(505))
        gb_tag = gr.tag_utils.python_to_tag([
            gone_burst_offset,
            fhss_utils.PMTCONSTSTR__gone_burst(), gone_burst_dict,
            pmt.intern("qa_test")
        ])

        # blocks
        src = blocks.vector_source_c(src_data, False, 1, [nb_tag, gb_tag])
        #src.set_min_output_buffer(min_data_size*2) # not necessary, block calls set_output_multiple
        debug = blocks.message_debug()

        dec = 16
        taps = [1]
        min_time = 1e-6
        max_time = 10e-6
        nthreads = 3
        samp_rate = 30.72e6
        rel_span = 1
        rel_samp_rate = 1
        rel_cf = 0
        dut = fhss_utils.tagged_burst_to_pdu(dec, taps, min_time, max_time,
                                             rel_cf, rel_span, rel_samp_rate,
                                             samp_rate, nthreads)

        self.tb.connect(src, dut)
        self.tb.msg_connect((dut, 'cpdus'), (debug, 'store'))

        #self.tb.run() # blocking, vector_source will end flowgraph
        self.tb.start()
        time.sleep(0.1)
        self.tb.stop()
        time.sleep(0.1)
        self.tb.wait()
        time.sleep(0.1)

        print("test long burst:")
        #print(f"how many msg? {debug.num_messages()}")
        self.assertEqual(debug.num_messages(), 1)
        #print(f"received: {pmt.car(debug.get_message(0))}")
        #print(f"received: {pmt.cdr(debug.get_message(0))}")
        #print(f"received len: {pmt.length(pmt.cdr(debug.get_message(0)))}")
        rcv_meta = pmt.car(debug.get_message(0))

        # we expect a duration equal to `max_time` and a vector of length that corrseponds to `max_time` samples
        self.assertAlmostEqual(
            pmt.to_double(
                pmt.dict_ref(rcv_meta, pmt.intern("duration"), pmt.PMT_NIL)),
            max_time, 6)
        self.assertEqual(pmt.length(pmt.cdr(debug.get_message(0))),
                         (max_time * samp_rate) // dec)
        self.assertEqual(
            pmt.to_uint64(
                pmt.dict_ref(rcv_meta, pmt.intern("burst_id"), pmt.PMT_NIL)),
            505)
 def test_002_symbols (self):
     """ 
     Same as before, but operate on symbols
     """
     n_zeros = 1
     items_per_symbol = 3
     gi = 1
     n_symbols = 4
     header = (1, 2, 3)
     payload = (1, 2, 3)
     data_signal = (0,) * n_zeros + (0,) + header + ((0,) + payload) * n_symbols
     trigger_signal = [0,] * len(data_signal)
     trigger_signal[n_zeros] = 1
     # This is dropped:
     testtag1 = gr.tag_t()
     testtag1.offset = 0
     testtag1.key = pmt.string_to_symbol('tag1')
     testtag1.value = pmt.from_long(0)
     # This goes on output 0, item 0 (from the GI)
     testtag2 = gr.tag_t()
     testtag2.offset = n_zeros
     testtag2.key = pmt.string_to_symbol('tag2')
     testtag2.value = pmt.from_long(23)
     # This goes on output 0, item 0 (middle of the header symbol)
     testtag3 = gr.tag_t()
     testtag3.offset = n_zeros + gi + 1
     testtag3.key = pmt.string_to_symbol('tag3')
     testtag3.value = pmt.from_long(42)
     # This goes on output 1, item 1 (middle of the first payload symbol)
     testtag4 = gr.tag_t()
     testtag4.offset = n_zeros + (gi + items_per_symbol) * 2 + 1
     testtag4.key = pmt.string_to_symbol('tag4')
     testtag4.value = pmt.from_long(314)
     data_src = blocks.vector_source_f(data_signal, False, tags=(testtag1, testtag2, testtag3, testtag4))
     trigger_src = blocks.vector_source_b(trigger_signal, False)
     hpd = digital.header_payload_demux(
         len(header) / items_per_symbol, # Header length (in symbols)
         items_per_symbol,               # Items per symbols
         gi,                             # Items per guard time
         "frame_len",                    # Frame length tag key
         "detect",                       # Trigger tag key
         True,                           # Output symbols (not items)
         gr.sizeof_float                 # Bytes per item
     )
     self.assertEqual(pmt.length(hpd.message_ports_in()), 1)
     header_sink = blocks.vector_sink_f(items_per_symbol)
     payload_sink = blocks.vector_sink_f(items_per_symbol)
     self.tb.connect(data_src,    (hpd, 0))
     self.tb.connect(trigger_src, (hpd, 1))
     self.tb.connect((hpd, 0), header_sink)
     self.tb.connect((hpd, 1), payload_sink)
     self.tb.start()
     time.sleep(.2) # Need this, otherwise, the next message is ignored
     hpd.to_basic_block()._post(
             pmt.intern('header_data'),
             pmt.from_long(n_symbols)
     )
     while len(payload_sink.data()) < len(payload) * n_symbols:
         time.sleep(.2)
     self.tb.stop()
     self.tb.wait()
     self.assertEqual(header_sink.data(),  header)
     self.assertEqual(payload_sink.data(), payload * n_symbols)
     ptags_header = []
     for tag in header_sink.tags():
         ptag = gr.tag_to_python(tag)
         ptags_header.append({'key': ptag.key, 'offset': ptag.offset})
     expected_tags_header = [
             {'key': 'tag2', 'offset': 0},
             {'key': 'tag3', 'offset': 0},
     ]
     self.assertEqual(expected_tags_header, ptags_header)
     ptags_payload = []
     for tag in payload_sink.tags():
         ptag = gr.tag_to_python(tag)
         ptags_payload.append({'key': ptag.key, 'offset': ptag.offset})
     expected_tags_payload = [
             {'key': 'frame_len', 'offset': 0},
             {'key': 'tag4', 'offset': 1},
     ]
     self.assertEqual(expected_tags_payload, ptags_payload)
    def test_001_t (self):
        """ Simplest possible test: put in zeros, then header,
        then payload, trigger signal, try to demux.
        The return signal from the header parser is faked via _post()
        Add in some tags for fun.
        """
        n_zeros = 1
        header = (1, 2, 3)
        payload = tuple(range(5, 20))
        data_signal = (0,) * n_zeros + header + payload
        trigger_signal = [0,] * len(data_signal)
        trigger_signal[n_zeros] = 1
        # This is dropped:
        testtag1 = gr.tag_t()
        testtag1.offset = 0
        testtag1.key = pmt.string_to_symbol('tag1')
        testtag1.value = pmt.from_long(0)
        # This goes on output 0, item 0:
        testtag2 = gr.tag_t()
        testtag2.offset = n_zeros
        testtag2.key = pmt.string_to_symbol('tag2')
        testtag2.value = pmt.from_long(23)
        # This goes on output 0, item 2:
        testtag3 = gr.tag_t()
        testtag3.offset = n_zeros + len(header) - 1
        testtag3.key = pmt.string_to_symbol('tag3')
        testtag3.value = pmt.from_long(42)
        # This goes on output 1, item 3:
        testtag4 = gr.tag_t()
        testtag4.offset = n_zeros + len(header) + 3
        testtag4.key = pmt.string_to_symbol('tag4')
        testtag4.value = pmt.from_long(314)

        data_src = blocks.vector_source_f(data_signal, False, tags=(testtag1, testtag2, testtag3, testtag4))
        trigger_src = blocks.vector_source_b(trigger_signal, False)
        hpd = digital.header_payload_demux(
            len(header), 1, 0, "frame_len", "detect", False, gr.sizeof_float
        )
        self.assertEqual(pmt.length(hpd.message_ports_in()), 1)
        header_sink = blocks.vector_sink_f()
        payload_sink = blocks.vector_sink_f()

        self.tb.connect(data_src,    (hpd, 0))
        self.tb.connect(trigger_src, (hpd, 1))
        self.tb.connect((hpd, 0), header_sink)
        self.tb.connect((hpd, 1), payload_sink)
        self.tb.start()
        time.sleep(.2) # Need this, otherwise, the next message is ignored
        hpd.to_basic_block()._post(
                pmt.intern('header_data'),
                pmt.from_long(len(payload))
        )
        while len(payload_sink.data()) < len(payload):
            time.sleep(.2)
        self.tb.stop()
        self.tb.wait()

        self.assertEqual(header_sink.data(),  header)
        self.assertEqual(payload_sink.data(), payload)
        ptags_header = []
        for tag in header_sink.tags():
            ptag = gr.tag_to_python(tag)
            ptags_header.append({'key': ptag.key, 'offset': ptag.offset})
        expected_tags_header = [
                {'key': 'tag2', 'offset': 0},
                {'key': 'tag3', 'offset': 2},
        ]
        self.assertEqual(expected_tags_header, ptags_header)
        ptags_payload = []
        for tag in payload_sink.tags():
            ptag = gr.tag_to_python(tag)
            ptags_payload.append({'key': ptag.key, 'offset': ptag.offset})
        expected_tags_payload = [
                {'key': 'frame_len', 'offset': 0},
                {'key': 'tag4', 'offset': 3},
        ]
        self.assertEqual(expected_tags_payload, ptags_payload)
rc = sock.bind(_ADDR)
#%%
flanks = pmt.make_f32vector(2, 0.0)
pmt.f32vector_set(flanks, 0, np.radians(15))
pmt.f32vector_set(flanks, 1, np.radians(70))
c = pmt.cons(pmt.to_pmt("doa"), flanks)
#%%
sock.recv()
#%%
sock.send(pmt.serialize_str(c))
# %% De acá para arriba anda
key0 = pmt.intern("doa")
val0 = pmt.from_long(123)
val1 = pmt.from_long(234)
val_list = pmt.list2(val0, val1)
pmt.length(val_list)
# %%
a = pmt.make_dict()
# %%
a = pmt.dict_add(a, key0, val_list)
print(pmt.cdr(a))
# %%
pmt.set_car(a, key0)
pmt.set_cdr(a, val_list)
# %%
print(pmt.cons(pmt.to_pmt("doa"), val_list))
# %%
print(
    pmt.cons(pmt.to_pmt("doa"),
             pmt.list2(pmt.from_long(123), pmt.from_long(234))))
# %%