Beispiel #1
0
    def decode_packet(self, pdu):
        # Reset decoder values before decoding next burst
        self.reset()

        # Grab packet PDU data
        meta = pmt.to_python(pmt.car(pdu))
        vector = pmt.to_python(pmt.cdr(pdu))
        self.snr = meta['snr']
        # print 'vector\n', vector
        # print 'vector.dtype\n', vector.dtype
        # print 'type(vector)\n', type(vector)
        self.bits = vector

        # Decode the header (common) part of the packet
        self.decode_header()

        parity_passed = self.check_parity()

        if parity_passed == 0:
            parity_passed = self.correct_errors()

        if parity_passed == 1:
            # If parity check passes, then decode the message contents
            self.decode_message()

            if self.print_level == 'Brief':
                self.print_planes()
Beispiel #2
0
def extract(cls):
    if not inspect.isclass(cls):
        cls = _blk_class(cls)

    spec = inspect.getargspec(cls.__init__)
    defaults = map(repr, spec.defaults or ())
    doc = cls.__doc__ or cls.__init__.__doc__ or ''
    cls_name = cls.__name__

    if len(defaults) + 1 != len(spec.args):
        raise ValueError("Need all default values")

    try:
        instance = cls()
    except Exception as e:
        raise RuntimeError("Can't create an instance of your block: " + str(e))

    name = instance.name()
    params = list(zip(spec.args[1:], defaults))

    sinks = _ports(instance.in_sig(),
                      pmt.to_python(instance.message_ports_in()))
    sources = _ports(instance.out_sig(),
                        pmt.to_python(instance.message_ports_out()))

    return BlockIO(name, cls_name, params, sinks, sources, doc)
    def test_001_t (self):
        """
        First header: Packet length 4, packet num 0
        Second header: Packet 2, packet num 1
        Third header: Invalid (parity bit does not check) (would be len 4, num 2)
        """
        encoded_headers = (
            #   | Number of bytes                    | Packet number                                  | Parity
                0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  1, 0, 0, 0,
                0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0,
                0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  1, 0, 0, 0
        )
        packet_len_tagname = "packet_len"

        src = gr.vector_source_b(encoded_headers)
        parser = digital.packet_headerparser_b(32, packet_len_tagname)
        sink = gr.message_debug()
        self.tb.connect(src, parser)
        self.tb.msg_connect(parser, "header_data", sink, "store")
        self.tb.start()
        time.sleep(1)
        self.tb.stop()
        self.tb.wait()
        self.assertEqual(sink.num_messages(), 3)
        msg1 = pmt.to_python(sink.get_message(0))
        msg2 = pmt.to_python(sink.get_message(1))
        msg3 = pmt.to_python(sink.get_message(2))
        self.assertEqual(msg1, {'packet_len': 4, 'packet_num': 0})
        self.assertEqual(msg2, {'packet_len': 2, 'packet_num': 1})
        self.assertEqual(msg3, False)
Beispiel #4
0
 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 set_mute(self, msg):
        """
        check if the last state in the queue is mute. If so increment the count
        else create a new state in the end of the queue and add the count

        """
        current_mute_n_samples_before = self.mute_n_samples_before
        if len(self.mute_log) > 0:
            last_state = self.mute_log[-1]['mute']
            if last_state == True:
                self.mute_log[-1]['count'] += pmt.to_python(msg)
                return
            else:
                current_unmute_len = max((self.mute_log[-1]['count'], 0))
                if current_unmute_len < self.mute_n_samples_before:  # don't go below 0
                    current_mute_n_samples_before = current_unmute_len

                self.mute_log[-1]['count'] -= current_mute_n_samples_before

        # else do
        self.mute_log.append({
            'mute':
            True,
            'count':
            current_mute_n_samples_before + self.mute_n_samples_after +
            pmt.to_python(msg)
        })
Beispiel #6
0
 def handle_mod_neural(self, pdu):
     t0 = time.time()
     self.mod_packet_cnt += 1
     tag_dict = pmt.to_python(pmt.car(pdu))
     vec = pmt.to_python(pmt.cdr(pdu))
     exploration = 'exploit' if self.run_mode == 'freeze' else 'explore'
     symbs = self.mod.modulate(
         util_data.bits_to_integers(vec, self.bits_per_symbol), exploration)
     self.past_actions = symbs
     ###DEBUG###
     self.actions_hist[self.mod_packet_cnt] = symbs
     ###DEBUG###
     # Spy and header fields
     if not self.use_shared:
         self.gen_preamble()
     classic, _ = self.assemble_packet_neural(vec[self.preamble.size:],
                                              (1 << 16) - 1,
                                              valid=False)
     classic_si = util_data.bits_to_integers(classic, self.bits_per_symbol)
     symbs = np.concatenate([self.spy_mod.modulate(classic_si), symbs])
     self.message_port_pub(
         self.port_id_mod_out,
         pmt.cons(pmt.PMT_NIL, pmt.to_pmt(symbs.astype(np.complex64))))
     t1 = time.time()
     self.logger.debug("neural mod {} handled {} bits in {} seconds".format(
         self.uuid_str, vec.size, t1 - t0))
Beispiel #7
0
    def handle_pdu(self, pdu):
        if not pmt.is_pair(pdu):
            return

        meta = pmt.to_python(pmt.car(pdu)) or {}
        bits = pmt.to_python(pmt.cdr(pdu))

        if meta.get('packed', False):
            bits = numpy.unpackbits(bytearray(bits))

        try:
            output = self.format_output(meta, bits)
            if self.stdout:
                print output
            if self.fp:
                self.fp.write(output)
                self.fp.write('\n')
                if self.flush:
                    self.fp.flush()
        except IndexError as e:
            print >> sys.stderr, "gr-reveng: IndexError: Ran out of bits?"
            print >> sys.stderr, traceback.format_exc(e)
        except ValueError as e:
            print >> sys.stderr, "gr-reveng: TypeError: Something casted wrong!"
            print >> sys.stderr, traceback.format_exc(e)
        except IOError as e:
            print >> sys.stderr, "gr-reveng: IOError: Unable to write to file, closing"
            try:
                self.fp.close()
            except (OSError, IOError):
                pass
            self.fp = None
        except StandardError as e:
            print >> sys.stderr, "gr-reveng: %s: Something went horribly wrong!" % type(e)
            print >> sys.stderr, traceback.format_exc(e)
    def test_001_t(self):
        # Constants
        tag_key = 'in1_tag'
        tag_value = 0
        tag_offset = 0
        in0_value = 1.0+1.0j
        in1_value = 2.717
        in0_data = (in0_value,)*10
        in1_data = (in1_value,)*10
        sink_data = in0_data

        tag = gr.tag_t()
        tag.key = pmt.to_pmt(tag_key)
        tag.value = pmt.to_pmt(tag_value)
        tag.offset = tag_offset

        # Only tag Input 1 of the share block and see if it transfers
        # to Output 0. Also verify that Input 0 stream is propagated to
        # Output 0.
        in0 = blocks.vector_source_c(in0_data, False, 1)
        in1 = blocks.vector_source_f(in1_data, False, 1, (tag,))
        tag_share = blocks.tag_share(gr.sizeof_gr_complex, gr.sizeof_float)
        sink = blocks.vector_sink_c(1)

        self.tb.connect(in0, (tag_share,0))
        self.tb.connect(in1, (tag_share,1))
        self.tb.connect(tag_share, sink)
        self.tb.run()

        self.assertEqual(len(sink.tags()), 1)
        self.assertEqual(pmt.to_python(sink.tags()[0].key), tag_key)
        self.assertEqual(pmt.to_python(sink.tags()[0].value), tag_value)
        self.assertEqual(sink.tags()[0].offset, tag_offset)
        self.assertEqual(sink.data(), sink_data)
    def test_006_basic_nrz(self):

        self.dut = pdu_utils.pdu_preamble([], [], 1, 0, True)
        self.connectUp()

        input_data = pmt.init_u8vector(8, [1, 0, 1, 1, 0, 0, 1, 0])
        input_dict = pmt.dict_add(pmt.make_dict(), pmt.intern("KEY"),
                                  pmt.intern("VALUE"))
        input_pdu = pmt.cons(input_dict, input_data)

        expected_data = [1, -1, 1, 1, -1, -1, 1, -1]
        expected_dict = pmt.dict_add(pmt.make_dict(), pmt.intern("KEY"),
                                     pmt.intern("VALUE"))
        expected_pdu = pmt.cons(
            expected_dict, pmt.init_f32vector(len(expected_data),
                                              expected_data))

        self.tb.start()
        time.sleep(.001)
        self.emitter.emit(input_pdu)
        time.sleep(.01)
        self.tb.stop()
        self.tb.wait()

        self.assertEqual(1, self.debug.num_messages())

        print("test_006_basic_nrz:")
        print("pdu expected: " + repr(pmt.car(expected_pdu)))
        print("pdu got:      " + repr(pmt.car(self.debug.get_message(0))))
        print("data expected: " + repr(pmt.to_python(pmt.cdr(expected_pdu))))
        print("data got:      " +
              repr(pmt.to_python(pmt.cdr(self.debug.get_message(0)))))
        print

        self.assertTrue(pmt.equal(self.debug.get_message(0), expected_pdu))
    def control_handler(self, msg):
        meta = pmt.to_python(pmt.car(msg))
        data = pmt.to_python(pmt.cdr(msg))
        #print data
        if meta == 'takeoff':
            self.data[8] = 1
        elif meta == 'land':
            self.data[8] = 2
        elif meta == 'rc_override':
            self.data[8] = 3
            print(data)
        elif meta == 'disarm':
            self.data[8] = 4
        elif meta == 'heartbeat':
            self.data[8] = 5
        self.data[0] = data[0]
        self.data[1] = data[1]
        self.data[2] = data[2]
        self.data[7] = data[7]
        ndata = numpy.array(self.data, dtype=numpy.int32)
        nbytes = ndata.tobytes()
        bufnp = numpy.frombuffer(nbytes, dtype=numpy.uint8)

        self.message_port_pub(pmt.intern("Vector_OUT"),
                              pmt.cons(pmt.PMT_NIL, pmt.to_pmt(bufnp)))
    def handler(self, pdu):

        # Grab packet PDU data
        meta = pmt.to_python(pmt.car(pdu))
        vector = pmt.cdr(pdu)
        if not pmt.is_u8vector(vector):
            print "[ERROR] Received invalid message type. Expected u8vector"
            return

        vector = pmt.to_python(pmt.cdr(pdu))

        self.snr = meta['snr']
        self.meta = meta
        # print 'vector\n', vector
        # print 'vector.dtype\n', vector.dtype
        # print 'type(vector)\n', type(vector)
        self.bits = vector

        #print meta
        #print self.bits

        #data = list(pmt.u8vector_elements(msg))
        #packed = self._pack_bytes(data)
        #hex_str = binascii.hexlify(packed)
        #print data, hex_str
        #self._decode_type(packed)
        try:
            self._decode_header()
            self._parse_payload()
            parity_passed = self._check_parity()
        except Exception as e:  # catch *all* exceptions
            print e
Beispiel #12
0
    def work(self, input_items, output_items):
        print("interleaver items read: {}".format(self.nitems_read(0)))
        in0 = input_items[0]
        out = output_items[0]
        # print("=========DEBUG OUTPUT=========")
        # print("in0 len: {}, out len: {}".format(len(in0),len(out)))
        
        tags = self.get_tags_in_window(0,0,len(in0),pmt.intern("packet_len"))
        for tag in tags:
            key = pmt.to_python(tag.key)
            value = pmt.to_python(tag.value)
            offset = tag.offset
            # self.add_item_tag(0,offset,tag.key,pmt.from_long(value/192))
            print("tag: {}, value: {}, offset: {}".format(key,value,offset))

        reverse = False
        assert(len(in0) % self.ncbps == 0)
        symbols = min([len(in0) / self.ncbps])
        for i in range(0,symbols):
            out_vec = np.zeros(self.ncbps,dtype=np.uint8)
            for k in range(0,self.ncbps):
                permutation_index = self.second[self.first[k]]
                if reverse:
                    out_vec[k] = in0[self.ncbps * i + permutation_index]
                else:
                    # print("out i: {}, in0 i: {},".format(i * self.ncbps + k,i * self.ncbps + self.second[self.first[k]]))
                    # out_vec[k] = in0[(self.second[self.first[k]])]
                    out_vec[permutation_index] = in0[self.ncbps* i + k]
            out[i] = out_vec
             
        return len(out)
Beispiel #13
0
 def work(self, input_items, output_items):
     while True:
         try: msg = self.pop_msg_queue()
         except: return -1
         result = self.handle_request(pmt.to_python(msg.key), pmt.to_python(msg.value))
         msg.value = pmt.from_python(result)
         if self._result_msg: self.post_msg(0, msg)
 def test_001_t (self):
     """
     First header: Packet length 4, packet num 0
     Second header: Packet 2, packet num 1
     Third header: Invalid (parity bit does not check) (would be len 4, num 2)
     """
     encoded_headers = (
         #   | Number of bytes                    | Packet number                                  | Parity
             0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  1, 0, 0, 0,
             0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0,
             0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  1, 0, 0, 0
     )
     packet_len_tagname = "packet_len"
     random_tag = gr.tag_t()
     random_tag.offset = 5
     random_tag.key = pmt.string_to_symbol("foo")
     random_tag.value = pmt.from_long(42)
     src = blocks.vector_source_b(encoded_headers, tags=(random_tag,))
     parser = digital.packet_headerparser_b(32, packet_len_tagname)
     sink = blocks.message_debug()
     self.tb.connect(src, parser)
     self.tb.msg_connect(parser, "header_data", sink, "store")
     self.tb.start()
     time.sleep(1)
     self.tb.stop()
     self.tb.wait()
     self.assertEqual(sink.num_messages(), 3)
     msg1 = pmt.to_python(sink.get_message(0))
     msg2 = pmt.to_python(sink.get_message(1))
     msg3 = pmt.to_python(sink.get_message(2))
     self.assertEqual(msg1, {'packet_len': 4, 'packet_num': 0, 'foo': 42})
     self.assertEqual(msg2, {'packet_len': 2, 'packet_num': 1})
     self.assertEqual(msg3, False)
    def test_simple(self):
        self.emitter = pdu_utils.message_emitter()
        self.ctm2 = pdu_utils.pdu_complex_to_mag2()
        self.debug = blocks.message_debug()
        self.tb.msg_connect((self.emitter, 'msg'), (self.ctm2, 'cpdus'))
        self.tb.msg_connect((self.ctm2, 'fpdus'), (self.debug, 'store'))

        # gnuradio uses single-precision floats by default
        i_vec = pmt.init_c32vector(3, [3 + 4j, 1 + 0j, 0 + 1j])
        e_vec = pmt.init_f32vector(3, [25, 1, 1])

        in_pdu = pmt.cons(pmt.make_dict(), i_vec)
        e_pdu = pmt.cons(pmt.make_dict(), e_vec)

        self.tb.start()
        time.sleep(.001)
        self.emitter.emit(in_pdu)
        time.sleep(.01)
        self.tb.stop()
        self.tb.wait()

        print("test ctm2:")
        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()

        self.assertTrue(pmt.equal(self.debug.get_message(0), e_pdu))
 def test_003_ofdm (self):
     """ Header 1: 193 bytes
     Header 2: 8 bytes
     2 bits per complex symbol, 32 carriers => 64 bits = 8 bytes per OFDM symbol
     """
     encoded_headers = (
         #   | Number of bytes                    | Packet number                                  | Parity
             1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  1, 0, 0, 0,
             0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,  1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0,
     )
     packet_len_tagname = "packet_len"
     frame_len_tagname = "frame_len"
     src = gr.vector_source_b(encoded_headers)
     header_formatter = digital.packet_header_ofdm(
             (range(32),), # 32 carriers are occupied (which doesn't matter here)
             1,         # 1 OFDM symbol per header (= 32 bits)
             packet_len_tagname,
             frame_len_tagname,
             "packet_num",
             1,         # 1 bit per header symbols (BPSK)
             2          # 2 bits per payload symbol (QPSK)
     )
     parser = digital.packet_headerparser_b(header_formatter.base())
     sink = gr.message_debug()
     self.tb.connect(src, parser)
     self.tb.msg_connect(parser, "header_data", sink, "store")
     self.tb.start()
     time.sleep(1)
     self.tb.stop()
     self.tb.wait()
     self.assertEqual(sink.num_messages(), 2)
     msg1 = pmt.to_python(sink.get_message(0))
     msg2 = pmt.to_python(sink.get_message(1))
     self.assertEqual(msg1, {'packet_len': 193*4, 'frame_len': 25, 'packet_num': 0})
     self.assertEqual(msg2, {'packet_len': 8*4, 'frame_len': 1, 'packet_num': 1})
    def test_001_t (self):
        """
        First header: Packet length 4, packet num 0
        Second header: Packet 2, packet num 1
        Third header: Invalid (parity bit does not check) (would be len 4, num 2)
        """
        encoded_headers = (
            #   | Number of bytes                    | Packet number                                  | Parity
                0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  1, 0, 0, 0,
                0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0, 0, 0, 0,
                0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,  0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  1, 0, 0, 0
        )
        packet_len_tagname = "packet_len"

        random_tag = gr.gr_tag_t()
        random_tag.offset = 5
        random_tag.key = pmt.pmt_string_to_symbol("foo")
        random_tag.value = pmt.pmt_from_long(42)
        src = gr.vector_source_b(encoded_headers, tags=(random_tag,))
        parser = digital.packet_headerparser_b(32, packet_len_tagname)
        sink = gr.message_debug()
        self.tb.connect(src, parser)
        self.tb.msg_connect(parser, "header_data", sink, "store")
        self.tb.start()
        time.sleep(1)
        self.tb.stop()
        self.tb.wait()
        self.assertEqual(sink.num_messages(), 3)
        msg1 = pmt.to_python(sink.get_message(0))
        msg2 = pmt.to_python(sink.get_message(1))
        msg3 = pmt.to_python(sink.get_message(2))
        self.assertEqual(msg1, {'packet_len': 4, 'packet_num': 0, 'foo': 42})
        self.assertEqual(msg2, {'packet_len': 2, 'packet_num': 1})
        self.assertEqual(msg3, False)
Beispiel #18
0
    def test_001_uint8(self):
        '''
        uint8_t input data, no decimation, no filter
        '''
        self.dut = pdu_utils.pdu_fir_filter(1, [1.0])
        self.connectUp()

        i_data = [1, 0, 0, 0] * 5
        i_meta = pmt.dict_add(pmt.make_dict(), pmt.intern("sample_rate"),
                              pmt.from_float(1000.0))
        in_pdu = pmt.cons(i_meta, pmt.init_u8vector(len(i_data), i_data))

        e_data = [1, 0, 0, 0] * 5
        e_meta = pmt.dict_add(pmt.make_dict(), pmt.intern("sample_rate"),
                              pmt.from_float(1000.0))
        e_pdu = pmt.cons(e_meta, pmt.init_u8vector(len(e_data), e_data))

        self.tb.start()
        time.sleep(.01)
        self.emitter.emit(in_pdu)
        time.sleep(.1)
        self.tb.stop()
        self.tb.wait()

        print("test_001:")
        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

        self.assertTrue(pmt.equal(self.debug.get_message(0), e_pdu))
Beispiel #19
0
 def vector_handler(self, msg):
     meta = pmt.to_python(pmt.car(msg))
     databuf = pmt.to_python(pmt.cdr(msg))
     data = numpy.frombuffer(databuf, dtype=numpy.uint32)
     print "vector handler"
     print data
     self.data[0] = int(data[0])
     self.data[1] = int(data[1])
     self.data[2] = int(data[2])
     self.data[7] = int(data[7])
     if (data[8] == 1):
         meta = pmt.to_pmt('takeoff')
         pmtdata = pmt.to_pmt(self.data)
         msg = pmt.cons(meta, pmtdata)
     elif (data[8] == 2):
         meta = pmt.to_pmt('land')
         pmtdata = pmt.to_pmt(self.data)
         msg = pmt.cons(meta, pmtdata)
     elif (data[8] == 3):
         meta = pmt.to_pmt('rc_override')
         pmtdata = pmt.to_pmt(self.data)
         msg = pmt.cons(meta, pmtdata)
     elif (data[8] == 4):
         meta = pmt.to_pmt('disarm')
         pmtdata = pmt.to_pmt(self.data)
         msg = pmt.cons(meta, pmtdata)
     elif (data[8] == 5):
         meta = pmt.to_pmt('heartbeat')
         pmtdata = pmt.to_pmt(self.data)
         msg = pmt.cons(meta, pmtdata)
     self.message_port_pub(pmt.intern("Control_OUT"), msg)
 def test_004_ofdm_scramble(self):
     """
     Test scrambling for OFDM header gen
     """
     header_len = 32
     packet_length = 23
     packet_len_tagname = "packet_len"
     frame_len_tagname = "frame_len"
     data, tags = tagged_streams.packets_to_vectors([range(packet_length),range(packet_length),], packet_len_tagname)
     src = blocks.vector_source_b(data, False, 1, tags)
     header_formatter = digital.packet_header_ofdm(
             (range(32),), # 32 carriers are occupied (which doesn't matter here)
             1,         # 1 OFDM symbol per header (= 32 bits)
             packet_len_tagname,
             frame_len_tagname,
             "packet_num",
             1,         # 1 bit per header symbols (BPSK)
             2,          # 2 bits per payload symbol (QPSK)
             scramble_header=True
     )
     header_gen = digital.packet_headergenerator_bb(header_formatter.base())
     header_parser = digital.packet_headerparser_b(header_formatter.base())
     sink = blocks.message_debug()
     self.tb.connect(src, header_gen, header_parser)
     self.tb.msg_connect(header_parser, "header_data", sink, "store")
     self.tb.start()
     time.sleep(1)
     self.tb.stop()
     self.tb.wait()
     msg = pmt.to_python(sink.get_message(0))
     self.assertEqual(msg, {'packet_len': packet_length, 'packet_num': 0, 'frame_len': 4})
     msg = pmt.to_python(sink.get_message(1))
     self.assertEqual(msg, {'packet_len': packet_length, 'packet_num': 1, 'frame_len': 4})
Beispiel #21
0
    def test_000(self):
        num_msgs = 10
        msg_interval = 1000
        msg_list = []
        for i in range(num_msgs):
            msg_list.append(pmt.from_long(i))

        # Create vector source with dummy data to trigger messages
        src_data = []
        for i in range(num_msgs * msg_interval):
            src_data.append(float(i))
        src = blocks.vector_source_f(src_data, False)
        msg_gen = message_generator(msg_list, msg_interval)
        msg_cons = message_consumer()

        # Connect vector source to message gen
        self.tb.connect(src, msg_gen)

        # Connect message generator to message consumer
        self.tb.msg_connect(msg_gen, 'out_port', msg_cons, 'in_port')

        # Verify that the messgae port query functions work
        self.assertEqual(
            pmt.to_python(msg_gen.message_ports_out())[0], 'out_port')
        self.assertEqual(
            'in_port' in pmt.to_python(msg_cons.message_ports_in()), True)

        # Run to verify message passing
        self.tb.run()

        # Verify that the message consumer got all the messages
        self.assertEqual(num_msgs, len(msg_cons.msg_list))
        for i in range(num_msgs):
            self.assertTrue(pmt.equal(msg_list[i], msg_cons.msg_list[i]))
Beispiel #22
0
 def command_handler(self, msg):
     print('receive message')
     meta = pmt.to_python(pmt.car(msg))
     data = pmt.to_python(pmt.cdr(msg))
     print(meta)
     print(data)
     if meta == 'takeoff':
         print('call takeoff')
         self.arm_and_takeoff(data)
     elif meta == 'rc_override':
         print(data)
         #self.data=data
         print('rc_override')
         #self.set_servo(data)
         self.set_channel_overrides(data)
         self.data = data
     elif meta == 'land':
         print('land')
         self.set_land()
     elif meta == 'disarm':
         print('disarm')
         self.disarm()
     elif meta == 'heartbeat':
         print('heartbeat')
         self.receive_hearbeat()
Beispiel #23
0
    def decode_packet(self, pdu):
        # Reset decoder values before decoding next burst
        self.reset()

        # Grab packet PDU data
        meta = pmt.to_python(pmt.car(pdu))
        vector = pmt.to_python(pmt.cdr(pdu))
        self.timestamp = meta["timestamp"]
        self.datetime = datetime.datetime.utcfromtimestamp(
            self.timestamp).strftime("%Y-%m-%d %H:%M:%S.%f UTC")
        self.snr = meta["snr"]
        # print "vector\n", vector
        # print "vector.dtype\n", vector.dtype
        # print "type(vector)\n", type(vector)
        self.bits = vector

        # Decode the header (common) part of the packet
        self.decode_header()

        parity_passed = self.check_parity()

        if parity_passed == 0:
            parity_passed = self.correct_errors()

        if parity_passed == 1:
            # If parity check passes, then decode the message contents
            self.decode_message()

            if self.print_level == "Brief":
                self.print_planes()
Beispiel #24
0
    def handle_pdu(self, pdu):
        if not pmt.is_pair(pdu):
            return

        meta = pmt.to_python(pmt.car(pdu)) or {}
        data = pmt.to_python(pmt.cdr(pdu))
        if meta.get('packed', False):
            bytez = str(bytearray(data))
        else:
            bytez = numpy.packbits(bytearray(data))

        ch_num = meta.get('name')
        ts = meta.get('ts')

        try:
            pkt = scapy_gotenna.Gotenna(bytez)
        except scapy.error:
            print >> sys.stderr, 'Bad packet:', bytez.encode('hex')
            return

        try:
            if ch_num == 'ch4' and pkt.type in [0x10, 0x11]:
                self.channels.get('ch%d' % pkt.next_chan).nom_packet(ts, pkt)
            else:
                self.channels.get(ch_num).nom_packet(ts, pkt)
        except StandardError as e:
            print >> sys.stderr, 'Failed calling nom_packet'
            print >> sys.stderr, 'Bad packet:', bytez.encode('hex')
            print >> sys.stderr, traceback.format_exc(e)
    def test_010_t (self):
        # PHR prefixer to removal
        data_in = pmt.cons(pmt.PMT_NIL, pmt.make_u8vector(2*self.c.phy_packetsize_bytes,170))
        self.src = blocks.message_strobe(data_in,100)
        self.snk = blocks.message_debug()

        self.tb.msg_connect(self.src, "strobe", self.fragmentation, "in")
        self.tb.msg_connect(self.fragmentation, "out", self.phr_prefixer, "in")
        self.tb.msg_connect(self.phr_prefixer, "out", self.zeropadding, "in")
        self.tb.connect(self.zeropadding, self.demux)
        self.tb.connect((self.demux,0), self.codeword_mapper_I, self.interleaver_I, self.preamble_sfd_prefixer_I, (self.qpsk_mapper,0))
        self.tb.connect((self.demux,1), self.codeword_mapper_Q, self.interleaver_Q, self.preamble_sfd_prefixer_Q, (self.qpsk_mapper,1))
        self.tb.connect(self.qpsk_mapper, self.dqpsk_mapper, self.dqcsk_mapper, self.dqcsk_demapper, self.dqpsk_demapper, self.qpsk_demapper)
        self.tb.connect((self.qpsk_demapper,0), self.preamble_sfd_removal_I, self.deinterleaver_I, self.codeword_demapper_I, (self.mux,0))        
        self.tb.connect((self.qpsk_demapper,1), self.preamble_sfd_removal_Q, self.deinterleaver_Q, self.codeword_demapper_Q, (self.mux,1)) 
        self.tb.connect(self.mux, self.zeropadding_removal) 
        self.tb.msg_connect(self.zeropadding_removal, "out", self.phr_removal, "in") 
        self.tb.msg_connect(self.phr_removal, "out", self.snk, "store")

        self.tb.start()
        time.sleep(0.3)
        self.tb.stop()

        msg_out1 = self.snk.get_message(0)
        msg_out2 = self.snk.get_message(1)
        data_out1 = pmt.to_python(msg_out1)[1]
        data_out2 = pmt.to_python(msg_out2)[1]
        ref = pmt.to_python(data_in)[1]
        self.assertTrue((data_out1==ref[:len(data_out1)]).all() and (data_out2==ref[:len(data_out2)]).all())  
Beispiel #26
0
def extract(cls):
    try:
        from gnuradio import gr
        import pmt
    except ImportError:
        raise EnvironmentError("Can't import GNU Radio")

    if not inspect.isclass(cls):
        cls = _find_block_class(cls, gr.gateway.gateway_block)

    spec = inspect.getargspec(cls.__init__)
    defaults = map(repr, spec.defaults or ())
    doc = cls.__doc__ or cls.__init__.__doc__ or ''
    cls_name = cls.__name__

    if len(defaults) + 1 != len(spec.args):
        raise ValueError("Need all __init__ arguments to have default values")

    try:
        instance = cls()
    except Exception as e:
        raise RuntimeError("Can't create an instance of your block: " + str(e))

    name = instance.name()
    params = list(zip(spec.args[1:], defaults))

    sinks = _ports(instance.in_sig(),
                   pmt.to_python(instance.message_ports_in()))
    sources = _ports(instance.out_sig(),
                     pmt.to_python(instance.message_ports_out()))

    return BlockIO(name, cls_name, params, sinks, sources, doc)
Beispiel #27
0
    def test_005_fff_down(self):
        self.dut = pdu_utils.pdu_pfb_resamp_fff([1], 1, 0.5)
        self.connectUp()

        in_data = [1, 1, 0, 0] * 4
        in_pdu = pmt.cons(pmt.make_dict(), pmt.init_f32vector(len(in_data), in_data))

        expected_data = [1, 0] * 4
        expected_pdu = pmt.cons(pmt.make_dict(), pmt.init_f32vector(len(expected_data), expected_data))

        self.tb.start()
        time.sleep(.001)
        self.emitter.emit(in_pdu)
        time.sleep(.01)
        self.tb.stop()
        self.tb.wait()

        self.assertEqual(1, self.debug.num_messages())

        print("test_005_fff_down:")
        print("pdu expected: " + repr(pmt.car(expected_pdu)))
        print("pdu got:      " + repr(pmt.car(self.debug.get_message(0))))
        print("data expected: " + repr(pmt.to_python(pmt.cdr(expected_pdu))))
        print("data got:      " + repr(pmt.to_python(pmt.cdr(self.debug.get_message(0)))))
        print

        self.assertTrue(pmt.equal(self.debug.get_message(0), expected_pdu))
def tag_to_python(tag):
    """ Convert a stream tag to a Python-readable object """
    newtag = PythonTag()
    newtag.offset = tag.offset
    newtag.key = pmt.to_python(tag.key)
    newtag.value = pmt.to_python(tag.value)
    newtag.srcid = pmt.to_python(tag.srcid)
    return newtag
Beispiel #29
0
def tag_to_python(tag):
    """ Convert a stream tag to a Python-readable object """
    newtag = PythonTag()
    newtag.offset = tag.offset
    newtag.key = pmt.to_python(tag.key)
    newtag.value = pmt.to_python(tag.value)
    newtag.srcid = pmt.to_python(tag.srcid)
    return newtag
 def assertMessages(self, expected_messages):
     expected_pythonic_messages = [
         pmt.to_python(message) for message in expected_messages
     ]
     actual_pythonic_messages = [
         pmt.to_python(message) for message in self.dst.messages
     ]
     numpy.testing.assert_equal(actual_pythonic_messages,
                                expected_pythonic_messages)
Beispiel #31
0
def tag_to_dict(t):
    d = {
        "offset": t.offset,
        "key": pmt.to_python(t.key),
        "value": pmt.to_python(t.value),
        "srcid": pmt.to_python(t.srcid)
    }

    return d
Beispiel #32
0
    def handle_pkt(self, msg_pmt):
        """ Make PDU into message and save it in the queque"""
        # Collect metadata, convert to Python format:
        meta = pmt.to_python(pmt.car(msg_pmt))

        # Collect message, convert to Python format:
        msg = pmt.to_python(pmt.cdr(msg_pmt))
        self.pktcnt += 1
        print self.pktcnt
        self.msg_queue.append(msg)
Beispiel #33
0
def iq_packet_to_dict(pkt):
    '''
    convert an iq packet in pmt format back to a dictionary
    '''

    d = {
        "meta": pmt.to_python(pmt.car(pkt)),
        "data": pmt.to_python(pmt.cdr(pkt))
    }

    return d
Beispiel #34
0
    def handle_msg(self, msg_pmt):
        print(msg_pmt)

        car = pmt.to_python(pmt.car(msg_pmt))
        if car == 'cmd':
            self.execute_cmd(bytes.fromhex(pmt.to_python(pmt.cdr(msg_pmt))))
            self.message_port_pub(pmt.intern(self.port_out_name),
                                  pmt.intern('done'))

        elif car == 'rf':
            self.handle_rf_pkt(bytes.fromhex(pmt.to_python(pmt.cdr(msg_pmt))))
Beispiel #35
0
    def work(self, input_items, output_items):
        """
        Work averages all input vectors and outputs one vector for each N inputs
        """
        inn = input_items[0]  # vectors of I/Q (complex) samples

        # get the number of input vectors
        nv = len(inn)  # number of events in this port

        # get any tags of a new detected event
        #        tags = self.get_tags_in_window(0, 0, +self.vlen, pmt.to_pmt('event'))
        tags = self.get_tags_in_window(0, 0, +self.vlen)
        # if there are tags, then a new event was detected
        if len(tags) > 0:
            for tag in tags:
                #                print 'Tag: ', tag
                key = pmt.to_python(tag.key)
                value = pmt.to_python(tag.value)
                if key == 'MJD':
                    self.eventmjd = value
#                    print 'Tag MJD : %15.9f' % (self.eventmjd)
                elif key == 'PEAK':
                    self.emagnitude = value
#                    print 'Tag PEAK: %7.4f' % (self.emagnitude)
                elif key == 'RMS':
                    self.erms = value
#                    print 'Tag RMs : %7.4f' % (self.erms)
                else:
                    print 'Unknown Tag: ', value

        # for all input vectors
        for i in range(nv):
            # if a new Modified Julian Day, then an event was detected
            if self.eventmjd > self.lastmjd:
                # log the event
                self.ecount = self.ecount + 1
                print "\nEvent   Logged: %15.9f (MJD) %9.4f %8.4f" % (
                    self.eventmjd, self.emagnitude, self.erms)
                imjd = np.int(self.eventmjd)
                seconds = (self.eventmjd - imjd) * 86400.
                isecond = np.int(seconds)
                microseconds = (seconds - isecond) * 1.e6
                self.lastmjd = self.eventmjd
                outline = self.pformat % (self.ecount, self.eventmjd, isecond,
                                          microseconds, self.emagnitude,
                                          self.erms)
                try:
                    with open(self.logname, "a+") as f:
                        f.write(outline)
                        f.close()
                except:
                    continue
            # end for all input events
        return nv
Beispiel #36
0
 def work(self, input_items, output_items):
     nread = self.nitems_read(0)
     tags = self.get_tags_in_range(0, nread, nread + len(input_items[0]))
     for tag in tags:
         self.tags.append({
             "key": pmt.to_python(tag.key),
             "offset": tag.offset,
             "value": pmt.to_python(tag.value)
         })
     output_items[0][:] = input_items[0]
     return len(output_items[0])
Beispiel #37
0
 def work(self, input_items, output_items):
     tags = self.get_tags_in_window(0, 0, len(input_items[0]))
     if (tags):
         for tag in tags:
             self.tags.append({
                 "key": pmt.to_python(tag.key),
                 "offset": tag.offset,
                 "value": pmt.to_python(tag.value)
             })
     output_items[0][:] = input_items[0]
     return len(output_items[0])
Beispiel #38
0
 def handler(self, pdu):
     meta = pmt.to_python(pmt.car(pdu))
     x = pmt.to_python(pmt.cdr(pdu))
     z = l2.Raw(x.tostring())
     if(meta.has_key("timestamp")):
         t = meta['timestamp']
         if( type(t) == tuple ):
             t = t[0]+t[1]
         else :
             t = t
         z.time = t
     self.pcap.write(z);
Beispiel #39
0
    def test_basic_types(self):
        self.assertEqual(42, pmt.to_python(pmt.pmt_from_long(42)))
        self.assertTrue(pmt.pmt_equal(pmt.pmt_from_long(42), pmt.from_python(42)))

        self.assertEqual(4.2, pmt.to_python(pmt.pmt_from_double(4.2)))
        self.assertTrue(pmt.pmt_equal(pmt.pmt_from_double(4.2), pmt.from_python(4.2)))

        self.loopback(None)
        self.loopback(42)
        self.loopback(4.2)
        self.loopback(4.2j)
        self.loopback("42")
Beispiel #40
0
    def work(self, input_items, output_items):
        self.post_msg(0, pmt.from_python("multx2"), pmt.from_python(((42,), None)))

        msg = self.pop_msg_queue()
        assert(pmt.to_python(msg.key) == "multx2")
        request, result, error = pmt.to_python(msg.value)

        print(error)
        assert(not error)
        print(result)
        assert(result == 42*2)

        return -1
Beispiel #41
0
    def app_rx(self,msg):
        try:            
            meta = pmt.car(msg)
            data =  pmt.cdr(msg)
        except:
            raise NameError("mac - input not a PDU")
            
        if pmt.is_u8vector(data):
            data = pmt.u8vector_elements(data)
        else:
            raise NameError("Data is not u8 vector")

        meta_dict = pmt.to_python(meta)
        if not (type(meta_dict) is dict):
            meta_dict = {}
        
        #double check to make sure correct meta data was in pdu
        if 'EM_USE_ARQ' in meta_dict.keys() and 'EM_DEST_ADDR' in meta_dict.keys():
            #assign tx path depending on whether PMT_BOOL EM_USE_ARQ is true or false
            if(meta_dict['EM_USE_ARQ']):
                self.queue.put( (data,meta_dict) )
            else:
                self.tx_no_arq(( data,meta_dict) ,USER_IO_PROTOCOL_ID)
        else:
            raise NameError("EM_USE_ARQ and/or EM_DEST_ADDR not specified in PDU")
Beispiel #42
0
    def deframe_APDU(self, msg_pmt):
        if pmt.is_blob(msg_pmt):
            blob = msg_pmt
            # print "is blob"
        elif pmt.is_pair(msg_pmt):
            blob = pmt.cdr(msg_pmt)
            # print "is pair"
        else:
            print "Formato desconocido"
            return
        data_np = pmt.to_python(blob)  # numpy.ndarray
        data_py = data_np.tolist()  # python list
        # print "Paquete",data_py,data_py.__class__
        if data_py[2:4] == [0xFF, 0xFF]:
            index = 16
        else:
            index = 24
        del data_py[:index]  # FC(2),Dst_Add(2),Src_Add(2),Radio(1),Sec_N(1),X->Dst_IEEE(8), Src_IEEE(8)
        # print "DEPACKED-->",data_py

        # Crea un PMT vacio:
        send_pmt = pmt.make_u8vector(len(data_py), ord(" "))
        # Copy all characters to the u8vector:
        for i in range(len(data_py)):
            pmt.u8vector_set(send_pmt, i, data_py[i])

            # Send the message:
        self.message_port_pub(pmt.intern("out"), pmt.cons(pmt.PMT_NIL, send_pmt))
 def handle_msg(self, msg):
     if pmt.dict_has_key(msg, pmt.intern(self.len_tag_key)):
         packet_len = pmt.to_python(msg)[self.len_tag_key]
         msg = pmt.dict_delete(msg, pmt.intern(self.len_tag_key))
         msg = pmt.dict_add(msg, pmt.intern(self.len_tag_key), pmt.from_long(packet_len * 8))
         
     self.message_port_pub(self.msg_buf_out, msg)
Beispiel #44
0
 def test_002_tags_plus_data(self):
     packet_len = 16
     src_data = range(packet_len)
     tag1 = gr.tag_t()
     tag1.offset = 0
     tag1.key = pmt.string_to_symbol('spam')
     tag1.value = pmt.from_long(23)
     tag2 = gr.tag_t()
     tag2.offset = 10 # Must be < packet_len
     tag2.key = pmt.string_to_symbol('eggs')
     tag2.value = pmt.from_long(42)
     src = blocks.vector_source_f(src_data, tags=(tag1, tag2))
     s2ts = blocks.stream_to_tagged_stream(gr.sizeof_float, vlen=1, packet_len=packet_len, len_tag_key="packet_len")
     ts2pdu = blocks.tagged_stream_to_pdu(blocks.float_t, "packet_len")
     dbg = blocks.message_debug()
     self.tb.connect(src, s2ts, ts2pdu)
     self.tb.msg_connect(ts2pdu, "pdus", dbg, "store")
     self.tb.start()
     while dbg.num_messages() < 1:
         time.sleep(0.1)
     self.tb.stop()
     self.tb.wait()
     result_msg = dbg.get_message(0)
     metadata = pmt.to_python(pmt.car(result_msg))
     vector   = pmt.f32vector_elements(pmt.cdr(result_msg))
     self.assertEqual(metadata, {'eggs': 42, 'spam': 23})
     self.assertFloatTuplesAlmostEqual(tuple(vector), src_data)
Beispiel #45
0
    def test_003_asm_mask (self):
        # asm with errors
        asm = (0x1f, 0xcf, 0xf0, 0x1d)
        frame_len = 223
        random_data = tuple(random.randint(0, 255) for _ in range(frame_len))

        data_in = asm + random_data
        
        src = blocks.vector_source_b(data_in, repeat=True)
        unpack = blocks.unpack_k_bits_bb(8)
        mapper = digital.map_bb((1,0))
        # mask to ignore errors
        corr = ccsds.correlator(0x1acffc1d, 0xf0fff0ff, 0, frame_len)
        dbg = blocks.message_debug()
        self.tb.connect(src, unpack, mapper, corr)
        self.tb.msg_connect((corr, 'out'), (dbg, 'store'))
        self.tb.start()

        while dbg.num_messages() < 1:
            time.sleep(0.001)

        self.tb.stop()
        self.tb.wait()

        msg = dbg.get_message(0)
        data_out = tuple(pmt.to_python(pmt.cdr(msg)))
        
        assert frame_len == len(data_out)
        assert random_data == data_out
Beispiel #46
0
 def _app_rx(self, msg):
     # verify structure, must be meta-data pair
     try:
         meta = pmt.car(msg)
         data = pmt.cdr(msg)
     except:
         # wrong structure!
         if self.debug_stderr:
             sys.stderr.write("in _app_rx(): message is not a PDU\n")
         # do nothing!
         return
     # is data a vector of unsigned chars?
     if pmt.is_u8vector(data):
         # yes! convert to python data type
         data = pmt.u8vector_elements(data)
     else:
         # no!
         if self.debug_stderr:
             sys.stderr.write("in _app_rx(): data is not a u8vector\n")
         # do nothing!
         return
     # convert meta data to a Python dictionary
     meta_dict = pmt.to_python(meta)
     if not (type(meta_dict) is dict):
         meta_dict = {}
     # send the packet
     self.send_pkt_radio(data, meta_dict, self.pkt_cnt)
     # increment packet number
     self.pkt_cnt = (self.pkt_cnt + 1) % 256
    def test_001_t (self):
        ''' Test fixed length packet '''
        # set up fg
        sync = map(int, bin(0xd391)[2:].zfill(16))
        data = map(int, bin(0xdeadbeef)[2:].zfill(32))
        stream = ([0] * 30) + sync + data + ([0] * 30)

        src = blocks.vector_source_b(stream)
        test_blk = reveng.packet_deframer('boop', sync, True, len(data), 0, 0, 0, False)
        sink = blocks.message_debug()

        self.tb.connect(src, test_blk)
        self.tb.msg_connect(test_blk, 'out', sink, 'store')
        self.tb.run()

        # check data
        rec_msg = pmt.to_python(sink.get_message(0))

        self.assertTrue(isinstance(rec_msg, tuple))
        self.assertTrue(len(rec_msg) == 2)

        (meta, bits) = rec_msg
        self.assertTrue(isinstance(meta, dict))
        self.assertTrue(isinstance(bits, numpy.ndarray))
        self.assertTrue(list(bits) == data)
    def test_010_t (self):
        '''
        Test two back-to-back variable length packets. Length is indexed one
        byte after sync. Two additional bytes for checksum after data packet.
        '''
        # set up fg
        sync = map(int, bin(0xd391)[2:].zfill(16))
        txid = map(int, bin(0x0001)[2:].zfill(16))
        plen = map(int, bin(4)[2:].zfill(8))
        data = map(int, bin(0xdeadbeef)[2:].zfill(32))
        csum = map(int, bin(0xa55a)[2:].zfill(16))

        pkt = txid + plen + data + csum
        stream = ([0] * 30) + sync + pkt + sync + pkt + ([0] * 30)

        src = blocks.vector_source_b(stream)
        test_blk = reveng.packet_deframer('boop', sync, False, 0, 0, 2, 2, True)
        sink = blocks.message_debug()

        self.tb.connect(src, test_blk)
        self.tb.msg_connect(test_blk, 'out', sink, 'store')
        self.tb.run()

        for idx in xrange(2):
            rec_msg = pmt.to_python(sink.get_message(idx))

            self.assertTrue(isinstance(rec_msg, tuple))
            self.assertTrue(len(rec_msg) == 2)

            (meta, bytez) = rec_msg
            self.assertTrue(isinstance(meta, dict))
            self.assertTrue(isinstance(bytez, numpy.ndarray))
            self.assertTrue(list(bytez) == [0x00, 0x01, 0x04, 0xde, 0xad, 0xbe, 0xef, 0xa5, 0x5a])
Beispiel #49
0
    def handle_msg(self, msg):
	# save the feedback from-decoder 
	self.feedback.extend(pmt.to_python(msg))
	# encrypted data
	ciphertext = []
        # consumed feedback
        feedback = []
        # consumed plain text
        plaintext = []
        # consume feedback from encoder
	while (min(len(self.feedback),len(self.plain_text)) > 0):
		# consume a feedback item
		f = self.feedback.pop(0)
                feedback.append(f)
		# consume a key bit
		k = self.key_bit.pop(0)
		if f: # positive feedback?
			# get a data bit
			d = self.plain_text.pop(0)
			plaintext.append(d)
			# post encrypted data bit
			ciphertext.append(int(k^d))
	if self.debug: 
           sys.stderr.write("encoder.handle_msg():feedback: " + \
                str(feedback) + "\n")
	if self.debug: 
           sys.stderr.write("encoder.handle_msg():plain text: " + \
                str(plaintext) + \
		" cipher text: " + str(ciphertext) + "\n")
        # post encrypted data
        self.message_port_pub(pmt.intern('ciphertext'),
           pmt.to_pmt(ciphertext))
    def test_002_t (self):
        '''
        Test variable length packet. Length byte straight after sync, no
        additional bytes.
        '''
        # set up fg
        sync = map(int, bin(0xd391)[2:].zfill(16))
        plen = map(int, bin(4)[2:].zfill(8))
        data = map(int, bin(0xdeadbeef)[2:].zfill(32))

        pkt = plen + data
        stream = ([0] * 30) + sync + pkt + ([0] * 30)

        src = blocks.vector_source_b(stream)
        test_blk = reveng.packet_deframer('boop', sync, False, 0, 0, 0, 0, False)
        sink = blocks.message_debug()

        self.tb.connect(src, test_blk)
        self.tb.msg_connect(test_blk, 'out', sink, 'store')
        self.tb.run()

        # check data
        rec_msg = pmt.to_python(sink.get_message(0))

        self.assertTrue(isinstance(rec_msg, tuple))
        self.assertTrue(len(rec_msg) == 2)

        (meta, bits) = rec_msg
        self.assertTrue(isinstance(meta, dict))
        self.assertTrue(meta.get('name') == "boop")

        self.assertTrue(isinstance(bits, numpy.ndarray))
        self.assertTrue(list(bits) == pkt)
Beispiel #51
0
 def handler(self, pdu):
     meta = pmt.car(pdu)
     vec = pmt.to_python(pmt.cdr(pdu))
     idx = numpy.argmax(numpy.abs(vec) > self.max_item)
     if(not idx == 0):
         vec = vec[0:idx]
     self.message_port_pub(pmt.intern("pdus"), pmt.cons( meta, pmt.to_pmt(vec) ) );
Beispiel #52
0
    def test_003_es_sink (self):
        print "test_003_es_sink"
        iv = [0,1,2,3,4,5,6,7,8,9];
        src = blocks.vector_source_f(iv, repeat=True);
        hd = blocks.head(gr.sizeof_float, 10000);
        snk = es.sink([gr.sizeof_float], 8);
        t = es.trigger_sample_timer(gr.sizeof_float, 10, 5, 10, 10);
        tb = gr.top_block();
        pduh = es.es_make_handler_pdu(es.es_handler_print.TYPE_F32);
        msgdb = blocks.message_debug()
        tb.connect(src, hd, t, snk);   
        tb.msg_connect( t, "which_stream", snk, "schedule_event" )
        tb.msg_connect( t, "sample_timer_event", pduh, "handle_event" )
        tb.msg_connect( pduh, "pdus_out", msgdb, "store" )
        tb.run();
 
        # expected output of each event in the periodic sequence   
        sv = numpy.array( iv[5:] + iv[:5], dtype=numpy.float32 );

        # verify each received message
        nm = msgdb.num_messages();
        print "nm = %d"%(nm);
        for i in range(0, nm):
            m = msgdb.get_message(i);
            mp = pmt.to_python(pmt.cdr(m));
            print mp;
            self.assertEqual( sv.all(), mp.all() );
Beispiel #53
0
    def handler(self, msg):
        if(self.idx > self.maxidx):
            return;

        ba = bitarray.bitarray();
        meta = pmt.car(msg);
        cdata = pmt.cdr(msg);
 
        pydict = None;
        try:   
            pydict = pmt.to_python(meta);       
        except:
            pass;

        x = pmt.c32vector_elements(cdata)

 
        #fn = "/tmp/cpdu_burst_%f.txt"%(time.time());       
        fn = "/tmp/cpdu_burst_%f.txt"%(self.idx);       
        print "writing %s"%(fn);
        f = open(fn,"w");
        x = ", ".join( map( lambda x: "%f+%fj"%(x.real, x.imag), x) );
        f.write("x = [%s]\n"%(str(x))); 
#        f.write("meta = %s"%(str(pydict)));
        f.close();
        f = None;

        self.idx = self.idx + 1;
    def test_001_t (self):
        # set up fg
        data_in = (0,1,2,3,0,0,4,5,6,7,0,0,8,9,10,11,0,0)
        self.src = blocks.vector_source_b(data_in)
        self.zeropadding_removal = ieee802_15_4.zeropadding_removal_b(phr_payload_len=4, nzeros=2)
        self.msgsink = blocks.message_debug()

        self.tb.connect(self.src, self.zeropadding_removal)
        self.tb.msg_connect(self.zeropadding_removal, "out", self.msgsink, "store")
        self.tb.start()
        time.sleep(2)
        self.tb.stop()
        # check data
        num_messages = self.msgsink.num_messages()
        self.assertTrue(num_messages == 3)
        data_out = []
        for i in range(num_messages):
            tmp = pmt.to_python(self.msgsink.get_message(i))
            data_out = np.concatenate((data_out,tmp[1]))

        ref = range(12)
        print "num messages:", self.msgsink.num_messages()
        print "ref:", ref
        print "data_out:", data_out
        self.assertFloatTuplesAlmostEqual(data_out, ref)
Beispiel #55
0
 def radio_rx(self, msg):
     # message structure is a meta data-data?
     try:
         meta = pmt.car(msg)
         data = pmt.cdr(msg)
     except:
         if self.debug_stderr:
             # log the error
             sys.stderr.write("in radio_rx(): message is not a PDU\n")
         return
     # data is a vector of unsigned chars?
     if pmt.is_u8vector(data):
         data = pmt.u8vector_elements(data)
     else:
         if self.debug_stderr:
             # log the error
             sys.stderr.write("in radio_rx(): data is not a u8vector\n")
         return
     # convert meta data dictionary from PMT to Python type
     meta_dict = pmt.to_python(meta)
     if not (type(meta_dict) is dict):
         meta_dict = {}
     # Get exclusive access
     with self.lock:
         self._radio_rx(data, meta_dict)
Beispiel #56
0
    def handle_payload_message(self, msg_pmt):
        #if not self.log:
        #    return

        meta = pmt.to_python(pmt.car(msg_pmt))
        packet_num = meta["packet_num"]
        #packet_num = pmt.to_double(pmt.dict_values(meta)[0])
        #print 'num = '+str(packet_num)
        msg = pmt.cdr(msg_pmt)
        msg_data = pmt.u8vector_elements(msg)

        self.num_rec_packets += 1
        self.sum_snr += self.curr_snr
        ok = True
        
        print '[per_logger] got message. Total = ' + str(self.num_rec_packets)
        #print list(msg_data)
        
        byte_errors, bit_errors = self.compare_lists(list(msg_data), self.payload)

        if bit_errors > 0:
            self.num_packet_errors += 1
            print '[per_logger] Packet error. Byte errors = ' + str(bit_errors) + " Bit errors = " + str(bit_errors) + " Total = " + str(self.num_packet_errors)
            ok = False

        self.log_packet(ok, self.curr_snr, byte_errors, bit_errors, packet_num)
Beispiel #57
0
 def _app_rx(self, msg, arq):
     try:
         meta = pmt.car(msg)
         data =  pmt.cdr(msg)
     except:
         #raise NameError("mac - input not a PDU")
         print "Message is not a PDU"
         return
     
     if pmt.is_u8vector(data):
         data = pmt.u8vector_elements(data)
     else:
         #raise NameError("Data is not u8 vector")
         print "Data is not a u8vector"
         return
     
     meta_dict = pmt.to_python(meta)
     if not (type(meta_dict) is dict):
         meta_dict = {}
     
     if arq:
         meta_dict['EM_USE_ARQ'] = True
     
     if (not 'EM_DEST_ADDR' in meta_dict.keys()) or (meta_dict['EM_DEST_ADDR'] == -1):
         meta_dict['EM_DEST_ADDR'] = BROADCAST_ADDR
     
     self.dispatch_app_rx(data, meta_dict)