def test_001(self): #test complementary operation of framer & deframer #want to frame some random data that has enough consecutive bits to #stuff at least a few bits npkts = 20 src_data = [0xFE, 0xDA, 0xAC, 0x29, 0x7F, 0xA2, 0x90, 0x0F, 0xF8] frame = digital.hdlc_framer_pb("wat") corr = digital.correlate_access_code_tag_bb("01111110", 0, "frame") deframe = digital.hdlc_deframer_bp("frame", 32, 500) debug = blocks.message_debug() self.tb.connect(frame, corr, deframe) self.tb.msg_connect(deframe, "out", debug, "store") self.tb.start() msg = pmt.cons(pmt.PMT_NIL, pmt.init_u8vector(len(src_data),src_data)) for i in xrange(npkts): frame.to_basic_block()._post(pmt.intern("in"), msg) sleep(0.2) self.tb.stop() self.tb.wait() rxmsg = debug.get_message(0) result_len = pmt.blob_length(pmt.cdr(rxmsg)) msg_data = [] for j in xrange(result_len): msg_data.append(pmt.u8vector_ref(pmt.cdr(rxmsg), j)) self.assertEqual(src_data, msg_data)
def test_packet_format_async_counter(self): bps = 2 ac = packet_utils.default_access_code hdr_format = digital.header_format_counter(ac, 0, 2) formatter = digital.protocol_formatter_async(hdr_format) snk_hdr = blocks.message_debug() snk_pld = blocks.message_debug() self.tb.msg_connect(formatter, 'header', snk_hdr, 'store') self.tb.msg_connect(formatter, 'payload', snk_pld, 'store') send_str = "Hello World" + 1000*"xxx" send_pmt = pmt.make_u8vector(len(send_str), ord(' ')) for i in range(len(send_str)): pmt.u8vector_set(send_pmt, i, ord(send_str[i])) msg = pmt.cons(pmt.PMT_NIL, send_pmt) port = pmt.intern("in") formatter.to_basic_block()._post(port, msg) self.tb.start() while (snk_hdr.num_messages() < 1) and (snk_pld.num_messages() < 1): time.sleep(0.1) self.tb.stop() self.tb.wait() result_hdr_pmt = pmt.cdr(snk_hdr.get_message(0)) result_pld_pmt = pmt.cdr(snk_pld.get_message(0)) result_hdr = pmt.u8vector_elements(result_hdr_pmt) result_pld = pmt.u8vector_elements(result_pld_pmt) header = "".join([chr(r) for r in result_hdr]) payload = "".join([chr(r) for r in result_pld]) access_code = packet_utils.conv_1_0_string_to_packed_binary_string(packet_utils.default_access_code)[0] rx_access_code = header[0:len(access_code)] length = len(send_str) rx_length = struct.unpack_from("!H", header, len(access_code))[0] rx_bps = struct.unpack_from("!H", header, len(access_code)+4)[0] rx_counter = struct.unpack_from("!H", header, len(access_code)+6)[0] self.assertEqual(access_code, rx_access_code) self.assertEqual(length, rx_length) self.assertEqual(bps, rx_bps) self.assertEqual(0, rx_counter) self.assertEqual(length, len(payload)) self.assertEqual(send_str, payload[0:length])
def handler(self, msg): self._lock.acquire(); # get input msg meta = pmt.car(msg); samples = pmt.cdr(msg); x = pmt.to_python(pmt.cdr(msg))*1.0 # add to raster self.__data.add_row(x) # update plot self.emit(QtCore.SIGNAL("updatePlot(int)"), 0) self._lock.release();
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 handle_msg(self, msg_pmt): msg = pmt.cdr(msg_pmt) if not pmt.is_u8vector(msg): print "[ERROR] Received invalid message type. Expected u8vector" return data = list(pmt.u8vector_elements(msg)) crc = hdlc.crc_ccitt(data) data.append(crc & 0xff) data.append((crc >> 8) & 0xff) buff = hdlc.flag * self.preamble_bytes ones = 0 # number of consecutive ones for byte in data: for _ in range(8): # transmit byte LSB first x = byte & 1 buff.append(x) if x: ones += 1 else: ones = 0 if ones == 5: # bit-stuff buff.append(0) ones = 0 byte >>= 1 buff.extend(hdlc.flag * self.postamble_bytes) buff = array.array('B', buff) self.message_port_pub(pmt.intern('out'), pmt.cons(pmt.PMT_NIL, pmt.init_u8vector(len(buff), buff)))
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)
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() );
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)
def handle_msg(self, msg_pmt): msg = pmt.cdr(msg_pmt) if not pmt.is_u8vector(msg): print "[ERROR] Received invalid message type. Expected u8vector" return packet = array.array("B", pmt.u8vector_elements(msg)) header = CSP(packet[:4]) # check that message is beacon if header.destination != 10 or header.dest_port != 30: return beacon_type = packet[4] payload = packet[4:] if header.source != 1 or beacon_type != 0 or len(payload) != 140: return beacon = gomx3_beacon.beacon_1_0(payload) print """<Placemark> <name>{}</name> <description>Altitude: {}ft Time: {}</description> <styleUrl>#plane</styleUrl> <Point><coordinates>{},{}</coordinates></Point> </Placemark>""".format(hex(beacon.adsb_last_icao), beacon.adsb_last_alt, beacon.adsb_last_time, beacon.adsb_last_lon if beacon.adsb_last_lon <= 180 else beacon.adsb_last_lon - 360, beacon.adsb_last_lat)
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_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
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")
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)
def deframe_MSJ(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__ index = 8 del data_py[:index] # FC (1), DesEP(1),Cluster(2),Profile(2),SourEP(1),Counter(1) # 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 make_MPDU(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 # Toma Pmt pair a numpyarray y luego a list data_np = pmt.to_python(blob) # numpy.ndarray npdu = data_np.tolist() # python list Src_Add = self.SrcAddM # Dir 16 bit id de la red Dst_Add = [0xFF, 0xFF] # Coordinador 00 00 / #broadcast FF FF Pan_Id = self.PanId # PanID que estabece el coordinador LSB -MSB global Seq_M Seq_M[0] = Seq_M[0] + 1 if Seq_M[0] > 254: Seq_M[0] = 0 FC_M = [0x41, 0x88] # Frame control Mac LSB-MSB to_fcs = FC_M + Seq_M + Pan_Id + Dst_Add + Src_Add + npdu s_to_fcs = struct.pack("B" * len(to_fcs), *to_fcs) # Convierte List a String a = self.crc16(s_to_fcs) # Calcula FCS FCS = [a & 0xFF, (a >> 8) & 0xFF] MPDU = FC_M + Seq_M + Pan_Id + Dst_Add + Src_Add + npdu + FCS send_pmt = pmt.make_u8vector(len(MPDU), ord(" ")) # Crea PMT vacio for i in range(len(MPDU)): pmt.u8vector_set(send_pmt, i, MPDU[i]) # Copia Caracteres a u8vector: # Envia mensaje: self.message_port_pub(pmt.intern("out"), pmt.cons(pmt.PMT_NIL, send_pmt))
def handle_msg(self, msg_pmt): msg = pmt.cdr(msg_pmt) if not pmt.is_u8vector(msg): print "[ERROR] Received invalid message type. Expected u8vector" return self.kiss.extend(pmt.u8vector_elements(msg)) while self.kiss: c = self.kiss.popleft() if c == FEND: if self.pdu and not self.pdu[0] & 0x0f: msg = array.array('B', self.pdu[1:]) self.message_port_pub(pmt.intern('out'), pmt.cons(pmt.PMT_NIL, pmt.init_u8vector(len(msg), msg))) self.pdu = list() elif self.transpose: if c == TFEND: self.pdu.append(FEND) elif c == TFESC: self.pdu.append(FESC) self.transpose = False elif c == FESC: self.transpose = True else: self.pdu.append(c)
def make_NPDU(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 # Toma Pmt pair a numpyarray y luego a list data_np = pmt.to_python(blob) #numpy.ndarray apdu = data_np.tolist() #python list Src_Ieee = self.SrcIeeeN # la dir del USRP de 64 bit puede ser cualquiera global Seq_Num Seq_Num[0] = Seq_Num[0] +1 if Seq_Num[0] > 254: Seq_Num[0] = 0 Radio = [0x1E] # Saltos Max del mensaje Src_Add = self.SrcAddN # Puede ser cualquiera Dst_Add = [0xFF,0xFF] # Coordinador 00 00 / #broadcast FF FF FC_N = [0x08,0x10] # Frame Control LSB-MSB NPDU = FC_N + Dst_Add + Src_Add + Radio + Seq_Num + Src_Ieee + apdu # Crea PMT vacio send_pmt = pmt.make_u8vector(len(NPDU), ord(' ')) # Copia Caracteres a u8vector: for i in range(len(NPDU)): pmt.u8vector_set(send_pmt, i, NPDU[i]) # Envia mensaje: self.message_port_pub(pmt.intern('out'), pmt.cons(pmt.PMT_NIL, send_pmt))
def test_000 (self): if enable_vw_testing: return print "test_000" payload_sizes = [28, 60, 92, 124, 156, 188, 220] codeword_sizes = [47, 79, 111, 159, 191, 223 ,255] enc = nuts.ngham_encoder(self.tsb_key) dec = nuts.ngham_decoder(verbose=True) dbg = blocks.message_debug() self.tb.connect(enc,dec) self.tb.msg_connect(dec, "out", dbg, "store") port_in = pmt.intern("in") print "starting up" self.tb.start() i = 0 #for i in range(len(payload_sizes)*0 + 1): src_data = [x for x in range(payload_sizes[i])] src_vec = pmt.init_u8vector(len(src_data), src_data) msg = pmt.cons(pmt.PMT_NIL, src_vec) print "posting msg" enc.to_basic_block()._post(port_in, msg) #while dbg.num_messages() < 1: #print "waiting..." time.sleep(1) self.tb.stop() self.tb.wait() result_msg = dbg.get_message(0) vector = pmt.u8vector_elements(pmt.cdr(result_msg)) print metadata print vector
def handle_msg(self, msg_pmt): msg = pmt.cdr(msg_pmt) if not pmt.is_u8vector(msg): print "[ERROR] Received invalid message type. Expected u8vector" return packet = array.array("B", pmt.u8vector_elements(msg)) try: header = csp_header.CSP(packet[:4]) except ValueError as e: if self.verbose: print e return if not self.force and not header.crc: if self.verbose: print "CRC not used" self.message_port_pub(pmt.intern('ok'), msg_pmt) else: if len(packet) < 8: # bytes CSP header, 4 bytes CRC-32C if self.verbose: print "Malformed CSP packet (too short)" return crc = crc32c.crc(packet[:-4] if self.include_header else packet[4:-4]) packet_crc = struct.unpack(">I", packet[-4:])[0] if crc == packet_crc: if self.verbose: print "CRC OK" self.message_port_pub(pmt.intern('ok'), msg_pmt) else: if self.verbose: print "CRC failed" self.message_port_pub(pmt.intern('fail'), msg_pmt)
def handle_msg(self, msg_pmt): msg = pmt.cdr(msg_pmt) if not pmt.is_u8vector(msg): print "[ERROR] Received invalid message type. Expected u8vector" return packet = array.array("B", pmt.u8vector_elements(msg)) try: header = CSP(packet[:4]) except ValueError as e: print e return # check that message is beacon if header.destination != 10 or header.dest_port != 30: print "Not a beacon: destination address {} port {}".format(header.destination, header.dest_port) print return if len(packet) < 5: print "Malformed beacon (too short)" return beacon_type = packet[4] payload = packet[4:] beacon = None if header.source == 1 and beacon_type == 0 and len(payload) == 140: beacon = gomx3_beacon.beacon_1_0(payload) print(beacon if beacon else "Beacon type {} {}".format(header.source, beacon_type)) print
def test_004 (self): # Test that the TCP server can stream PDUs <= the MTU size. port = str(random.Random().randint(0, 30000) + 10000) mtu = 10000 srcdata = tuple(x % 256 for x in range(mtu)) data = pmt.init_u8vector(srcdata.__len__(), srcdata) pdu_msg = pmt.cons(pmt.PMT_NIL, data) self.pdu_source = blocks.message_strobe(pdu_msg, 500) self.pdu_send = blocks.socket_pdu("TCP_SERVER", "localhost", port, mtu) self.pdu_recv = blocks.socket_pdu("TCP_CLIENT", "localhost", port, mtu) self.pdu_sink = blocks.message_debug() self.tb.msg_connect(self.pdu_source, "strobe", self.pdu_send, "pdus") self.tb.msg_connect(self.pdu_recv, "pdus", self.pdu_sink, "store") self.tb.start() time.sleep(1) self.tb.stop() self.tb.wait() received = self.pdu_sink.get_message(0) received_data = pmt.cdr(received) msg_data = [] for i in range(mtu): msg_data.append(pmt.u8vector_ref(received_data, i)) self.assertEqual(srcdata, tuple(msg_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 handle_queue(self): if self.state == self.STATE_IDLE: if self.app_queue.empty() == False: self.last_tx_packet = self.app_queue.get() msg_str = "".join([chr(x) for x in pmt.u8vector_elements(pmt.cdr(self.last_tx_packet))]) self.curr_packet_len = len(msg_str[3:]) self.curr_packet_seq = ord(msg_str[0]) self.last_tx_time = time.time() print '[stop_and_wait] :: Sending packet. Payload len: '+ str(self.curr_packet_len) +' Queue fill level = ', self.app_queue.qsize() if self.use_ack: self.state = self.STATE_WAIT_FOR_ACK self.num_data_packets_send += 1 self.log_packet("TX", 0, self.curr_packet_len, self.curr_packet_seq, self.last_snr) self.message_port_pub(pmt.intern('to_phy'), self.last_tx_packet) elif self.state == self.STATE_WAIT_FOR_ACK: if (time.time() - self.last_tx_time) > self.ack_timeout: #retransmit print '[stop_and_wait] :: ACK timeout. Retransmitting' self.last_tx_time = time.time() self.num_ack_timeouts += 1 self.num_data_packets_send += 1 self.log_packet("TX", 0, self.curr_packet_len, self.curr_packet_seq, self.last_snr) self.message_port_pub(pmt.intern('to_phy'), self.last_tx_packet)
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)
def handle_msg(self, msg): meta = pmt.car(msg) data = pmt.cdr(msg) if not pmt.is_u8vector(data): raise NameError("Data is no u8 vector") packet = pmt.u8vector_elements(data) packet = array.array("B", packet) # TODO - add ax25 depacket try: string, payload, pid, ctrl, src, dest = ax25.printpacket(packet.tostring()) if self.verbose: print "Packet: ", packet.tostring() print "Payload: ", payload print "Payload(hex): ", self.hex_string(array.array("B", payload)) print "PID: %x" % pid print "CTRL: %x" % ctrl print "SRC: ", src print "DEST: ", dest payload = array.array("B", payload) # print outstream self.message_port_pub(pmt.intern("out"), pmt.cons(pmt.PMT_NIL, pmt.init_u8vector(len(payload), payload))) print "********Deframer: ", time.time() except: print ("Bad packet") return 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 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 test_002 (self): # Send a PDU through a pair of UDP sockets port = str(random.Random().randint(0, 30000) + 10000) srcdata = (0x64, 0x6f, 0x67, 0x65) data = pmt.init_u8vector(srcdata.__len__(), srcdata) pdu_msg = pmt.cons(pmt.PMT_NIL, data) self.pdu_source = blocks.message_strobe(pdu_msg, 500) self.pdu_recv = blocks.socket_pdu("UDP_SERVER", "localhost", port) self.pdu_send = blocks.socket_pdu("UDP_CLIENT", "localhost", port) self.dbg = blocks.message_debug() self.tb.msg_connect(self.pdu_source, "strobe", self.pdu_send, "pdus") self.tb.msg_connect(self.pdu_recv, "pdus", self.dbg, "store") self.tb.start () time.sleep(1) self.tb.stop() self.tb.wait() self.pdu_send = None self.pdu_recv = None received = self.dbg.get_message(0) received_data = pmt.cdr(received) msg_data = [] for i in range(4): msg_data.append(pmt.u8vector_ref(received_data, i)) self.assertEqual(srcdata, tuple(msg_data))
def handle_msg(self, msg_pmt): msg = pmt.cdr(msg_pmt) if not pmt.is_u8vector(msg): print "[ERROR] Received invalid message type. Expected u8vector" return packet = str(bytearray(pmt.u8vector_elements(msg))) data = None try: if self.verbose: print "Trying to decode as long packet: 250 FEC bytes, 92 data bytes" (data, bit_corr, byte_corr) = self.ec.decode(packet[1:]) except Exception as ex: if self.verbose: print(ex) try: if self.verbose: print "Trying to decode as short packet: 128 FEC bytes, 31 data bytes" (data, bit_corr, byte_corr) = self.ec.decode(packet[1:1 + 128]) except Exception as ex: if self.verbose: print(ex) if data: if self.verbose: print "FEC decoded OK. Bit errors: {}. Byte errors {}".format(bit_corr, byte_corr) data = data[:-2] # strip out HMAC self.message_port_pub(pmt.intern('out'), pmt.cons(pmt.PMT_NIL, pmt.init_u8vector(len(data), bytearray(data))))
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 recalc_msg(self, msg): if pmt.is_pair(msg): key = pmt.car(msg) val = pmt.cdr(msg) if pmt.eq(key, pmt.intern("recalc")): if pmt.is_integer(val): if pmt.to_long(val) == 10: global file_written file_written = 1 if pmt.to_long(val) == 20: global file_written file_written = 0 print "hello"
def handle_pkt(self, pkt_pmt): """ Handles packet received on the packet port :param pkt_pmt: """ print(pkt_pmt) car = pmt.to_python(pmt.car(pkt_pmt)) if car == 'pkt': data = pmt.to_python(pmt.cdr(pkt_pmt)) self.in_packets.put_nowait( numpy.frombuffer(data, dtype=numpy.uint8))
def handle_msg(self, msg_pmt): msg = pmt.cdr(msg_pmt) if not pmt.is_u8vector(msg): print "[ERROR] Received invalid message type. Expected u8vector" return array = bytearray(pmt.u8vector_elements(msg)) packet = base64.b64encode(array) time = datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S:%f") self.file.write(time + "," + str(self.direction) + "," + packet + "\n") self.file.flush()
def handle_msg(self, msg_pmt): msg = pmt.cdr(msg_pmt) if not pmt.is_u8vector(msg): print "[ERROR] Received invalid message type. Expected u8vector" return packet = bytearray(pmt.u8vector_elements(msg)) try: print(picsat_telemetry.Packet.parse(packet)) print except Exception: print "Error decoding telemetry" print
def msg_handler(self, msg): if not pmt.is_pair(msg): return if not pmt.is_dict(pmt.car(msg)): return if not pmt.is_uniform_vector(pmt.cdr(msg)): return arr = pmt.to_python(msg)[1] pmt.set_cdr(msg, pmt.to_pmt(arr[self.start_trim_length:-self.end_trim_length or len(arr)])) self.message_port_pub(pmt.intern("out"), msg)
def handle_msg(self, msg_pmt): msg = pmt.cdr(msg_pmt) if not pmt.is_u8vector(msg): print('[ERROR] Received invalid message type. Expected u8vector') return packet = np.array(pmt.u8vector_elements(msg), dtype='uint8') if packet.size % 10 != 0: print('[ERROR] Packet size is not a multiple of 10 bits') return packet = np.packbits(packet.reshape((-1, 10))[:, 1:-1]) self.message_port_pub( pmt.intern('out'), pmt.cons(pmt.PMT_NIL, pmt.init_u8vector(len(packet), packet)))
def handle_packet(self, pdu): t0 = time.time() self.packet_cnt += 1 tag_dict = pmt.car(pdu) vec = pmt.to_python(pmt.cdr(pdu)) data_si = util_data.bits_to_integers(vec, self.bits_per_symbol) symbs = self.modulate(data_si).astype(numpy.complex64) self.message_port_pub(self.port_id_out, pmt.cons(pmt.PMT_NIL, pmt.to_pmt(symbs))) t1 = time.time() self.logger.debug("classic mod {} handled {} bits in {} seconds".format( self.uuid_str, vec.size, t1 - t0))
def handler(self, pdu): meta = pmt.to_python(pmt.car(pdu)) #print type(pmt.cdr(pdu)) msg = pmt.to_python(pmt.cdr(pdu)) #print type(meta), meta meta['msg_hex'] = binascii.hexlify(msg) #metaj = json.dumps(meta, sort_keys=True, indent=4, separators=(',', ': ')); metaj = json.dumps(meta) #print binascii.hexlify(msg), metaj #Create new PDU and emit vector = pmt.init_u8vector(len(metaj) + 1, bytearray(metaj + '\n')) pdu = pmt.cons(pmt.to_pmt(None), vector) self.message_port_pub(pmt.intern('out'), pdu)
def msgHandler(self, msg): try: newVal = pmt.to_python(pmt.cdr(msg)) if type(newVal) == float or type(newVal) == int: super().change_angle(float(newVal)) else: print( "[Compass] Error: Value received was not an int or a float: %s" % str(e)) except Exception as e: print("[Compass] Error with message conversion: %s" % str(e))
def test_bit_flip(self): self.dut = pdu_utils.pdu_binary_tools(0) self.connectUp() i_vec = pmt.init_u8vector(6, [1, 0, 0, 1, 0, 1]) e_vec = pmt.init_u8vector(6, [0, 1, 1, 0, 1, 0]) 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 bit_flip:") print("pdu expected: " + repr(pmt.car(e_pdu))) print("pdu got: " + repr(pmt.car(self.debug.get_message(0)))) print("data expected: " + repr(pmt.u8vector_elements(pmt.cdr(e_pdu)))) print("data got: " + repr(pmt.u8vector_elements(pmt.cdr(self.debug.get_message(0))))) print(self.assertTrue(pmt.equal(self.debug.get_message(0), e_pdu)))
def handle_body(self, pdu): t0 = time.time() self.npackets += 1 tags = pmt.car(pdu) data = pmt.to_python(pmt.cdr(pdu)) assert type(data) is numpy.ndarray assert type(data[0]) is numpy.complex64 frame = self.wrapper.wrap(data) self.message_port_pub(self.port_out_id, pmt.cons(tags, pmt.to_pmt(frame))) t1 = time.time() self.logger.debug("packet wrap {} handled {} symbols in {} seconds".format( self.uuid_str, data.size, t1 - t0))
def msgHandler(self, msg): try: newVal = pmt.to_python(pmt.cdr(msg)) if type(newVal) == float or type(newVal) == int: super().setValue(newVal) else: print( "[LevelGauge] Error: Value received was not an int or a float: %s" % str(e)) except Exception as e: print("[LevelGauge] Error with message conversion: %s" % str(e))
def handle_msg(self, msg_pmt): msg = pmt.cdr(msg_pmt) if not pmt.is_u8vector(msg): print("[ERROR] Received invalid message type. Expected u8vector") return packet = bytes(pmt.u8vector_elements(msg)) try: data = kr01_telemetry.Beacon.parse(packet[0x23:]) except: print("Could not parse telemetry beacon") return print(data)
def handle_msg(self, msg_pmt): msg = pmt.cdr(msg_pmt) if not pmt.is_u8vector(msg): print("[ERROR] Received invalid message type. Expected u8vector") return packet = bytes(pmt.u8vector_elements(msg)) # try: data = floripasat_telemetry.Packet.parse(packet) # except: # print("Could not decode telemetry beacon") # return print(data)
def test_tagger(self): """Runs some test data through the tagger and checks resulting PDUs""" self.tb.start() self.tb.wait() self.assertEqual(self.debug.num_messages(), len(self.tag_positions), 'Unexpected number of PDUs') for j, pos in enumerate(self.tag_positions): pdu = np.array(pmt.u8vector_elements( pmt.cdr(self.debug.get_message(j))), dtype='uint8') expected = self.data[pos:pos+self.packet_len] np.testing.assert_equal(pdu, expected, 'PDU values do not match expected')
def handle_msg(self, msg_pmt): msg = pmt.cdr(msg_pmt) if not pmt.is_u8vector(msg): print("[ERROR] Received invalid message type. Expected u8vector") return packet = np.array(pmt.u8vector_elements(msg), dtype='uint8') packet = np.unpackbits(packet) packet = reflect(packet) packet = bytes(np.packbits(packet)) self.message_port_pub( pmt.intern('out'), pmt.cons(pmt.PMT_NIL, pmt.init_u8vector(len(packet), packet)))
def _msgHandler(self, msg): if not pmt.is_pair(msg): return key = str(pmt.car(msg)) key = key.lower() value = pmt.cdr(msg) print(key) handler = self.handlers.get(key, self.invalid) handler(value)
def main(top_block_cls=eve_sim, options=None): tb = top_block_cls() tb.start() tb.wait() for i in range(10): print pmt.symbol_to_string(pmt.cdr((tb.blocks_message_debug_0.get_message(i)))) print tb.blocks_message_debug_0.num_messages() tb.stop() tb.wait()
def handle_msg(self, msg_pmt): # print msg_pmt #msg_pmt_cdr = pmt.cdr(msg_pmt) # msg_str = "".join([chr(x) for x in pmt.u8vector_elements(msg)]) msg = pmt.cdr(msg_pmt) msg_str = "".join([chr(x) for x in pmt.u8vector_elements(msg)]) #msg_str = filter(lambda x: x in string.printable, msg_str) #msg_str = pmt.symbol_to_string(msg_pmt) msg_cutted = msg_str[24:] # print "Server: Handle MSG: "+msg_cutted # Change setting of the transceiver self.send_to_clients(msg_cutted)
def handle_msg(self, msg_pmt): msg = pmt.cdr(msg_pmt) if not pmt.is_u8vector(msg): print "[ERROR] Received invalid message type. Expected u8vector" return packet = bytearray(pmt.u8vector_elements(msg)) try: data = telecommand.FullPacket.parse(packet[:]) except: print "Could not decode telecommand packet" return print(data)
def handler(self, msg): meta = pmt.car(msg) x = pmt.to_python(pmt.cdr(msg)) # put bits into bitarray .. ba = bitarray.bitarray() for i in x: ba.append(i) # send packed vec2 = numpy.frombuffer(ba.tobytes(), dtype='uint8') self.message_port_pub(pmt.intern("pdus"), pmt.cons(meta, pmt.to_pmt(vec2)))
def handle_msg(self, pdu): if self.metadict_mode == "META": meta = pmt.car(pdu) try: val = pmt.to_python(pmt.dict_ref(meta, self.key, pmt.PMT_NIL)) if val: val = self.fn(val) meta = pmt.dict_add(meta, self.key, pmt.to_pmt(val)) except Exception as e: print(e) pass self.message_port_pub(pmt.intern("pdu"), pmt.cons(meta, pmt.cdr(pdu))) elif self.metadict_mode == "UVEC": vec = pmt.cdr(pdu) try: vec = pmt.to_pmt(self.fn(pmt.to_python(vec))) except Exception as e: print(e) pass self.message_port_pub(pmt.intern("pdu"), pmt.cons(pmt.car(pdu), vec)) elif self.metadict_mode == "RAW": # TODO: This is more of a "message lambda" block, in the future it should be # a separate block outside the PDU namespace try: pdu = self.fn(pdu) except Exception as e: print(e) pass self.message_port_pub(pmt.intern("pdu"), pdu) else: raise ValueError("pdu_lambda block instantiated in unknown mode " + repr(self.metadict_mode)) pass
def msgHandler(self, msg): try: new_val = pmt.to_python(pmt.cdr(msg)) if type(new_val) == float or type(new_val) == int: self.call_var_callback(new_val) self.setValue(new_val) else: gr.log.error("Value received was not an int or a float. %s" % str(type(new_val))) except Exception as e: gr.log.error("Error with message conversion: %s" % str(e))
def msg_handler(self, pdu): meta = pmt.car(pdu) data = pmt.c32vector_elements(pmt.cdr(pdu)) data = [ d * r for d, r in zip( data, np.exp(1j * np.linspace(0, 2 * np.pi * self.rotate * len(data), len(data)))) ] self.message_port_pub( pmt.intern("out"), pmt.cons(meta, pmt.init_c32vector(len(data), data)))
def handle_msg(self, msg_pmt): msg = pmt.cdr(msg_pmt) if not pmt.is_u8vector(msg): print("[ERROR] Received invalid message type. Expected u8vector") return packet = bytes(pmt.u8vector_elements(msg)) packet_length = packet[0] + 1 + self.crc_len self.message_port_pub( pmt.intern('out'), pmt.cons(pmt.car(msg_pmt), pmt.init_u8vector(packet_length, packet)))
def handle_msg(self, msg_pmt): msg = pmt.cdr(msg_pmt) if not pmt.is_u8vector(msg): print "[ERROR] Received invalid message type. Expected u8vector" return packet = bytearray(pmt.u8vector_elements(msg)) try: data = au03_telemetry.Beacon.parse(packet[4:]) except: print "Could not decode telemetry beacon" return print(data)
def msgHandler(self, msg): try: newVal = pmt.to_python(pmt.cdr(msg)) if type(newVal) == float or type(newVal) == int: self.updateData(newVal) else: print( "[DistanceRadar] Error: Value received was not an int or a float: %s" % str(e)) except Exception as e: print("[DistanceRadar] Error with message conversion: %s" % str(e))
def set_signal_number_msg(self, msg): if pmt.is_pair(msg): key = pmt.car(msg) val = pmt.cdr(msg) if pmt.eq(key, pmt.string_to_symbol("signal_number_msg")): if pmt.is_integer(val): self.n = pmt.to_long(val) else: print("DoA Esprit: Not an integer") else: print("DoA Esprit: Key not 'signal_number_msg'") else: print("DoA Esprit: Not a tuple")
def handle_msg(self, msg): msgs = pmt.cdr(msg) msg_str = "".join([chr(x) for x in pmt.u8vector_elements(msgs)]) print msg_str print self.message self.message = msg self.message_port_pub(pmt.intern('message_stream out'), self.message) if pmt.eq(self.message, msg): print "No change" pass else: print "Changed" self.message = msg
def handle_msg(self, msg_pmt): msg = pmt.cdr(msg_pmt) if not pmt.is_u8vector(msg): print("[ERROR] Received invalid message type. Expected u8vector") return packet = bytes(pmt.u8vector_elements(msg)) block_size = 46 # check packet len if len(packet) != block_size + 2: return block = struct.unpack('<H', packet[:2])[0] data = packet[2:] if self.current_file == -1: if block == 0: # first file received print("Starting image 0") self.current_file = 0 self.filename = os.path.join( self.path, 'img{}.jpg'.format(self.current_file)) self.f = open(self.filename, 'wb', 0) else: return elif block == 0: # new file print("Image {} finished. Starting image {}".format( self.current_file, self.current_file + 1)) self.f.close() self.current_file += 1 self.expected_block = 0 self.filename = os.path.join(self.path, 'img{}.jpg'.format(self.current_file)) self.f = open(self.filename, 'wb', 0) self.displaying = False elif block != self.expected_block: # lost block print("Lost image block {}".format(self.expected_block)) print("Received image block {}".format(block)) self.f.seek(block_size * block) self.f.write(data) self.expected_block = block + 1 if self.display and not self.displaying and block >= 5: self.displaying = True try: self.feh.open(self.filename) except Exception: pass