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 handler(self, msg): ba = bitarray.bitarray(); meta = pmt.car(msg); packed_data = pmt.cdr(msg); # convert pmt -> int list (of packed bytes) data = array.array('B', pmt.u8vector_elements(packed_data)) # add header on front header = struct.pack('hh', 0x1337, 8*len(data)); ba.frombytes(header); # compute header crc c2 = binascii.crc32(ba.tobytes()); hcrc = struct.pack('i', c2); ba.frombytes(hcrc); # add the data payload ba.frombytes(data.tostring()) # compute payload crc c2 = binascii.crc32(ba.tobytes()); pcrc = struct.pack('i', c2); ba.frombytes(pcrc); # convert the unpacked bits to a list and back into a pmt u8vector burst_bits = pmt.init_u8vector(len(ba), ba.tolist()); print "Tx Packet: " + ":".join("{:02x}".format(ord(c)) for c in ba.tobytes()[0:8]) # make the new pdu pdu = pmt.cons(meta, burst_bits); # send it on its way self.message_port_pub(pmt.intern("unpacked_pdus"), pdu);
def handle_msg(self, msg): #if message run hdlc encoder meta = pmt.car(msg) data = pmt.cdr(msg) if not pmt.is_u8vector(data): raise NameError("Data is no u8 vector") payload = pmt.u8vector_elements(data) payload = array.array('B', payload) outstream = ax25.sendpacket(payload, self.preamble_length, self.postamble_length) if (self.use_scrambler): outstream = ax25.scrambler(outstream) outstream = ax25.nrziencode(outstream) outstream = array.array('B', outstream) #print outstream self.message_port_pub( pmt.intern('out'), pmt.cons(pmt.PMT_NIL, pmt.init_u8vector(len(outstream), outstream))) 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 pdu_to_msg(pdu, debug=False): '''Extracts message from PDU. @param pdu: a PDU. @param debug: print additional information, default False. @return: (metadata, message string). ''' # code taken from chat_blocks in GNURadio tutorial 5 # collect metadata, convert to Python format: meta = pmt.to_python(pmt.car(pdu)) # collect message, convert to Python format: msg = pmt.cdr(pdu) # make sure it's a u8vector if not pmt.is_u8vector(msg): print "[ERROR] Received invalid message type.\n" return ('', '') # convert to string: msg_str = "".join([chr(x) for x in pmt.u8vector_elements(msg)]) if debug: if meta is None: msg_dbg = "[METADATA]: None, [CONTENTS]: " + msg_str else: msg_dbg = "[METADATA]: " + meta + ", [CONTENTS]: " + msg_str mutex_prt(msg_dbg) return (meta, msg_str)
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 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') # Decode ESEO "line coding" packet = np.unpackbits(packet) packet = destuff(packet) if packet is None: return packet = descramble(packet) packet = nrzi_decode(packet) packet = reflect_bytes(packet) # Remove dummy padding cutbits = packet.size % 8 if cutbits: packet = packet[:-cutbits] packet = np.packbits(packet) packet = bytes(packet) self.message_port_pub( pmt.intern('out'), pmt.cons(pmt.car(msg_pmt), pmt.init_u8vector(len(packet), packet)))
def handler(self, pdu): (ometa, data) = (pmt.to_python(pmt.car(pdu)), pmt.cdr(pdu)) d = {} try: # grab all mboard sensor data uhd_source = eval("self.parent.%s" % (self.target)) mbs = uhd_source.get_mboard_sensor_names() for k in mbs: v = uhd_source.get_mboard_sensor(k) d[k] = v.value d["gain"] = uhd_source.get_gain() d["gps_present"] = True gps_location = subprocess.Popen( ["gpspipe", "-w", "-o", "-t", "|", "grep", "-m", "1", "lon"], stdout=PIPE) except AttributeError: d["gps_present"] = False #pprint.pprint(d); ometa.update(d) self.message_port_pub(pmt.intern("pdus"), pmt.cons(pmt.to_pmt(ometa), data), pmt.intern("gps_location"))
def msgHandler(self, msg): new_val = None try: new_val = pmt.to_python(pmt.car(msg)) if new_val is not None: if type(new_val) == dict: if 'az' in new_val and 'el' in new_val: self.updateData(float(new_val['az']), float(new_val['el'])) else: gr.log.error( "az and el keys were not found in the dictionary.") else: gr.log.error( "Value received was not a dictionary. Expecting a dictionary " "in the car message component with az and el keys.") else: gr.log.error( "The CAR section of the inbound message was None. " "This part should contain the dictionary with 'az' and 'el' float keys." ) except Exception as e: gr.log.error("[AzElPlot] Error with message conversion: %s" % str(e)) if new_val is not None: gr.log.error(str(new_val))
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, 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 packetise(self, msg): data = pmt.cdr(msg) meta = pmt.car(msg) if not pmt.is_u8vector(data): #raise NameError("Data is no u8 vector") return "Message data is not u8vector" buf = pmt.u8vector_elements(data) buf_str = "".join(map(chr, buf)) # FIXME: Max: 4096-header-crc meta_dict = pmt.to_python(meta) if not (type(meta_dict) is dict): meta_dict = {} pkt = "" pkt += self.preamble pkt += packet_utils.make_packet( buf_str, 0, #self._samples_per_symbol, 0, #self._bits_per_symbol, #preamble=<default> access_code=self.access_code, pad_for_usrp=False, #pad_for_usrp, whitener_offset=self.whitener_offset, whitening=self.whiten) pkt += self.postamble pkt = map(ord, list(pkt)) if self.rotate_whitener_offset: self.whitener_offset = (self.whitener_offset + 1) % 16 meta = pmt.to_pmt(meta_dict) data = pmt.init_u8vector(len(pkt), pkt) self.message_port_pub(pmt.intern('out'), pmt.cons(meta, data)) '''
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))
def input_msg(self, msg): if self.count_packets: self.ctr += 1 pdu = pmt.cdr(msg) b0 = pmt.u8vector_ref(pdu, 0) b1 = pmt.u8vector_ref(pdu, 1) b2 = pmt.u8vector_ref(pdu, 2) b3 = pmt.u8vector_ref(pdu, 3) if self.textfile: self.textfile.write("PACKET meta:" + str(pmt.car(msg)) + "\n") self.textfile.write("\tfirst bytes:") for i in range(4): self.textfile.write(str(pmt.u8vector_ref(pdu, i)) + "\t") self.textfile.write("\n") new_seq_nr = (b0 << 0) + (b1 << 8) + (b2 << 16) + (b3 << 24) if new_seq_nr > self.seq_numbers[0]: if self.first_seqnr is None: self.first_seqnr = new_seq_nr self.unique_msg_ctr += 1 # if new_seq_nr - self.seq_numbers[0] > 1: # print "\t missed", new_seq_nr - self.seq_numbers[0] - 1, "frame(s)!" # print "new seq #:", new_seq_nr self.seq_numbers.appendleft(new_seq_nr) self.PER = 1 - len(self.seq_numbers) / float( self.seq_numbers[0] - self.seq_numbers[-1] + 1)
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 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 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 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
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 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_command(self, msg): with self.lock: # incoming message will be a dictionary that should contain the items # freq and lo_offset at a minimum - if this is met, issue a command # that can be handled by the freq_xlating_fir_filter_ccf block try: # print "got a message!" # we don't care about the frequency since we are CORDIC tuning lo_offset = pmt.dict_ref(msg, self.dict_key, pmt.PMT_NIL) if not pmt.eqv(lo_offset, pmt.PMT_NIL): offset = pmt.to_python(lo_offset) # print "lo offset is " + repr(offset*-1.0) self.message_port_pub(pmt.intern("freq"), pmt.cons(pmt.intern("freq"), pmt.from_double(-1.0*offset))) # print "published msg, offset = " + repr(-1.0*offset) # if the dictionary has a time value, use it time_tag = pmt.dict_ref(msg, pmt.intern("time"), pmt.PMT_NIL) if not pmt.eqv(time_tag, pmt.PMT_NIL): secs = pmt.to_uint64(pmt.car(time_tag)) - self.ref_time['secs'] frac = pmt.to_double(pmt.cdr(time_tag)) - self.ref_time['frac'] tune_sample = long(secs * self.sample_rate) + long(frac * self.sample_rate) + self.ref_time['offset'] else: tune_sample = TAG_IMMEDIATELY # we will also set the block to tag the output when it is time if len(self.tune_commands) < self.tune_commands.maxlen: self.tune_commands.append((tune_sample,pmt.from_double(-1.0*offset))) except Exception as e: print "exception: " + repr(e)
def msg_handler(self, m): if not pmt.is_pair(m): return meta = pmt.car(m) if not pmt.is_dict(meta): return blockstart = pmt.to_long( pmt.dict_ref(meta, pmt.intern('blockstart'), pmt.from_long(-1024))) blockend = pmt.to_long( pmt.dict_ref(meta, pmt.intern('blockend'), pmt.from_long(-1024))) if blockstart == -1024 or blockend == -1024: return rel_cfreq = pmt.to_double( pmt.dict_ref(meta, pmt.intern('rel_cfreq'), pmt.from_double(-1.0))) rel_bw = pmt.to_double( pmt.dict_ref(meta, pmt.intern('rel_bw'), pmt.from_double(-1.0))) if rel_cfreq < 0.0 or rel_bw < 0.0: return blockleft = int(self.normwidth * (rel_cfreq - rel_bw / 2.0)) blockright = int( numpy.ceil(self.normwidth * (rel_cfreq + rel_bw / 2.0))) #print('new msg: {} {} {} {} {} {}'.format(blockstart, blockend, rel_cfreq, rel_bw, blockleft, blockright)) self.msg_puffer += [(blockstart, blockend, blockleft, blockright)]
def test_002_normal(self): tnow = time.time() in_data = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1] meta = pmt.dict_add(pmt.make_dict(), pmt.intern( 'system_time'), pmt.from_double(tnow - 10.0)) in_pdu = pmt.cons(meta, pmt.init_c32vector(len(in_data), in_data)) e_data = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1] e_meta = pmt.dict_add(pmt.make_dict(), pmt.intern( 'system_time'), pmt.from_double(tnow)) e_meta = pmt.dict_add(e_meta, pmt.intern( 'sys time delta (ms)'), pmt.from_double(10000.0)) e_pdu = pmt.cons(e_meta, pmt.init_c32vector(len(e_data), e_data)) # set up fg self.tb.start() self.time_delta.to_basic_block()._post(pmt.intern("pdu"), in_pdu) self.waitFor(lambda: self.debug.num_messages() == 1, timeout=1.0, poll_interval=0.01) self.tb.stop() self.tb.wait() # check data self.assertEqual(1, self.debug.num_messages()) a_meta = pmt.car(self.debug.get_message(0)) time_tag = pmt.dict_ref(a_meta, pmt.intern("system_time"), pmt.PMT_NIL) delta_tag = pmt.dict_ref(a_meta, pmt.intern( "sys time delta (ms)"), pmt.PMT_NIL) self.assertAlmostEqual(tnow, pmt.to_double(time_tag), delta=60) self.assertAlmostEqual(10000, pmt.to_double(delta_tag), delta=10)
def test_pdu_add_meta(self): tb = gr.top_block() dbg = blocks.message_debug() meta = pmt.make_dict() meta = pmt.dict_add(meta, pmt.intern('k1'), pmt.intern('v1')) meta = pmt.dict_add(meta, pmt.intern('k2'), pmt.intern('v2')) add_meta = pdu_add_meta(meta) pdu = pmt.cons(pmt.PMT_NIL, pmt.make_u8vector(10, 0)) tb.msg_connect((add_meta, 'out'), (dbg, 'store')) add_meta.to_basic_block()._post(pmt.intern('in'), pdu) add_meta.to_basic_block()._post( pmt.intern('system'), pmt.cons(pmt.intern('done'), pmt.from_long(1))) tb.start() tb.wait() pdu_out = dbg.get_message(0) meta_out = pmt.car(pdu_out) self.assertTrue(pmt.dict_has_key(meta_out, pmt.intern('k1')), 'Test key k1 not in output PDU metadata') self.assertTrue(pmt.dict_has_key(meta_out, pmt.intern('k2')), 'Test key k1 not in output PDU metadata') self.assertEqual(pmt.u8vector_elements(pmt.cdr(pdu_out)), pmt.u8vector_elements(pmt.cdr(pdu)), 'Output PDU data does not match input PDU data')
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 handler(self, msg): ba = bitarray.bitarray() meta = pmt.car(msg) packed_data = pmt.cdr(msg) # convert pmt -> int list (of packed bytes) data = array.array('B', pmt.u8vector_elements(packed_data)) # add header on front header = struct.pack('hh', 0x1337, 8 * len(data)) ba.frombytes(header) # compute header crc c2 = binascii.crc32(ba.tobytes()) hcrc = struct.pack('i', c2) ba.frombytes(hcrc) # add the data payload ba.frombytes(data.tostring()) # compute payload crc c2 = binascii.crc32(ba.tobytes()) pcrc = struct.pack('i', c2) ba.frombytes(pcrc) # convert the unpacked bits to a list and back into a pmt u8vector burst_bits = pmt.init_u8vector(len(ba), ba.tolist()) print "Tx Packet: " + ":".join("{:02x}".format(ord(c)) for c in ba.tobytes()[0:8]) # make the new pdu pdu = pmt.cons(meta, burst_bits) # send it on its way self.message_port_pub(pmt.intern("OUT"), pdu)
def test_004_boost_time(self): self.tb = gr.top_block() start_time = 0.1 sob_tag = gr.tag_utils.python_to_tag( (34, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) eob_tag = gr.tag_utils.python_to_tag( (34 + (8 * 31), pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) vs = blocks.vector_source_s(range(350), False, 1, [sob_tag, eob_tag]) t2p = pdu_utils.tags_to_pdu_s(pmt.intern('SOB'), pmt.intern('EOB'), 1024, 512000, ([]), False, 0, start_time) t2p.enable_time_debug(True) t2p.set_eob_parameters(8, 0) dbg = blocks.message_debug() #td = pdu_utils.time_delta("TIME CHECKER") #td = timing_utils.time_delta("TIME CHECKER") self.tb.connect(vs, t2p) self.tb.msg_connect((t2p, 'pdu_out'), (dbg, 'store')) #self.tb.msg_connect((t2p, 'pdu_out'), (td, 'pdu_in')) expected_vec = pmt.init_s16vector((8 * 31), range(34, 34 + (8 * 31))) expected_time = start_time + (34 / 512000.0) ts = time.time() self.tb.run() self.assertEqual(dbg.num_messages(), 1) self.assertTrue(pmt.equal(pmt.cdr(dbg.get_message(0)), expected_vec)) time_tuple1 = pmt.dict_ref(pmt.car(dbg.get_message(0)), pmt.intern("burst_time"), pmt.PMT_NIL) self.assertAlmostEqual( pmt.to_uint64(pmt.tuple_ref(time_tuple1, 0)) + pmt.to_double(pmt.tuple_ref(time_tuple1, 1)), expected_time) #wct = pmt.to_double(pmt.dict_ref(pmt.car(dbg.get_message(0)), pmt.intern("wall_clock_time"), pmt.PMT_NIL)) #self.assertTrue((wct - ts) < 1.0) self.tb = None
def test_002_tags_plus_data(self): packet_len = 16 src_data = list(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 = pdu.tagged_stream_to_pdu(gr.types.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() 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 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 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") payload = pmt.u8vector_elements(data) payload = array.array('B', payload) if len(payload) > AX25_MAX_PAYLOAD: print 'Payload too large for an HDLC(AX25) frame' return 0 #TODO - add paramters for each in this functions packet = ax25.buildpacket(self.mycall, 1, self.destcall, 0, "0", 0, 0x03, 0xf0, payload.tostring()) if self.verbose: print "Payload: ", payload.tostring() print "Packet: ", packet print "********Framer:", time.time() print self.hex_string(packet) packet = array.array('B', packet) #print outstream self.message_port_pub( pmt.intern('out'), pmt.cons(pmt.PMT_NIL, pmt.init_u8vector(len(packet), packet))) return 0
def test_002_secondSOB(self): self.tb = gr.top_block() start_time = 4.999999999 sob_tag = gr.tag_utils.python_to_tag( (34, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) sob_tag2 = gr.tag_utils.python_to_tag( (51, pmt.intern("SOB"), pmt.PMT_T, pmt.intern("src"))) eob_tag = gr.tag_utils.python_to_tag( (51 + (8 * 26), pmt.intern("EOB"), pmt.PMT_T, pmt.intern("src"))) vs = blocks.vector_source_s(range(350), False, 1, [sob_tag, sob_tag2, eob_tag]) t2p = pdu_utils.tags_to_pdu_s(pmt.intern('SOB'), pmt.intern('EOB'), 1024, 460800, ([]), False, 0, start_time) t2p.set_eob_parameters(8, 0) dbg = blocks.message_debug() self.tb.connect(vs, t2p) self.tb.msg_connect((t2p, 'pdu_out'), (dbg, 'store')) expected_vec = pmt.init_s16vector((8 * 26), range(51, 51 + (8 * 26))) expected_time = start_time + (51 / 460800.0) self.tb.run() self.assertEqual(dbg.num_messages(), 1) self.assertTrue(pmt.equal(pmt.cdr(dbg.get_message(0)), expected_vec)) time_tuple1 = pmt.dict_ref(pmt.car(dbg.get_message(0)), pmt.intern("burst_time"), pmt.PMT_NIL) self.assertAlmostEqual( pmt.to_uint64(pmt.tuple_ref(time_tuple1, 0)) + pmt.to_double(pmt.tuple_ref(time_tuple1, 1)), expected_time) self.tb = None
def 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 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()
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()
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 handle_payload_message(self, msg_pmt): meta = pmt.to_python(pmt.car(msg_pmt)) packet_num = meta["packet_num"] packet_rx_time = meta["rx_time"] packet_rx_time_full_sec = packet_rx_time[0] packet_rx_time_frac_sec = packet_rx_time[1] msg = pmt.cdr(msg_pmt) msg_data = pmt.u8vector_elements(msg) self.num_rec_packets += 1 self.sum_snr += self.curr_snr ok = True timestamp = packet_rx_time_full_sec + packet_rx_time_frac_sec print '[per_logger] Packet: rx_time = ' + str( timestamp) + ' id = ' + str(packet_num) log_packet_simple(timestamp, packet_num) if self.check_payload: user_data = list(msg_data)[self.skip_header_bytes_start:-self. skip_header_bytes_end] byte_errors, bit_errors = self.compare_lists( user_data, self.payload) if bit_errors > 0: self.num_packet_errors += 1 ok = False self.log_packet(timestamp, self.curr_snr, byte_errors, bit_errors, packet_num) else: self.log_packet(timestamp, self.curr_snr, 0, 0, packet_num)
def handle_msg(self, msg_pmt): """Process incoming GNU Radio PDU containing a Blocksat Packet Args: msg_pmt : the message containing a Blocksat Packet """ # Get metadata and information from message meta = pmt.to_python(pmt.car(msg_pmt)) msg = pmt.cdr(msg_pmt) # Validate (message should be a vector of u8, i.e. bytes) if not pmt.is_u8vector(msg): print "[ERROR] Received invalid message type.\n" return # Convert incoming packet to a bytes string raw_pkt = b''.join([chr(x) for x in pmt.u8vector_elements(msg)]) if (self.protocol_version > 1): # Parse Blocksat Packet packet = BlocksatPacket(raw_pkt) # Process the parsed packet self.handle_pkt(packet) else: # Write raw data directly to named pipe self.blk_pipe.write(raw_pkt)
def pdu_arg_add(pdu, k, v): meta = pmt.car(pdu); data = pmt.cdr(pdu); if(pmt.is_null(meta)): meta = pmt.make_dict(); assert(pmt.is_dict(meta)); meta = pmt.dict_add(meta, k, v); return pmt.cons(meta,data);
def handle_msg(self, msg_pmt): meta = pmt.to_python(pmt.car(msg_pmt)) msg = pmt.cdr(msg_pmt) #TODO: Fix this ... hack hack hack bin_str = int("".join(map(lambda x: '1' if x else '0', pmt.u8vector_elements(msg))), 2) data = struct.pack('xB7xBB', meta['chan'], 0xe9, 0x8a) data += bytearray.fromhex(hex(bin_str)[2:-1]) self.write_packet(data)
def received_msg(self, msg): meta = pmt.car(msg) meta_dict = pmt.to_python(meta) print >> sys.stderr, 'seq no. =', meta_dict['seq_nr'] data = pmt.cdr(msg) data = pmt.u8vector_elements(data) print >> sys.stderr, 'received data:\n', data print >> sys.stderr, '\n'
def handler(self, msg): #print "synch starting new sync" self.start_timer(); # get input meta = pmt.car(msg); samples = pmt.cdr(msg); x = numpy.array(pmt.c32vector_elements(samples), dtype=numpy.complex64) self.diff_timer("get_input"); # correct for CFO eqBurst = self.qpskBurstCFOCorrect(x, self.Fs) self.diff_timer("cfo") # determine preamble start preCrossCorr = numpy.absolute(numpy.correlate(self.preSyms_x2, eqBurst, 'full')) maxIdx = numpy.argmax(preCrossCorr) preambleIdxStart = len(eqBurst) - maxIdx - 1 eqIn = eqBurst[preambleIdxStart:] # decimate the signal to 1sps (right now the constructor enforces teh 2 sps) eqIn_decimated = eqIn[0:len(eqIn):2] self.diff_timer("timing") wOpt = self.determineOptimalFilter(eqIn_decimated) self.diff_timer("est_filter") # filter the input signal w/ the optimal filter (in MMSE sense) # todo, do we need to remove the extra syms at the end produced by conv? whFilt = numpy.convolve(wOpt, eqIn_decimated) whFiltMean = numpy.mean(numpy.absolute(whFilt)) whFilt /= whFiltMean self.diff_timer("apply filt") # correct any residual phase offset w/ the 1st order PLL alpha = 0.002 phRecoveredSyms = self.qpskFirstOrderPLL(whFilt, alpha) self.diff_timer("residual phase") # if(self.debugMode): # dictToSave = {} # dictToSave['gr_eqBurst'] = eqBurst # dictToSave['gr_preCrossCorr'] = preCrossCorr # dictToSave['gr_eqIn'] = eqIn # dictToSave['gr_wOpt'] = wOpt # dictToSave['gr_whFilt'] = whFilt # dictToSave['gr_phRecoveredSyms'] = phRecoveredSyms # sio.savemat(self.debugFilename, dictToSave) # publish equalized symbols c = map(lambda i: complex(i), phRecoveredSyms); xcm = pmt.init_c32vector(len(c), c) #xcm = pmt.init_c32vector(phRecoveredSyms.size, map(lambda i: complex(i), phRecoveredSyms)) xcm_cpdu = pmt.cons(meta,xcm) self.message_port_pub(pmt.intern("cpdus"), xcm_cpdu); self.diff_timer("publish result") self.burstidx = self.burstidx + 1;
def radio_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") incoming_pkt = data #get data print >> sys.stderr, '@MAC.radio_rx\t\tincoming pkt:', incoming_pkt if ( len(incoming_pkt) > 5 ): #check for weird header only stuff if( ( incoming_pkt[PKT_INDEX_DEST] == self.addr or incoming_pkt[PKT_INDEX_DEST] == 255) and not incoming_pkt[PKT_INDEX_SRC] == self.addr): #for us? #check to see if we must ACK this packet if(incoming_pkt[PKT_INDEX_CTRL] == ARQ_REQ): #TODO, stuff CTRL and Protocol in one field self.send_ack(incoming_pkt[PKT_INDEX_SRC],incoming_pkt[PKT_INDEX_CNT]) #Then send ACK then if not (self.arq_expected_sequence_number == incoming_pkt[PKT_INDEX_CNT]): self.arq_sequence_error_cnt += 1 self.throw_away = True print >> sys.stderr, "@MAC.radio_rx\t\tThrow away" else: self.throw_away = False self.arq_expected_sequence_number = ( incoming_pkt[PKT_INDEX_CNT] + 1 ) % 255 else: if not (self.no_arq_expected_sequence_number == incoming_pkt[PKT_INDEX_CNT]): self.no_arq_sequence_error_cnt += 1 #print self.no_arq_sequence_error_cnt #print self.no_arq_sequence_error_cnt,incoming_pkt[PKT_INDEX_CNT],self.no_arq_expected_sequence_number self.no_arq_expected_sequence_number = ( incoming_pkt[PKT_INDEX_CNT] + 1 ) % 255 incoming_protocol_id = incoming_pkt[PKT_INDEX_PROT_ID] #check to see if this is an ACK packet if(incoming_protocol_id == ARQ_PROTOCOL_ID): if incoming_pkt[5] == self.expected_arq_id: self.arq_channel_state = ARQ_CHANNEL_IDLE self.pkt_cnt_arq = ( self.pkt_cnt_arq + 1 ) % 255 print >> sys.stderr, '@MAC.radio_rx\t\tACKED, PKT_ID:', self.expected_arq_id else: print >> sys.stderr, '@MAC.radio_rx\t\treceived out of sequence ack',incoming_pkt[5],self.expected_arq_id #do something with incoming user data elif(incoming_protocol_id == USER_IO_PROTOCOL_ID): if not self.throw_away: data = incoming_pkt meta_dict = {} pdu_tuple = (data,meta_dict) self.output_user_data(pdu_tuple) self.throw_away = False else: print >> sys.stderr, '@MAC.radio_rx\t\tunknown protocol'
def rx_from_mac(self, msg): meta = pmt.car(msg) meta_dict = pmt.to_python(meta) print >> sys.stderr, 'seq no. =', meta_dict['seq_nr'] data = pmt.cdr(msg) print >> sys.stderr, 'received data:\n', pmt.u8vector_elements(data) print >> sys.stderr, '\n' self.message_port_pub(pmt.intern('to_tap'), pmt.cons(pmt.PMT_NIL, data))
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);
def handler(self, pdu): # grab float vector from pdu meta = pmt.car(pdu); x = pmt.to_python(pmt.cdr(pdu)) # convert to uint8 vector of mapped bits bindata = numpy.array(map(lambda x: x > 0, x), dtype='uint8') # send it on its way self.message_port_pub(pmt.intern("pdus"), pmt.cons(meta, pmt.to_pmt(bindata)))
def handler(self, msg): meta = pmt.car(msg); data_in = pmt.cdr(msg); data = array.array('B', pmt.u8vector_elements(data_in)) #data = array.array('B', pmt.u8vector_elements(data_in)) pre_data = self.preamble + data; # print pre_data[:100]; #burst_bits = pmt.to_pmt(pre_data); burst_bits = pmt.init_u8vector(len(pre_data), pre_data.tolist()); pdu = pmt.cons(meta, burst_bits); self.message_port_pub(pmt.intern("pdus"), pdu);
def handler(self, pdu): data = pmt.to_python(pmt.cdr(pdu)) meta = pmt.car(pdu) data = data - numpy.mean(data) # remove DC mag_sq = numpy.mean(numpy.real(data*numpy.conj(data))) #compute average Mag Sq p = self.k + 10*numpy.log10(mag_sq) # print "Power: %f"%(p) meta = pmt.dict_add(meta, pmt.intern("power"), pmt.from_float( p ) ) # done pass vector element for now ... self.message_port_pub( pmt.intern("cpdus"), pmt.cons( meta, pmt.PMT_NIL ) );
def handler(self, msg): # get input meta = pmt.car(msg); samples = pmt.cdr(msg); # ensure we have a dictionary assert(pmt.is_dict(meta)) #print pmt.to_python(pmt.dict_keys(meta)); # get the value from dict and publish it val = pmt.dict_ref(meta, self.key, pmt.PMT_NIL) self.message_port_pub(self.outport, val);
def handler(self, 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);
def tx_handler(self, msg): self.tx_cnt = self.tx_cnt + 1; if(len(self.retrans) > 1000): print "WARNING!!!!!!!!! DISCARDING PACKET BECAUSE RE-TX QUEUE IS TOO LONG!" return meta = pmt.car(msg); data_in = array.array('B', pmt.u8vector_elements(pmt.cdr(msg))) now = time.time(); self.retrans[self.pkt_idx] = {"time_orig":now, "time_last":now, "attempts":0, "pdu":(meta,data_in)}; self.send_data(self.pkt_idx,(meta,data_in)); self.pkt_idx = self.pkt_idx + 1;
def handle_message(self, msg_pmt): meta = pmt.to_python(pmt.car(msg_pmt)) msg = pmt.cdr(msg_pmt) if not pmt.is_u8vector(msg): print "ERROR wrong pmt format" return msg_str = "".join([chr(x) for x in pmt.u8vector_elements(msg)]) packet = digital.packet_utils.dewhiten(msg_str, 0) (ok, packet) = digital.crc.check_crc32(packet) if not ok: print '#######################################################' print '################## ERROR: Bad CRC #####################' print '#######################################################' return if ok: #print 'CRC check OK' frag_byte = ord(packet[0]) frag_index = frag_byte >> 2 #print 'Fragmentation byte: ', frag_byte if frag_byte & 0x01 == 1 : #print "got packet fragment. Index = %d. Last index = %d" % (frag_index, self.last_frag_index) self.last_frag_index = frag_index if frag_byte & 0x02 == 0 : self.wait_for_frag = True #strip fragmentation control and append payload self.packet_buffer += packet[1:] return else: #last part of fragmented packet #print 'got last fragment of packet. Index = ', frag_index self.wait_for_frag = False self.packet_buffer += packet[1:] packet = self.packet_buffer self.packet_buffer = '' else: #packet is not fragmented at all. #just strip off frag byte and hand it off packet = packet[1:] self.wait_for_frag = False if not self.wait_for_frag: # Create an empty PMT (contains only spaces): send_pmt = pmt.make_u8vector(len(packet), ord(' ')) # Copy all characters to the u8vector: for i in range(len(packet)): pmt.u8vector_set(send_pmt, i, ord(packet[i])) # Send the message: self.message_port_pub(pmt.intern('out'), pmt.cons(pmt.PMT_NIL, send_pmt))
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_input(self, pdu): #self.setSortingEnabled(False) # we expect a pdu if not pmt.is_pair(pdu): print("Message is not a PDU") return meta = pmt.car(pdu) if not pmt.is_dict(meta): print("No meta field present") return meta_dict = pmt.to_python(meta) if(not type(meta_dict) == type({})): return # for now, we insist on having the row_id pmt within the meta field if meta_dict.has_key(self.row_id): # get the current row identifier id_value = meta_dict[self.row_id] cur_idx = self.rowcount create_new_row = id_value not in self.ids.keys() if create_new_row: #print("Creating new Table Entry with "+str(id_value)) tab_item = QtGui.QTableWidgetItem(str(id_value)) tab_item.setData(QtCore.Qt.EditRole, id_value) tab_item.setBackground(QtGui.QColor(225,225,225)) self.setRowCount(self.rowcount + 1) self.setItem(self.rowcount, 0, tab_item) self.ids[id_value] = tab_item else: #print("Updating Table Entry " + str(id_value)) # if row id already exists, get and use the respective row idx cur_idx = self.ids[id_value].row() for col, idx in self.column_dict.iteritems(): if meta_dict.has_key(col) and col is not self.row_id: value = meta_dict[col] # for now, we wont allow meta field entrys other than the specified columns tab_item = QtGui.QTableWidgetItem(str(value)) tab_item.setData(QtCore.Qt.EditRole, value) self.setItem(cur_idx, idx, tab_item) if create_new_row: self.rowcount += 1 self.setRowCount(self.rowcount) if self.scroll_to_bottom: self.updateTrigger.emit() else: print("Meta Field "+self.row_id+" not found.")
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 background_thread(): # Establish ZMQ context and socket context = zmq.Context() socket = context.socket(zmq.SUB) socket.setsockopt(zmq.SUBSCRIBE, "") socket.connect("tcp://0.0.0.0:%d" % (ZMQ_PORT)) while True: # Receive decoded ADS-B message from the decoder over ZMQ pdu_bin = socket.recv() pdu = pmt.deserialize_str(pdu_bin) plane = pmt.to_python(pmt.car(pdu)) socketio.emit("updatePlane", plane) time.sleep(0.010)
def track(self, msg): data = pmt.cdr(msg) meta = pmt.car(msg) if not pmt.is_u8vector(data): #raise NameError("Data is no u8 vector") return "Message data is not u8vector" buf = pmt.u8vector_elements(data) meta_dict = pmt.to_python(meta) if not (type(meta_dict) is dict): meta_dict = {} if not 'EM_SRC_ID' in meta_dict: if self.verbose: print "[%s<%s>] Packet without source channel ID" % (self.name(), self.unique_id()) return src_id = meta_dict['EM_SRC_ID'] if len(buf) < 18: if self.verbose: print "[%s<%s>] Packet is less than Ethernet minimum" % (self.name(), self.unique_id()) return mac_dest = buf[0:6] mac_src = buf[6:12] mac_dest_str = ":".join(map(lambda x: ("%02X"%(x)), mac_dest)) mac_src_str = ":".join(map(lambda x: ("%02X"%(x)), mac_src)) #if self.verbose: # print "[%s<%s>] (%02d) %s -> %s" % (self.name(), self.unique_id(), src_id, mac_src_str, mac_dest_str) with self.lock: if mac_src_str in self.mac_to_chan_map and self.mac_to_chan_map[mac_src_str] != src_id: # Same MAC from different source ID if self.verbose: print "[%s<%s>] Same MAC %s from different source ID %d (current mapping: %d)" % (self.name(), self.unique_id(), mac_src_str, src_id, self.mac_to_chan_map[mac_src_str]) elif not mac_src_str in self.mac_to_chan_map: print "[%s<%s>] %s -> %02d" % (self.name(), self.unique_id(), mac_src_str, src_id) #if src_id in self.chan_to_mac_map and self.chan_to_mac_map[src_id] != mac_src_str: # # Already have a MAC from a source ID, but now seeing a different MAC # pass #self.chan_to_mac_map[src_id] = mac_src_str self.mac_to_chan_map[mac_src_str] = src_id