def test_004_es_source_pdus(self): print "test_004_es_source_pdus" msg = pmt.cons( pmt.to_pmt( {"somekey":"val2", "somekey2":"someval2" } ), pmt.to_pmt( numpy.array( [0,1,2,3,4,5,6,7,8,9] , dtype=numpy.float32) ) ); src = es.source([gr.sizeof_float], 8, 2); stb = blocks.message_strobe( msg, 100.0 ); tb = gr.top_block(); tb.msg_connect(stb, "strobe", src, "schedule_event"); th = blocks.throttle(gr.sizeof_float, 1000*100); hd = blocks.head(gr.sizeof_float, 1000*100); snk = blocks.vector_sink_f(); tb.connect(src,th,hd,snk); # TODO: this can not use run because it is # subject to GNU Radio's shutdown msg block bug # for remaining upstream msg blocks ... #tb.run(); # workaround tb.start(); time.sleep(1); tb.stop(); tb.wait(); self.assertEqual( sum(snk.data())>0, True );
def parser_output(self, mat_frame, parity_ok=True, crc_ok=True): # Reshaping the mat_frame into a simple row vector and convert the vector to a string size_mat_frame = mat_frame.shape mat_vect = numpy.reshape(mat_frame, (size_mat_frame[0] * size_mat_frame[1], 1)) mat_vect = numpy.array(mat_vect) mat_vect_str = mat_vect.tostring() # Creation of dictionnary with the matrix and the crc_ok & parity_ok boolean key_crc = pmt.intern("crc_ok") val_crc = pmt.to_pmt(crc_ok) key_parity = pmt.intern("parity_ok") val_parity = pmt.to_pmt(parity_ok) key_mat = pmt.intern("mat_vect_str") val_mat = pmt.to_pmt(mat_vect_str) dic = pmt.make_dict() dic = pmt.dict_add(dic, key_crc, val_crc) dic = pmt.dict_add(dic, key_parity, val_parity) dic = pmt.dict_add(dic, key_mat, val_mat) # Sending the dictionnary to the acarsparser block self.message_port_pub(pmt.intern("parser_output"), pmt.cons(pmt.PMT_NIL, dic))
def timer_tick(self): if (self.has_gps_sensor): gps_gpgga = self.uhd_dev.get_mboard_sensor('gps_gpgga').value gps_gprmc = self.uhd_dev.get_mboard_sensor('gps_gprmc').value gps_time = self.uhd_dev.get_mboard_sensor('gps_time').to_int() gps_locked = self.uhd_dev.get_mboard_sensor('gps_locked').to_bool() pps_seconds = self.uhd_dev.get_time_last_pps().to_ticks(1.0) uhd_time_set = (pps_seconds == gps_time) gps_data = pmt.make_dict() gps_data = pmt.dict_add(gps_data, pmt.intern('gps_time'), pmt.to_pmt(gps_time)) gps_data = pmt.dict_add(gps_data, pmt.intern('gps_locked'), pmt.to_pmt(gps_locked)) gps_data = pmt.dict_add(gps_data, pmt.intern('usrp_time_is_absolute'), pmt.to_pmt(uhd_time_set)) gps_data = pmt.dict_add(gps_data, pmt.intern('usrp_time'), pmt.to_pmt(pps_seconds)) self.message_port_pub(pmt.intern('gps_data'), gps_data) if self.udp_socket: # send UDP self.udp_socket.sendto("\r\n" + gps_gprmc + "\r\n" + gps_gpgga, ("127.0.0.1", self.udp_port)) self.timer = Timer(self.update_rate, self.timer_tick) self.timer.start()
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 send_response(self, response): response_msg = response.strip() response = numpy.fromstring(response, dtype=numpy.uint8) response = pmt.to_pmt(response) response = pmt.cons(pmt.to_pmt(None), response) # self.debug_msg('Responding with {}'.format(response_msg)) self.message_port_pub(pmt.intern('out'), response)
def test_001_t(self): # set up fg msg_meta = pmt.make_dict() msg_meta = pmt.dict_add(msg_meta, pmt.to_pmt("freq"), pmt.to_pmt("val")) vec1 = [ 0x01, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00 ] msg_vector = pmt.init_u8vector(len(vec1), vec1) msg = pmt.cons(msg_meta, msg_vector) src = blocks.message_strobe(msg, 10) dut = capture_tools.bit_sniffer(fade_out=500, hexadecimal=True) self.tb.msg_connect((src, "strobe"), (dut, "packets")) self.tb.start() time.sleep(5) vec1 = [0x01, 0x00, 0x01, 0x00, 0x01, 0x00] msg_vector = pmt.init_u8vector(len(vec1), vec1) msg = pmt.cons(msg_meta, msg_vector) src.set_msg(msg) time.sleep(5) vec1 = [0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x00, 0x01, 0x01] msg_vector = pmt.init_u8vector(len(vec1), vec1) msg = pmt.cons(msg_meta, msg_vector) src.set_msg(msg) time.sleep(5) self.tb.stop()
def to_spec_sense(self, meta, data): meta = pmt.to_pmt(meta) data = pmt.to_pmt(data) pdu = pmt.cons(meta, data) #make the PDU #publish PDU to msg port self.message_port_pub(pmt.intern('to_spect_sens'),pdu) return None
def handle_demod_classic(self, pdu): t0 = time.time() self.demod_packet_cnt += 1 tag_dict = pmt.car(pdu) vec = pmt.to_python(pmt.cdr(pdu)) _, _, new_echo_s, my_echo_s = self.split_packet_iq(vec) bits = util_data.integers_to_bits(self.demod.demodulate(vec), self.bits_per_symbol) spy, hdr, new_echo, _ = self.split_packet_bits(bits) # Check spy header to see if packet is corrupt if self.spy_length > 0: spy_ber = sum(spy != self.spy_master) * 1.0 / self.spy_length else: spy_ber = 0 # Interpret header if hdr is not None: idxpre = hdr[0] idxecho = hdr[1] valid = hdr[2] else: valid = False idxpre = (1 << 16) - 1 idxecho = (1 << 16) - 1 if spy_ber < self.spy_threshold: self.logger.debug( "classic demod {} spy passed ({}) but header failed to decode" .format(self.uuid_str, spy_ber)) if spy_ber > self.spy_threshold: # BAD PACKET! self.logger.debug( "classic demod {} spy ber {} above threshold {}".format( self.uuid_str, spy_ber, self.spy_threshold)) # Publish to both ports so mod can decide what to do with the bad packet #self.message_port_pub(self.port_id_corrupt, # pmt.cons(pmt.PMT_NIL, pmt.to_pmt(bits.astype(np.int8)))) self.message_port_pub( self.port_id_demod_out, pmt.cons(pmt.PMT_NIL, pmt.to_pmt(bits.astype(np.int8)))) else: # Publish good packet self.demod_update_cnt += 1 self.message_port_pub( self.port_id_demod_out, pmt.cons(pmt.PMT_NIL, pmt.to_pmt(bits.astype(np.int8)))) try: preamble = self.get_preamble_hist(idxecho)[:self.preamble.size] ber = sum(preamble != new_echo) * 1.0 / self.preamble.size if self.demod_update_cnt % self.log_interval == 0 or self.run_mode == 'freeze': with open("ber_{}.csv".format(self.uuid_str), "a") as f: f.write("{},{}\n".format(self.demod_update_cnt, ber)) except KeyError as e: self.logger.info( "DEBUG::Unable to calculate BER with stored index {}". format(idxecho)) t1 = time.time() self.logger.debug( "classic demod {} handled {} bits in {} seconds".format( self.uuid_str, bits.size, t1 - t0)) return bits
def publish_to_ports(self, range_rate): shifted_downlink = self.downlink_frequency * (1.0 - range_rate / SPEED_OF_LIGHT) shifted_uplink = self.uplink_frequency * (1.0 + range_rate / SPEED_OF_LIGHT) self.message_port_pub( pmt.intern("downlink_shift"), pmt.to_pmt(self.downlink_frequency - shifted_downlink)) self.message_port_pub( pmt.intern("uplink_shift"), pmt.to_pmt(self.uplink_frequency - shifted_uplink))
def _parse_payload(self): if self.uf_str == 'UF0': self.rl = self.payload[8] self.aq = self.payload[13] self.ds = self.payload[14:22] self.ap = self.payload[32:32 + 24] if self.verbose: #print '\n' print '----------------------------------------------------------------------' print self.meta print len(self.payload), self.payload print 'datetime: {:s}'.format(self.meta['datetime']) print ' SNR: {:2.2f} dB'.format(self.meta['snr']) print ' SYNC: {:d}'.format(self.meta['sync']) print ' UF: {:d} {:s}'.format(self.uf, UF_STR_LUT[self.uf]) print ' RL: {:d}'.format(self.rl) print ' AQ: {:d}'.format(self.aq) print ' DS: 0x{:04x}'.format(self.bin2dec(self.ds)) print ' bits AP:', self.ap print ' hex AP: 0x{:06x}'.format(self.bin2dec(self.ap)) #Create output pdu and emit meta = pmt.to_pmt(self.meta) vector = pmt.to_pmt(self.payload) pdu = pmt.cons(meta, vector) self.message_port_pub(pmt.intern('out'), pdu)
def tag_end_preamble(self, freq_shift, fine_freq_shift, time_shift, fine_delay, sync_value, sof_idx): #Prepare tag #This delay estimator has an uncertainty of +/-M (by steps of M/2). #So we put the tag M items before the estimated SOF item, to allow #A successive block to remove this uncertainty. tag_offset = self.nitems_written(0) + time_shift + sof_idx*self.M \ + self.M//4 tag1_key = pmt.intern('fine_freq_offset') tag1_value = pmt.to_pmt(fine_freq_shift) tag2_key = pmt.intern('coarse_freq_offset') tag2_value = pmt.to_pmt(freq_shift/self.M) tag3_key = pmt.intern('sync_word') tag3_value = pmt.to_pmt(sync_value) tag4_key = pmt.intern('time_offset') tag4_value = pmt.to_pmt(int(time_shift)) tag5_key = pmt.intern('fine_time_offset') tag5_value = pmt.to_pmt(float(fine_delay)) #Append tags self.add_item_tag(0, tag_offset, tag1_key, tag1_value) self.add_item_tag(0, tag_offset, tag2_key, tag2_value) self.add_item_tag(0, tag_offset, tag3_key, tag3_value) self.add_item_tag(0, tag_offset, tag4_key, tag4_value) self.add_item_tag(0, tag_offset, tag5_key, tag5_value)
def update_file_range(self): try: (s, l) = self.f_range meta = { "start": s, "len": l, "end": s + l, "filename": self.filename } self.F.seek(s * self.itemsize) if self.force_complex: vec = numpy.fromfile(self.F, dtype=self.filetype, count=2 * l, sep='') vec = vec[0::2] + 1j * vec[1::2] else: vec = numpy.fromfile(self.F, dtype=self.filetype, count=l, sep='') vec = numpy.array(vec, dtype="complex64") self.message_port_pub(pmt.intern("pdus"), pmt.cons(pmt.to_pmt(meta), pmt.to_pmt(vec))) except: pass
def test_011_tag1 (self): # set up fg tags = [] tags.append(gr.tag_utils.python_to_tag((2, pmt.to_pmt("the_key"), pmt.to_pmt("the_value"), pmt.PMT_NIL))) tags.append(gr.tag_utils.python_to_tag((3, pmt.to_pmt("hehe"), pmt.to_pmt("the_value"), pmt.PMT_NIL))) #tags.append(gr.tag_utils.python_to_tag((4, pmt.to_pmt("end"), pmt.to_pmt("vector_source_c"), pmt.PMT_NIL))) self.src = blocks.vector_source_c([1,2,3,4,5], tags=tags) self.dst = blocks.vector_sink_c() self.repeating = capture_tools.repeat_input_n_times_cc(3, 1000) self.repeating.set_tag_propagate_end(False) self.repeating.set_tag_add_repeat(False) self.tb.connect(self.src, self.repeating, self.dst) self.tb.run () tags = self.dst.tags() #for t in tags: # print("HER: "+str(t.offset)) self.assertEqual(self.dst.data() , ((1+0j), (2+0j), (3+0j), (4+0j), (5+0j), (1+0j), (2+0j), (3+0j), (4+0j), (5+0j), (1+0j), (2+0j), (3+0j), (4+0j), (5+0j))) self.assertEqual(len(tags), 7) self.assertEqual(str(tags[0].key), "the_key") self.assertEqual(str(tags[0].value), "the_value") self.assertEqual(int(tags[0].offset), 2) self.assertEqual(str(tags[2].key), "the_key") self.assertEqual(str(tags[2].value), "the_value") self.assertEqual(int(tags[2].offset), 7) self.assertEqual(str(tags[4].key), "the_key") self.assertEqual(str(tags[4].value), "the_value") self.assertEqual(int(tags[4].offset), 12) self.assertEqual(str(tags[3].key), "hehe") self.assertEqual(str(tags[3].value), "the_value") self.assertEqual(int(tags[3].offset), 8)
def work(self, input_items, output_items): """ Send out packets to be encoded and sent to the transmitter :param input_items: :param output_items: :return: """ out = output_items[0] if not self.out_packet: return 0 else: packet_len = self.out_packet.size out[:packet_len] = self.out_packet out[packet_len + 1] = 0 self.add_item_tag( 0, # Port number self.nitems_written(0), # Offset pmt.intern(f'Packet start'), pmt.to_pmt(self.received_packets)) self.add_item_tag( 0, # Port number self.nitems_written(0) + packet_len, # Offset pmt.intern(f'Packet end'), pmt.to_pmt(self.received_packets)) self.received_packets += 1 self.out_packet = None self.status = self.Status.WAITING print(f'Pkt source: output of {packet_len} items') return packet_len + 1
async def process_cmd(self, msg): print(f'Received cmd: {msg}') cmd = msg[0] # Data packet if cmd == 0: print(f'Sending packet to modulator') # TODO: eeeeh not really data = self.preamble + msg[1:] # print(f"Received {data.hex()}") data = numpy.frombuffer(data, dtype=numpy.uint8) self.out_packet = data self.status = self.Status.SENDING # Pass to board interface elif cmd == 1: print(f'Passing message to board interface') message = pmt.cons(pmt.intern('cmd'), pmt.to_pmt(msg[1:].hex())) self.message_port_pub(pmt.intern(self.port_out_name), message) # Pass rf pkt to board interface elif cmd == 2: print(f'Passing rf pkt to board interface') message = pmt.cons(pmt.intern('rf'), pmt.to_pmt(msg[1:].hex())) self.message_port_pub(pmt.intern(self.port_out_name), message)
def test_003_trim_from_end(self): orig_array = np.array([1.1, 2.2, 3.3, 4.4, 5.5]) expected_out_array = np.array([1.1, 2.2, 3.3]) metadata = {'a': 1, 'b': 2} in_pmt = pmt.cons(pmt.to_pmt(metadata), pmt.to_pmt(orig_array)) expected_pmt = pmt.cons(pmt.to_pmt(metadata), pmt.to_pmt(expected_out_array)) # We just need something connected to the trimmer block for # the flowgraph to compile, but we'll post messages to it directly src = blocks.message_strobe(pmt.PMT_NIL, 9999999) trimmer = pdu_trim_uvector(0, 2) snk = blocks.message_debug() self.tb.msg_connect((src, 'strobe'), (trimmer, 'in')) self.tb.msg_connect((trimmer, 'out'), (snk, 'store')) self.tb.start() trimmer.to_basic_block()._post(pmt.intern('in'), in_pmt) time.sleep(0.1) self.tb.stop() self.tb.wait() # check data self.assertEqual(snk.num_messages(), 1) self.assertTrue(pmt.equal(snk.get_message(0), expected_pmt))
def test_generic_output(self): messages = [ pmt.to_pmt('foo'), pmt.to_pmt('bar'), pmt.to_pmt({'foo': [1, 2]}) ] for parameters, expected_output in [ (dict(output=OutputType.RAW), 'foo\nbar\n((foo . #(1 2)))\n'), (dict(output=OutputType.PYTHON), "foo\nbar\n{'foo': [1, 2]}\n"), ]: with self.subTest(parameters=parameters, expected_output=expected_output): # sub-tests don't call tearDown / setUp self.tearDown() self.setUp() # given self._setup_graph(messages, **parameters) # when out = io.StringIO() with contextlib.redirect_stdout(out): self._run() # then self.assertEqual(out.getvalue(), expected_output)
def work(self, input_items, output_items): in0 = input_items[0] in1 = input_items[1] #if we have data to classify: if len(in0) >= 1 and len(self.bw_list) > self.sig_no: #create the feature vector x = [self.bw_list[self.sig_no]] x.extend(in0[0]) x.extend(in1[0]) x_tmp = [] x_tmp.append(x) #predict! a = self.knn.predict(x_tmp) #print "Signal #"+ str(self.sig_no)+" :" +a[0] #write to the output message port. pmt_signal = pmt.to_pmt(("signal", self.sig_no)) pmt_class = pmt.to_pmt((a[0], 0)) pmt_tuple = pmt.make_tuple(pmt_signal, pmt_class) self.message_port_pub(pmt.intern("classification"), pmt_tuple) #consume, finish self.consume(0, len(in0)) self.consume(1, len(in1)) return len(input_items[0])
def tx_work(self, x): pygame.init() screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption('Pygame Caption') pygame.mouse.set_visible(0) done = False while not done: time.sleep(0.1) for event in pygame.event.get(): if (event.type == KEYUP) or (event.type == KEYDOWN): print event if (event.key == K_ESCAPE and event.type == KEYDOWN): dict2 = {"id": "joystick", "buttons": [1, 0, 0]} #pmt_dict = pmt.to_pmt(dict2) self.message_port_pub(pmt.intern('out'), pmt.to_pmt(dict2)) if (event.key == K_ESCAPE and event.type == KEYUP): dict2 = {"id": "joystick", "buttons": [0, 0, 0]} #pmt_dict = pmt.to_pmt(dict2) self.message_port_pub(pmt.intern('out'), pmt.to_pmt(dict2)) print 'here' '''
def set_takeoff(self, takeoff): if (takeoff == 1): meta = pmt.to_pmt('takeoff') data = pmt.to_pmt(self.altitude) msg = pmt.cons(meta, data) print('send_zmq') self.zmqc.send(pmt.serialize_str(msg))
def set_land(self, land): self.land = land meta = pmt.to_pmt('land') data = pmt.to_pmt(1) msg = pmt.cons(meta, data) print('send_zmq') self.zmqc.send(pmt.serialize_str(msg))
def test_003_2_byte_sync(self): orig_array = np.array([1, 0, 1, 0, 1, 0, 1], dtype=np.uint8) metadata = {'a': 1, 'b': 2} expected_array = np.array([ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1 ], dtype=np.uint8) in_pmt = pmt.cons(pmt.to_pmt(metadata), pmt.to_pmt(orig_array)) expected_pmt = pmt.cons(pmt.to_pmt(metadata), pmt.to_pmt(expected_array)) appender = add_sync_pdu(0xf023, 2) snk = blocks.message_debug() self.tb.msg_connect((appender, 'out'), (snk, 'store')) self.tb.start() appender.to_basic_block()._post(pmt.intern('in'), in_pmt) time.sleep(0.1) self.tb.stop() self.tb.wait() # check data self.assertEqual(snk.num_messages(), 1) self.assertTrue(pmt.equal(snk.get_message(0), expected_pmt))
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 tx_work(self,x): pygame.init() screen = pygame.display.set_mode((640, 480)) pygame.display.set_caption('Pygame Caption') pygame.mouse.set_visible(0) done = False while not done: time.sleep(0.1) for event in pygame.event.get(): if (event.type == KEYUP) or (event.type == KEYDOWN): print event if (event.key == K_ESCAPE and event.type == KEYDOWN): dict2 = { "id" : "joystick", "buttons" : [1,0,0]} #pmt_dict = pmt.to_pmt(dict2) self.message_port_pub(pmt.intern('out'),pmt.to_pmt(dict2)) if (event.key == K_ESCAPE and event.type == KEYUP): dict2 = { "id" : "joystick", "buttons" : [0,0,0]} #pmt_dict = pmt.to_pmt(dict2) self.message_port_pub(pmt.intern('out'),pmt.to_pmt(dict2)) print 'here' '''
def general_work(self, input_items, output_items): # this block only works with single input port, so make a convenience var for ch0 inp = input_items[0] # check if we need to look for a header if self.nitems_remaining <= 0: # make sure there's a whole header plus first payload byte available if len(inp) >= self.hdr_len + 1: pad_len, frame_len = struct.unpack(self.hdr_fmt, inp[:self.hdr_len]) packet_len = frame_len - self.hdr_len self.nitems_remaining = packet_len - 1 # add stream tags for payload len and zero pad len offset = self.nitems_written(0) self.add_item_tag(0, offset, self.zero_pad_tag_name, pmt.to_pmt(pad_len)) self.add_item_tag(0, offset, self.len_tag_name, pmt.to_pmt(packet_len)) # keep track of where we are in the input chain self.consume_each(self.hdr_len + 1) output_items[0][0] = inp[self.hdr_len] return 1 # if a full header isn't available in inp, return and hope for better # luck next iteration else: return 0 # this should always be true at this point if self.nitems_remaining > 0: # figure out how many items we can output noutput_items = min(len(inp), len(output_items[0]), self.nitems_remaining) output_items[0][:noutput_items] = inp[:noutput_items] # consume header and all items we just passed to output and return self.consume_each(noutput_items) self.nitems_remaining -= noutput_items return noutput_items else: # we should not be able to get here... print("Warning, traffic parser is hitting an unexpected state") return 0 # we shouldn't be able to get here either print("Warning, traffic parser is hitting another unexpected state") return 0
def send_msg(self, meta, data): # construct pdu and publish to radio port # data = pmt.intern(str(data)) #convert from string meta = pmt.to_pmt(meta) data = pmt.to_pmt(data) pdu = pmt.cons(meta, data) # make the PDU # publish PDU to msg port self.message_port_pub(pmt.intern("PDU spect_msg"), pdu)
def set_disarm(self, disarm): self.disarm = disarm if self.disarm == 1: meta = pmt.to_pmt('disarm') pmtdata = pmt.to_pmt(self.data) msg = pmt.cons(meta, pmtdata) print('send_zmq disarm') self.zmqc.send(pmt.serialize_str(msg))
def update_file_range(self): (s, l) = self.f_range meta = {"start": s, "len": l, "end": s + l, "filename": self.filename} self.F.seek(s * self.itemsize) vec = numpy.fromfile(self.F, dtype=self.filetype, count=l, sep='') vec = numpy.array(vec, dtype="complex64") self.message_port_pub(pmt.intern("pdus"), pmt.cons(pmt.to_pmt(meta), pmt.to_pmt(vec)))
def make_tag(key, value, offset, srcid=None): tag = gr.tag_t() tag.key = pmt.string_to_symbol(key) tag.value = pmt.to_pmt(value) tag.offset = offset if srcid is not None: tag.srcid = pmt.to_pmt(srcid) return tag
def send_msg(self, meta, data): #construct pdu and publish to radio port #data = pmt.intern(str(data)) #convert from string meta = pmt.to_pmt(meta) data = pmt.to_pmt(data) pdu = pmt.cons(meta, data) #make the PDU #publish PDU to msg port self.message_port_pub(pmt.intern('PDU spect_msg'), pdu)
def sync_fsm(self): if self.sync_state == 'INIT': #select a sub-channel at random from the hop_sequence!! #rnd_sync_listen_channel = random.randint(0, sequence_length) #how? doesn't have access to xorshift/hop_sequence, which is internal to the FH message strobe block? #implement later, currently set to center_freq if self.hopset_loaded == 'FALSE': try: self.d_py_hop_seq = self.hopset_import(self.d_py_hop_seq) self.hopset_loaded = 'TRUE' print "\n Hopset Loaded \n" except: print "ERROR: Failed to load hopset" if self.init_tune == 'FALSE': init_freq_pmt = pmt.to_pmt(self.d_center_freq) self.message_port_pub(pmt.intern('rx_freq_out'), init_freq_pmt) self.init_tune = 'TRUE' print "Radio Tuned for INIT" #publish this pmt to the freq_out port #INIT SYNC times out if (time.time() - self.last_sync_time) >= self.sync_rx_timeout: print "Time elapsed is: ", (time.time() - self.last_sync_time) print "Failed to acquire Sync after: %03d. Defaulting to internal time." % ( self.sync_rx_timeout) #self.send_sync_pkt() needs to broadcast sync on all channels #broadcast sync packets to every channel #work through the hop_sequence from 0-sequence_length? self.sync_state = 'SYNCED' self.last_sync_time = time.time() print "New Sync Time is: ", self.last_sync_time #if sync_state == SYNCED if self.sync_state == 'SYNCED' and ( (time.time() - self.last_sync_time) >= self.sync_tx_interval): self.send_sync_pkt() self.last_sync_time = time.time() if self.sync_state == 'SYNCED' and ( (time.time() - self.last_sync_time) >= self.sync_rx_timeout): print "Changing state to INIT after: ", self.sync_rx_timeout self.sync_state = 'INIT' self.init_tune = 'FALSE' self.last_sync_time = time.time() if self.sync_state == 'SYNCED': d_time_ms = (datetime.now().minute * 60000) + (datetime.now().second * 1000) + (datetime.now().microsecond / 1000) d_current_hop = (d_time_ms / self.d_period_ms) % self.d_sequence_length #print "Length of Sequence is: ", len(self.d_py_hop_seq) #print "Current Hop Index is: ", d_current_hop d_current_freq = self.d_py_hop_seq[d_current_hop] fh_rx_freq_pmt = pmt.to_pmt(d_current_freq + self.d_center_freq) fh_tx_freq_pmt = pmt.to_pmt(d_current_freq) self.message_port_pub(pmt.intern('rx_freq_out'), fh_rx_freq_pmt) self.message_port_pub(pmt.intern('tx_freq_out'), fh_tx_freq_pmt)
def work(self, input_items, output_items): output_items[0][:] = input_items[0] if self.inject_tag: offset = self.nitems_read(0) for key, val in self.inject_tag.items(): self.add_item_tag(0, offset, pmt.to_pmt(key), pmt.to_pmt(val)) self.injected_offset = offset self.inject_tag = None return len(output_items[0])
def range_received(self, msg): (s,l) = pmt.to_python(msg) meta = {"start":s, "len":l, "end":s+l, "filename":self.filename} self.F.seek(s*self.itemsize) vec = numpy.fromfile(self.F, dtype=numpy.complex64, count=l, sep='') self.message_port_pub(pmt.intern("pdus"), pmt.cons( pmt.to_pmt(meta), pmt.to_pmt(vec) ))
def update_file_range(self): (s,l) = self.f_range meta = {"start":s, "len":l, "end":s+l, "filename":self.filename} self.F.seek(s*self.itemsize) vec = numpy.fromfile(self.F, dtype=self.filetype, count=l, sep='') vec = numpy.array(vec, dtype="complex64") self.message_port_pub(pmt.intern("pdus"), pmt.cons( pmt.to_pmt(meta), pmt.to_pmt(vec) ))
def test_001_t (self): # set up fg tag1 = gr.tag_utils.python_to_tag((0, pmt.to_pmt("ramp_up"), pmt.to_pmt("the_value"), pmt.PMT_NIL)) tag2 = gr.tag_utils.python_to_tag((25, pmt.to_pmt("ramp_down"), pmt.to_pmt("the_value"), pmt.PMT_NIL)) self.src = blocks.vector_source_c([1+2j,1+2j,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1], tags=[tag1, tag2]) self.dut = capture_tools.add_rampup_cc(0.4) self.dst = blocks.vector_sink_c() self.tb.connect(self.src, self.dut, self.dst) self.tb.run () print(self.dst.data())
def test_1(self): datas = ( 0, 1, 2, 5, 6, 10, 14, 15, 16, 3, 4, 7, 8, 9, 11, 12, 13, 17 ) expected = tuple(range(18)) tagname = "packet_length" len_tags_0 = ( make_len_tag(0, tagname, 3), make_len_tag(3, tagname, 2), make_len_tag(5, tagname, 1), make_len_tag(6, tagname, 3) ) len_tags_1 = ( make_len_tag(0, tagname, 2), make_len_tag(2, tagname, 3), make_len_tag(5, tagname, 3), make_len_tag(8, tagname, 1) ) test_tag_0 = gr.tag_t() test_tag_0.key = pmt.string_to_symbol('spam') test_tag_0.offset = 4 # On the second '1' test_tag_0.value = pmt.to_pmt(42) test_tag_1 = gr.tag_t() test_tag_1.key = pmt.string_to_symbol('eggs') test_tag_1.offset = 3 # On the first '3' of the 2nd stream test_tag_1.value = pmt.to_pmt(23) src0 = blocks.vector_source_b(datas[0:9], False, 1, len_tags_0 + (test_tag_0,)) src1 = blocks.vector_source_b(datas[9:], False, 1, len_tags_1 + (test_tag_1,)) tagged_stream_mux = blocks.tagged_stream_mux(gr.sizeof_char, tagname) snk = blocks.vector_sink_b() self.tb.connect(src0, (tagged_stream_mux, 0)) self.tb.connect(src1, (tagged_stream_mux, 1)) self.tb.connect(tagged_stream_mux, snk) self.tb.run() self.assertEqual(expected, snk.data()) tags = [gr.tag_to_python(x) for x in snk.tags()] tags = sorted([(x.offset, x.key, x.value) for x in tags]) tags_expected = [ (0, 'packet_length', 5), (5, 'packet_length', 5), (6, 'spam', 42), (8, 'eggs', 23), (10, 'packet_length', 4), (14, 'packet_length', 4) ] self.assertEqual(tags, tags_expected)
def work(self, input_items, output_items): tensordata = [] input_i = [] shapev = np.array(input_items[0]).shape for item in range(shapev[0]): inp = np.array(input_items[0][item]) if self.dtype == np.complex64: # complex data must be split into real # and imaginary floats for the ANN tensordata.append(np.array([[inp.real,inp.imag]])) elif self.dtype == np.float32: if np.mean(inp) == 0.0: return len(input_items[0]) ## Normalise data inp = (inp - np.mean(inp)) / np.std(inp) ## Reshape data as specified if not self.reshape == (): floats = np.reshape(inp,self.reshape) else: floats = inp tensordata.append(np.array([floats])) ne = [] for v in tensordata: try: #print("In: ",self.inp,"Out : ",self.out) #print("Inp ",v) outp = self.sess.run(self.out, feed_dict={self.inp: [v]})[0] #print("OUTP ",outp) ne.append(outp) except tf.errors.InvalidArgumentError: print("Invalid size of input vector to TensorFlow model") quit() pmtv = pmt.make_dict() for outp in ne: pmtv = pmt.make_tuple(pmt.to_pmt(("signal",self.signum)),pmt.to_pmt((self.classes[np.argmax(outp)],outp[np.argmax(outp)].item()))) self.message_port_pub(pmt.intern("classification"), pmtv) return len(input_items[0])
def test_001_t (self): # set up fg tags= [] tags.append(gr.tag_utils.python_to_tag((2, pmt.to_pmt("add_here"), pmt.to_pmt("the_value"), pmt.PMT_NIL))) tags.append(gr.tag_utils.python_to_tag((5, pmt.to_pmt("add_here"), pmt.to_pmt("the_value"), pmt.PMT_NIL))) src = blocks.vector_source_c([1,2,3,4,5,6,7,8,9], tags=tags) dut = capture_tools.add_at_tag_cc(10,10,0,"add_here") dst = blocks.vector_sink_c() self.tb.connect(src,dut,dst) self.tb.run () print(dst.data()) print("Tags:") for t in dst.tags(): print(str(t.offset)+": "+str(t.key)+"")
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 encode_decode_test(self, payload_str="TEST", whitening=False, encode_crc=False, decode_crc=False): preamble = "01010101" sync1 = 0x2 sync2 = 0x3 sync_length = 2 payload = [ord(c) for c in payload_str] strobe = blocks.message_strobe(pmt.cons(pmt.PMT_NIL, pmt.to_pmt(payload)), 200) encoder = cc11xx_encoder.cc11xx_encoder(preamble=[int(preamble, 2)], syncword=[sync1, sync2], whitening=whitening, crc=encode_crc) pdu_to_stream = blocks.pdu_to_tagged_stream(blocks.byte_t, "packet_len") debug = blocks.message_debug() self.tb.msg_connect(strobe, "strobe", encoder, "in") self.tb.msg_connect(encoder, "out", pdu_to_stream, "pdus") unpack = blocks.packed_to_unpacked_bb(1, 0) acc_code_block = digital.correlate_access_code_tag_bb(preamble, 0, "preamble") deframer = cc11xx.cc11xx_deframer_bb(sync1 ,sync2, whitening, decode_crc, sync_length) self.tb.connect(pdu_to_stream,unpack) self.tb.connect(unpack, acc_code_block) self.tb.connect(acc_code_block, deframer) self.tb.msg_connect((deframer, 'out'), (debug, 'store')) self.tb.start() time.sleep(1) self.tb.stop() #Please get rid of this sleep if you know how! time.sleep(0.1) self.tb.stop() result_data = [i for i in pmt.to_python(pmt.cdr(debug.get_message(0)))] self.assertEqual(payload, result_data)
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) ) );
def work(self, input_items, output_items): in0 = input_items[0] for bit in in0: if self.pattern_check == self.pattern: self.output.append(bit) if len(self.output) == self.output.maxlen: output = list(self.output) outs = ''.join(['1' if ch == 1 else '0' for ch in output]) pmt_out = (None, outs) self.message_port_pub(pmt.intern('out'), pmt.to_pmt(pmt_out)) output = self.format_output(output) if self.stdout: print output if self.fp: try: self.fp.write(output + '\n') self.fp.flush() except IOError as e: print 'Error while writing to file:', print str(e) self.fp.close() self.fp = None self.output.clear() self.pattern_check.clear() else: self.pattern_check.append(bit) return len(input_items[0])
def next_vector(self, seed, samp_rate, noise_amp, modulation, delay, samples_to_receive, freq, rx_id): timing_tag = gr.tag_t() timing_tag.offset = 0 timing_tag.key = pmt.string_to_symbol('rx_time') timing_tag.value = pmt.to_pmt((float(seed), 0.6)) timing_tag.srcid = pmt.string_to_symbol(str('gr uhd usrp source1')) # Rx freq tags: #print "In source emulation (before tag)" #print freq rx_freq_tag = gr.tag_t() rx_freq_tag.offset = 0 rx_freq_tag.key = pmt.string_to_symbol('rx_freq') rx_freq_tag.value = pmt.from_double(freq) rx_freq_tag.srcid = pmt.string_to_symbol(str('gr uhd usrp source1')) # Samp_rate tags: rx_rate_tag = gr.tag_t() rx_rate_tag.offset = 0 rx_rate_tag.key = pmt.string_to_symbol('rx_rate') rx_rate_tag.value = pmt.from_double(samp_rate) rx_rate_tag.srcid = pmt.string_to_symbol(str('gr uhd usrp source1')) pulse_width = 4 np.random.seed(seed=seed) tx_vector = np.reshape(np.matlib.repmat(np.random.randint(0,2,(5*samples_to_receive)/pulse_width)*2-1,pulse_width,1).T,[1,5*samples_to_receive])[0].tolist() # delay signal vector -> insert zeros at beginnig; nothing happens if signal has not reached the receiver: tx_vector_delayed = np.hstack((np.zeros(delay),tx_vector)) #tx_vector_delayed = tx_vector_delayed[:600] print len(tx_vector_delayed) self.vector_source.set_data(tx_vector_delayed,(timing_tag, rx_freq_tag, rx_rate_tag)) self.head.reset() self.vector_source.rewind()
def make_tag(key, value, offset): """Create a gr.tag_t() from key, value, offset.""" tag = gr.tag_t() tag.offset = offset tag.key = pmt.string_to_symbol(key) tag.value = pmt.to_pmt(value) return tag
def test_preserve_tag_head_pos(self): """ Test the 'preserve head position' function. This will add a 'special' tag to item 0 on stream 1. It should be on item 0 of the output stream. """ special_tag = gr.tag_t() special_tag.key = pmt.string_to_symbol('spam') special_tag.offset = 0 special_tag.value = pmt.to_pmt('eggs') len_tag_key = "length" packet_len_1 = 5 packet_len_2 = 3 mux = blocks.tagged_stream_mux(gr.sizeof_float, len_tag_key, 1) sink = blocks.vector_sink_f() self.tb.connect( blocks.vector_source_f(range(packet_len_1)), blocks.stream_to_tagged_stream(gr.sizeof_float, 1, packet_len_1, len_tag_key), (mux, 0) ) self.tb.connect( blocks.vector_source_f(range(packet_len_2), False, 1, (special_tag,)), blocks.stream_to_tagged_stream(gr.sizeof_float, 1, packet_len_2, len_tag_key), (mux, 1) ) self.tb.connect(mux, sink) self.tb.run() self.assertEqual(sink.data(), tuple(range(packet_len_1) + range(packet_len_2))) tags = [gr.tag_to_python(x) for x in sink.tags()] tags = sorted([(x.offset, x.key, x.value) for x in tags]) tags_expected = [ (0, 'length', packet_len_1 + packet_len_2), (0, 'spam', 'eggs'), ] self.assertEqual(tags, tags_expected)
def send_pkt_radio(self, payload, meta_dict, pkt_cnt): # sink in Sink table? if self.SINK_ADDR not in self.sinkTable.keys(): if self.debug_stderr: # yes! log the packet sys.stderr.write( "%d:in send_pkt_radio(): dropping packet\n" % self.addr) # drop the packet return # yes! get the value paired with the sink key aSinkVal = self.sinkTable[self.SINK_ADDR] # yes! data packet header structure data = [self.DATA_PROTO, self.addr, self.addr, pkt_cnt, aSinkVal.min_dx_to_sink, self.SINK_ADDR, aSinkVal.min_dx_to_sink + self.R] # add payload if payload is None: payload = [] elif isinstance(payload, str): payload = map(ord, list(payload)) elif not isinstance(payload, list): payload = list(payload) data += payload # debug mode enabled? if self.debug_stderr: # yes! log the packet sys.stderr.write( "%d:in send_pkt_radio(): sending packet:\n" % self.addr) self.print_pkt(data) # conversion to PMT PDU (meta data, data) pdu = pmt.cons( pmt.to_pmt({}), pmt.init_u8vector(len(data), data)) # push to radio msg port self.message_port_pub(pmt.intern('to_radio'), pdu)
def _to_ofdm_radio(self, pdu_tuple, pkt_cnt, protocol_id, control): meta_data = pdu_tuple[1] payload = pdu_tuple[0] if payload is None: payload = [] elif isinstance(payload, str): payload = map(ord, list(payload)) elif not isinstance(payload, list): payload = list(payload) dest_addr = meta_data['EM_DEST_ADDR'] if dest_addr == -1: dest_addr = BROADCAST_ADDR elif dest_addr < -1 or dest_addr > BROADCAST_ADDR: print "Invalid address:", dest_addr return #create header, merge with payload, convert to pmt for message_pub data = [pkt_cnt, self.address, dest_addr, protocol_id, control] data += payload data = pmt.init_u8vector(len(data), data) meta = pmt.to_pmt({}) #construct pdu and publish to radio port pdu = pmt.cons(meta, data) #publish to msg port self.message_port_pub(pmt.intern('to_ofdm_radio'),pdu)
def work(self, input_items, output_items): # feedback to encoder feedback = [] # read photon angle, previous basis pairs for i in range(len(input_items[0])): # compares encoder and decoder basis used for previous photon if input_items[0][i]==self.sel_basis: # append positive feedback feedback.append(1) # append corresponding biy to key self.key_bit.append(self.dec_bit) else: # append negative feedback feedback.append(0) # randomly select a basis self.sel_basis=random.randint(0, 1) # decode a photon if input_items[1][i]==self.basis[self.sel_basis][0]: # store a zero self.dec_bit = 0 elif input_items[1][i]==self.basis[self.sel_basis][1]: # store a one self.dec_bit = 1 else: # store a random value self.dec_bit = random.randint(0, 1) if self.debug: sys.stderr.write("decoder.work():feedback: " + \ str(feedback) + "\n") # post feedback to encoder self.message_port_pub(pmt.intern('feedback'), pmt.to_pmt(feedback)) return len(input_items[0])
def set_freqs(self, freq0, freq1, freq2, freq3): self.top4[0] = freq0 self.top4[1] = freq1 self.top4[2] = freq2 self.top4[3] = freq3 self.message_out0.set_msg(pmt.cons( pmt.to_pmt("freq"), pmt.to_pmt(freq0-self.tune_freq) )) #send differencial frequency self.message_out1.set_msg(pmt.cons( pmt.to_pmt("freq"), pmt.to_pmt(freq1-self.tune_freq) )) self.message_out2.set_msg(pmt.cons( pmt.to_pmt("freq"), pmt.to_pmt(freq2-self.tune_freq) )) self.message_out3.set_msg(pmt.cons( pmt.to_pmt("freq"), pmt.to_pmt(freq3-self.tune_freq) ))
def work(self, input_items, output_items): """Where the magic happens.""" for _ in range(len(input_items[0]) // self.header_len): msg = self.messages[self.msg_count] or False self.message_port_pub(pmt.intern('header_data'), pmt.to_pmt(msg)) self.msg_count += 1 output_items[0][:] = input_items[0][:] return len(input_items[0])
def work(self, input_items, output_items): for i in range(len(input_items[0]) // self.header_len): msg = self.messages[self.msg_count] or False #print("Sending message: {0}".format(msg)) self.message_port_pub(pmt.intern('header_data'), pmt.to_pmt(msg)) self.msg_count += 1 output_items[0][:] = input_items[0][:] return len(input_items[0])
def work(self, input_items, output_items): tags = self.get_tags_in_window(0, 0, len(input_items[0]), self.tag) tags = sorted(tags, reverse=True) for tag in tags: rel_offset = tag.offset - self.nitems_read(0) if rel_offset + self.burst_length_bits > len(input_items[0]): return rel_offset else: pdu = pmt.cons( pmt.to_pmt({'chan': self.chan_idx}), pmt.to_pmt(input_items[0][rel_offset:rel_offset+self.burst_length_bits]) ) self.message_port_pub( pmt.intern('burst'), pdu ) return len(input_items[0])
def update_file_range(self): try: (s,l) = self.f_range meta = {"start":s, "len":l, "end":s+l, "filename":self.filename} self.F.seek(s*self.itemsize) if self.force_complex: vec = numpy.fromfile(self.F, dtype=self.filetype, count=2*l, sep='') vec = vec[0::2] + 1j*vec[1::2] else: vec = numpy.fromfile(self.F, dtype=self.filetype, count=l, sep='') vec = numpy.array(vec, dtype="complex64") self.message_port_pub(pmt.intern("pdus"), pmt.cons( pmt.to_pmt(meta), pmt.to_pmt(vec) )) except: pass
def request(self, id_str, args=None): socks = dict(self.poller_req_out.poll(10)) if socks.get(self.req_socket) == zmq.POLLOUT: self.req_socket.send(pmt.serialize_str(pmt.to_pmt((id_str,args)))) socks = dict(self.poller_req_in.poll(10)) if socks.get(self.req_socket) == zmq.POLLIN: reply = pmt.to_python(pmt.deserialize_str(self.req_socket.recv())) print("[RPC] reply:", reply) return reply
def handler(self, msg): ba = bitarray.bitarray(); meta = pmt.car(msg); data = pmt.cdr(msg); f_vec = pmt.to_pmt( numpy.array(pmt.to_python(data), dtype="float32") * 2 - 1 ) pdu = pmt.cons(meta, f_vec); # send it on its way self.message_port_pub(pmt.intern("fpdus"), pdu);