Exemplo n.º 1
0
 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))
Exemplo n.º 2
0
    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)]
Exemplo n.º 3
0
    def handle_pdu(self, pdu):
        if not pmt.is_pair(pdu):
            return

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

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

        try:
            output = self.format_output(meta, bits)
            if self.stdout:
                print output
            if self.fp:
                self.fp.write(output)
                self.fp.write('\n')
                if self.flush:
                    self.fp.flush()
        except IndexError as e:
            print >> sys.stderr, "gr-reveng: IndexError: Ran out of bits?"
            print >> sys.stderr, traceback.format_exc(e)
        except ValueError as e:
            print >> sys.stderr, "gr-reveng: TypeError: Something casted wrong!"
            print >> sys.stderr, traceback.format_exc(e)
        except IOError as e:
            print >> sys.stderr, "gr-reveng: IOError: Unable to write to file, closing"
            try:
                self.fp.close()
            except (OSError, IOError):
                pass
            self.fp = None
        except StandardError as e:
            print >> sys.stderr, "gr-reveng: %s: Something went horribly wrong!" % type(e)
            print >> sys.stderr, traceback.format_exc(e)
Exemplo n.º 4
0
    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))
Exemplo n.º 5
0
    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))
Exemplo n.º 6
0
    def _handleInput(self, msg):
        # Check message type.
        if not pmt.is_pair(msg):
            line = "Invalid input data type detected, must be a pair (car=pmt.NIL, cdr=pmt.init_u8vector([...]))."
            logger.error(line)
            print(line)
            return

        # Unpack data bytes.
        value = pmt.cdr(msg)
        if not pmt.is_u8vector(value):
            line = "Invalid value type, must be a u8vector (cdr=%s)." % str(value)
            logger.error(line)
            print(line)
            return
        octets = pmt.to_python(value)

        line = "Input: {}".format(",".join(["0x{:02x}".format(bi) for bi in octets]))
        logger.debug(line)

        # Encode
        bitSeq = octetsToBits(octets)

        # Forward message.
        self.message_port_pub(pmt.intern("pkt"), msg)
Exemplo n.º 7
0
    def handler(self, msg):
        # is pair() will pass both dictionaries and pairs
        if not pmt.is_pair(msg):
            return

        try:
            # will fail if msg is not a dictionary or pdu
            fpmt = pmt.dict_ref(msg, self.filename_tag, pmt.PMT_NIL)
        except:
            return

        if pmt.equal(fpmt, pmt.PMT_NIL):
            return
        fname = pmt.symbol_to_string(fpmt)
        print "received file {}".format(fname)

        with self.mutex:
            self.file_queue.append(fname)

            if self.copy:
                self.copy_queue.append(fname)

            if len(self.file_queue) > self.nfiles_max:
                oldest = self.file_queue.popleft()
                self.delete(oldest)
Exemplo n.º 8
0
    def deframe_APDU(self, msg_pmt):
        if pmt.is_blob(msg_pmt):
            blob = msg_pmt
            # print "is blob"
        elif pmt.is_pair(msg_pmt):
            blob = pmt.cdr(msg_pmt)
            # print "is pair"
        else:
            print "Formato desconocido"
            return
        data_np = pmt.to_python(blob)  # numpy.ndarray
        data_py = data_np.tolist()  # python list
        # print "Paquete",data_py,data_py.__class__
        if data_py[2:4] == [0xFF, 0xFF]:
            index = 16
        else:
            index = 24
        del data_py[:index]  # FC(2),Dst_Add(2),Src_Add(2),Radio(1),Sec_N(1),X->Dst_IEEE(8), Src_IEEE(8)
        # print "DEPACKED-->",data_py

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

            # Send the message:
        self.message_port_pub(pmt.intern("out"), pmt.cons(pmt.PMT_NIL, send_pmt))
Exemplo n.º 9
0
    def deframe_APDU(self, msg_pmt):
        if pmt.is_blob(msg_pmt):
            blob = msg_pmt
            #print "is blob"
        elif pmt.is_pair(msg_pmt):
            blob = pmt.cdr(msg_pmt)
            #print "is pair"
        else:
            print "Formato desconocido"
            return
        data_np = pmt.to_python(blob)  #numpy.ndarray
        data_py = data_np.tolist()  #python list
        #print "Paquete",data_py,data_py.__class__
        if data_py[2:4] == [0xFF, 0xFF]:
            index = 16
        else:
            index = 24
        del data_py[:
                    index]  # FC(2),Dst_Add(2),Src_Add(2),Radio(1),Sec_N(1),X->Dst_IEEE(8), Src_IEEE(8)
        #print "DEPACKED-->",data_py

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

        # Send the message:
        self.message_port_pub(pmt.intern('out'),
                              pmt.cons(pmt.PMT_NIL, send_pmt))
Exemplo n.º 10
0
    def handle_pdu(self, pdu):
        if not pmt.is_pair(pdu):
            return

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

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

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

        try:
            if ch_num == 'ch4' and pkt.type in [0x10, 0x11]:
                self.channels.get('ch%d' % pkt.next_chan).nom_packet(ts, pkt)
            else:
                self.channels.get(ch_num).nom_packet(ts, pkt)
        except StandardError as e:
            print >> sys.stderr, 'Failed calling nom_packet'
            print >> sys.stderr, 'Bad packet:', bytez.encode('hex')
            print >> sys.stderr, traceback.format_exc(e)
Exemplo n.º 11
0
    def _modemInputHandler(self, msg):
        # Parse raw packet.
        if not pmt.is_pair(msg):
            logger.error("KISS_TNC: Invalid input message.")
            return

        value = pmt.cdr(msg)
        if not pmt.is_u8vector(value):
            logger.error("KISS_TNC: Invalid message type.")
            return

        # Get bytes.
        data = bytearray(pmt.to_python(value))
        frame = {
            "ctrl": KISS_Utils.KISS_CTRL_DATA,
            "port": self.portNum,
            "param": 0,
            "data": data
        }
        packet = KISS_pack(frame)

        # Send TNC response.
        self.message_port_pub(
            pmt.intern("tnc_resp"),
            pmt.cons(pmt.PMT_NIL, pmt.init_u8vector(len(packet), packet)))
Exemplo n.º 12
0
    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))
Exemplo n.º 13
0
    def StdDev(self, msg_pmt):
        # veficcación del formato PMT
        if pmt.is_blob(msg_pmt):
            blob = msg_pmt
            #print "is blob"
        elif pmt.is_pair(msg_pmt):
            blob = pmt.cdr(msg_pmt)

        else:
            print "Formato desconocido"
            return

        vec = pmt.cdr(
            msg_pmt)  #se toma del diccionario en formato pmt la llave
        #print "sin convertir",vec,vec.__class__
        vecp = pmt.to_python(vec)  #se convierte de pmt a vector en python
        self.d_Std = np.array(
            vecp)  # se crea una variable que se pueda mmanipular
        Std1 = np.std(
            self.d_Std
        )  # se calcula la desviación estandar del vector que llego
        #print (self.d_Std)
        #print (Std1)
        Std12 = float(Std1)
        #print (Std12)
        #Stdv = pmt.from_float(Std12) #se convierte a float el valor obtenido
        Stdv1 = pmt.make_f32vector(
            1, Std12
        )  # se crea un vector de tipo PMT para despues ser interpretado por el  bloque PDU to Tagged Stream; debe ser "1" en el primer argumento o no funciona.
        self.message_port_pub(pmt.intern("out"), pmt.cons(pmt.PMT_NIL, Stdv1))
Exemplo n.º 14
0
 def handle_msg(self, msg):
     if(pmt.is_pair(msg)):
          blob = pmt.cdr(msg)
          s = ""
          for i in pmt.u8vector_elements(blob):
              s += chr(i)
          print "encoder sent:" + s
          self.encode_string(s) #"\n\n\n"
Exemplo n.º 15
0
    def app_in(self, msg):  # Generate messages
        global d_msg_len, d_mac_id, d_seq_nr, d_msg

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

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

        d_msg = []

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

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

        self.message_port_pub(pmt.intern("pdu out"),
                              pmt.cons(pmt.PMT_NIL, generatedMacPayload))
        print
        print "**********************************"
        print
        if self.debug:
            print "Data Published to physical Layer: ", pmt.u8vector_elements(
                generatedMacPayload), "\n"
Exemplo n.º 16
0
 def _handle_pdu_message(self, message):
     if not pmt.is_pair(message):
         print('Invalid pdu: ', message)
     else:
         data = pmt.cdr(message)
         if self._is_binary(data):
             self._binary_printer(data)
         else:
             self._printer(data)
Exemplo n.º 17
0
  def pdu_in(self, msg): # consume messages
	global d_mac_id

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

		    macPayload = pmt.make_u8vector(data_len - 14, 0)
		    for i in range(data_len - 14):	
			    pmt.u8vector_set(macPayload, i, pmt.u8vector_elements(data)[i+10]) 	
		    self.message_port_pub(pmt.intern('app out'), pmt.cons(pmt.PMT_NIL, macPayload))
		    if self.debug: print "Data sent up to Application Layer : ", pmt.u8vector_elements(macPayload), "\n"	
Exemplo n.º 18
0
def is_u8_pdu(msg):
    """Checks if a PMT is a uint8 PDU"""
    if not pmt.is_pair(msg):
        return False

    if not pmt.is_dict(pmt.car(msg)):
        return False

    if not pmt.is_u8vector(pmt.cdr(msg)):
        return False

    return True
Exemplo n.º 19
0
 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 start
                     start = 0
                 if pmt.to_long(val) == 20:
                     global start
                     start = 1
Exemplo n.º 20
0
    def msg_handler(self, msg):
        if not pmt.is_pair(msg) or pmt.is_dict(msg) or pmt.is_pdu(msg):
            gr.log.warn("Input message %s is not a simple pair, dropping" %
                        repr(msg))
            return

        new_val = pmt.to_python(pmt.cdr(msg))
        try:
            self.callback(new_val)
        except Exception as e:
            gr.log.error("Error when calling " + repr(self.callback.name()) +
                         " with " + repr(new_val) + " (reason: %s)" % repr(e))
Exemplo n.º 21
0
    def deframe_NPDU(self, msg_pmt):
        global pack_err
        global pack_tot
        global PER
        # veficcación del formato 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_len = pmt.blob_length(blob)
        if (data_len < 11):
            print "MAC: muy corta!"
            pack_err = pack_err + 1.0
            return
        data_np = pmt.to_python(blob)  #numpy.ndarray
        data_py = data_np.tolist()  #python list
        #print "Paquete",data_py,data_py.__class__
        #print "Dir Gateway",self.SrcAddR," Dir Nodo",data_py[7:9]
        if len(set(self.SrcAddR).intersection(
                data_py)) < 2:  #Validación TX de la misma dirección

            # Valodacion FCS y cuenta PER
            rec_FCS = [data_py[-2], data_py[-1]]  #FCS recibido
            del data_py[-2], data_py[-1]  #quita FCS
            s_to_fcs = struct.pack('B' * len(data_py),
                                   *data_py)  # Convierte List a String
            a = self.crc16(s_to_fcs)  #Calcula FCS
            FCS = [a & 0xFF, (a >> 8) & 0xFF]

            if FCS == rec_FCS:  # paquete correcto
                index = 9
                del data_py[:
                            index]  # FC(2),Sec_N(1),PanID(2),Dst_Add(2),Src_Add(2)
                # 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))
            else:
                pack_err = pack_err + 1.0

            pack_tot = pack_tot + 1.0
            PER = pack_err / pack_tot * 100.0
            print ",", pack_tot, ",", pack_err, ",", PER, "%"
Exemplo n.º 22
0
    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)
Exemplo n.º 23
0
 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"
Exemplo n.º 24
0
    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 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")
Exemplo n.º 26
0
    def _tncInputHandler(self, msg):
        # Parse raw packet.
        if not pmt.is_pair(msg):
            logger.error("KISS_TNC: Invalid input message.")
            return

        value = pmt.cdr(msg)
        if not pmt.is_u8vector(value):
            logger.error("KISS_TNC: Invalid message type.")
            return

        # Get bytes.
        data = bytearray(pmt.to_python(value))
        # Unpack to frame.
        frames = KISS_unpack(data)
        if len(frames) == 0:
            logger.error("Failed to unpack KISS frames from data: %s" %
                         str(data))
            return

        # Filter out TNC commands to different port(s).
        filtered = []
        for frame in frames:
            port = frame.get("port", -1)
            if port != self.portNum:
                logger.debug("Filtering KISS packet (port %u != %u)." %
                             (port, self.portNum))
                continue
            filtered.append(frame)

        # Perform the desired operation.
        for frame in filtered:
            # Get control byte.
            ctrl = frame.get("ctrl", None)
            if ctrl == None:
                logger.error("No control byte found.")
                continue

            # Call correct handler.
            handler = self.handler.get(ctrl, self.printError)
            handler(frame)

            # Add data to transmit queue.
            octets = frame.get("data", [])
            if len(octets) > 0:
                logger.debug("Queueing packet (len=%u)." % len(octets))
                self.txQueue.put(octets)

        # Send data immediately if CSMA is disabled.
        if not self.csma:
            self.sendData()
Exemplo n.º 27
0
    def msg_handler(self, msg):
        if self.lock:
            return
            
        if not pmt.is_pair(msg):
            gr.log.warn("Incoming message is not a pair.  Only pairs are supported.  "
                        "No message generated.")
            return

        meta = pmt.to_python(pmt.car(msg))

        if not type(meta) is dict:
            gr.log.warn("Incoming message does not contain a dictionary.  "
                        "No message generated.")
            return

        if not 'corrective_lags' in meta:
            gr.log.warn("Incoming message dictionary does not contain key corrective_lags.  "
                        "No message generated.")
            return

        try:
            new_delay = int(meta['corrective_lags'][self.index_to_extract])
        except Exception as e:
            gr.log.error("Cannot extract lag info: %s" % str(e))
            return

        try:
            if meta['corrvect'][self.index_to_extract] < self.minCorrScore:
                return
        except Exception as e:
            gr.log.error("Cannot extract correlation info: %s" % str(e))
            return

        self.callback(new_delay)

        new_pair = None

        try:
            new_pair = pmt.cons(pmt.intern('delay'), pmt.to_pmt(new_delay))
        except Exception as e:
            gr.log.error("Cannot construct new message: %s" % str(e))
            return

        try:
            self.message_port_pub(pmt.intern("delay"), new_pair)
        except Exception as e:
            gr.log.error("Cannot send message: %s" % str(e))
            gr.log.error("Incoming dictionary (%s):" % str(type(meta)))
            gr.log.error(str(meta))
Exemplo n.º 28
0
    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.")
Exemplo n.º 29
0
    def handler(self, msg):
        # Check if msg is c32_vector
        if not pmt.is_pair(msg):
            print("Not expected c32 vector type")

        sizevec = pmt.u32vector_elements(pmt.car(msg))
        # print(sizevec)
        weights = pmt.c32vector_elements(pmt.cdr(msg))
        weights = numpy.reshape(weights, sizevec, order='C')
        # print(weights.shape)
        # print(weights)
        # print(weights.tolist())
        # print(weights[0])

        self.message_port_pub(pmt.intern("A"), pmt.to_pmt(weights.tolist()))
Exemplo n.º 30
0
	def deframe_NPDU(self,msg_pmt):
		global pack_err
		global pack_tot
		global PER
		# veficcación del formato 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_len = pmt.blob_length(blob)
		if(data_len < 11):
			print "MAC: muy corta!"
			pack_err = pack_err+1.0
			return;
		data_np	= pmt.to_python(blob) 	#numpy.ndarray	
		data_py = data_np.tolist()		#python list
		#print "Paquete",data_py,data_py.__class__
		#print "Dir Gateway",self.SrcAddR," Dir Nodo",data_py[7:9]
		if len(set(self.SrcAddR).intersection(data_py)) < 2 :		#Validación TX de la misma dirección
			
			# Valodacion FCS y cuenta PER
			rec_FCS = [data_py[-2],data_py[-1]] #FCS recibido
			del data_py[-2],data_py[-1]			#quita FCS
			s_to_fcs = struct.pack('B'*len(data_py), *data_py)  # Convierte List a String
			a = self.crc16(s_to_fcs)		#Calcula FCS
			FCS= [a & 0xFF,(a>>8)&0xFF] 

			if FCS == rec_FCS:		# paquete correcto
				index = 9
				del data_py[:index]				# FC(2),Sec_N(1),PanID(2),Dst_Add(2),Src_Add(2)
				# 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))
			else:
				pack_err = pack_err+1.0
		
			pack_tot = pack_tot +1.0
			PER =pack_err/pack_tot*100.0
			print ",",pack_tot,",",pack_err,",",PER,"%"
Exemplo n.º 31
0
    def insert_pdu_into_table(self, pdu):
        # Only process PDUs
        if pmt.is_pair(pdu):
            meta = pmt.to_python(pmt.car(pdu))
            if meta is None:
                meta = dict()

            # Create table if we haven"t already
            if not self.created_table:
                # Find the non fixed-position columns and sort alphabetically
                non_fixed_position_columns = meta.keys()
                for key in self.fixed_position_columns:
                    try:
                        non_fixed_position_columns.remove(key)
                    except:
                        continue

                ordered_keys = self.fixed_position_columns + sorted(non_fixed_position_columns)
                if self.vector_column_name not in ordered_keys:
                    # Add the vector column at the end unless otherwise specified in the Fixed-Position Columns list
                    cols = "(" + ", ".join(ordered_keys) + ", " + self.vector_column_name + ")"
                else:
                    cols = "(" + ", ".join(ordered_keys) + ")"

                # Attempt to create the table
                self.c.execute("CREATE TABLE IF NOT EXISTS " + self.table_name + " " + cols)
                self.conn.commit()
                self.created_table = True

                # Get list of true column names (whether we just made the table or it already existed)
                self.c.execute("SELECT * FROM " + self.table_name)
                self.column_names = [description[0] for description in self.c.description]

            # Set the PDU vector into the meta dictionary with appropriate key
            # meta[self.vector_column_name] = buffer(pmt.to_python(pmt.cdr(pdu)))
            meta[self.vector_column_name] = buffer(pmt.serialize_str(pmt.cdr(pdu)))

            # Insert PDU into table, with only columns that already exist in the table
            valid_keys = [key for key in meta.keys() if key in self.column_names]
            cols = "(" + ", ".join(valid_keys) + ")"
            question_marks = "(" + ", ".join(["?"]*len(valid_keys)) + ")"
            vals = [meta[key] for key in valid_keys]

            self.c.execute("INSERT INTO " + self.table_name + " " + cols + " VALUES " + question_marks, vals)
            self.conn.commit()
Exemplo n.º 32
0
    def test_fr(self):
        """
            Simple TCH/F Full Rate test
        """
        framenumbers_input = [
            373420, 373421, 373422, 373423, 373424, 373425, 373426, 373427,
            3734298
        ]
        timeslots_input = [3, 3, 3, 3, 3, 3, 3, 3]
        bursts_input = [
            "0000101011011010011110011011101011100000100010001011010100110111011110001001011101111000111010001001000110000011100010000010111110110101001101011000",
            "0001011011111010000000111010110001110101010011011100000110100111011110001001011101111000110100000010000001100010101101011010000110000101101011000000",
            "0000011010010000100000000100110111111110101101011001001010010111011110001001011101111000010001010001101000010100100111101110110010011110010000011000",
            "0001000000010111010111100100110110000101101111000000011011100111011110001001011101111000101001000001101010010110011100011010010011010001010010001000",
            "0000111001001110100011110000101001110110111011001110110110110111011110001001011101111000011110001000010101011000101010010101000000100000010011101000",
            "0000011001001010010101100000110100101001111001001100101010000111011110001001011101111000100111000000111111000000100001101001101010000110111111100000",
            "0001011011101100100001010001001000110010010010100101000111010111011110001001011101111000100001101110100101000100100100100100000100011101111001011000",
            "0000010111000101101101100001011000110010010011001110101000010111011110001001011101111000001001100011010001111110001101010100110001010001100100001000"
        ]

        src = grgsm.burst_source(framenumbers_input, timeslots_input,
                                 bursts_input)
        decoder = grgsm.tch_f_decoder(grgsm.TCH_FS, False)
        dst = blocks.message_debug()

        self.tb.msg_connect(src, "out", decoder, "bursts")
        self.tb.msg_connect(decoder, "voice", dst, "store")

        self.tb.run()

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

        pdu = dst.get_message(0)
        self.assertEqual(True, pmt.is_pair(pdu))

        data = pmt.cdr(pdu)
        self.assertEqual(True, pmt.is_blob(data))

        np.testing.assert_array_equal(
            np.array([
                211, 92, 197, 118, 171, 142, 160, 70, 219, 146, 71, 20, 226,
                128, 73, 35, 142, 75, 35, 94, 32, 73, 28, 114, 73, 44, 132,
                192, 72, 228, 141, 201, 27
            ]), pmt.to_python(data))
Exemplo n.º 33
0
    def _msgHandler(self, msg):
        if not pmt.is_pair(msg):
            logger.error("Invalid input message (expected PMT pair).")
            return

        # Convert to Python format.
        data = pmt.cdr(msg)
        try:
            item = pmt.to_python(data)
            if not isinstance(item, str):
                item = item.tostring()
        except Exception as e:
            logger.error("Failed to convert PMT to Python: %s." % str(e))
            return

        # Write item to log.
        self.logBook.debug(item)

        # Send to update slot.
        self.emit(QtCore.SIGNAL("updateText(QString)"), item)
Exemplo n.º 34
0
    def tchh_multirate(self, frames, timeslots, bursts, multirate, subchan):
        """
            Common TCH/H MultiRate test code
        """
        src = grgsm.burst_source(frames, timeslots, bursts)
        decoder = grgsm.tch_h_decoder(subchan, multirate, False)
        dst = blocks.message_debug()

        self.tb.msg_connect(src, "out", decoder, "bursts")
        self.tb.msg_connect(decoder, "voice", dst, "store")

        self.tb.run()

        result = []
        for i in range(0, dst.num_messages()):
            pdu = dst.get_message(i)
            self.assertEqual(True, pmt.is_pair(pdu))
            data = pmt.cdr(pdu)
            self.assertEqual(True, pmt.is_blob(data))
            result.append(pmt.to_python(data).tolist())
        return result
Exemplo n.º 35
0
    def test_pair(self):
        cs = starcoder.command_source()
        snk = blocks.message_debug()
        self.tb.msg_connect((cs, 'out'), (snk, 'store'))

        msg = starcoder_pb2.BlockMessage()
        msg.pair_value.car.symbol_value = "testtransmission"
        msg.pair_value.cdr.double_value = 23.2

        expected = pmt.cons(pmt.intern("testtransmission"),
                            pmt.from_double(23.2))

        self.tb.start()
        cs.push(msg.SerializeToString())
        time.sleep(0.1)
        self.tb.stop()
        self.tb.wait()

        self.assertEqual(snk.num_messages(), 1)
        self.assertTrue(pmt.is_pair(snk.get_message(0)))
        self.assertTrue(pmt.equal(snk.get_message(0), expected))
Exemplo n.º 36
0
    def handle_input(self, pdu):
        # 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 isinstance(meta_dict, dict):
            return

        self.setRowCount(self.rowcount + 1)
        # get the current row identifier
        for col, idx in self.column_dict.items():
            if col == self.body_label:
                msg_pmt = pmt.cdr(pdu)
                msg_bytes = bytes(pmt.u8vector_elements(msg_pmt))
                value = msg_bytes.decode("utf8", errors="replace")
                display = str(value)
            elif col in ("freq", "frequency"):
                value = meta_dict.get(col)
                display = eng_notation.num_to_str(value) + "Hz"
            elif col == "rx_time":
                value = meta_dict.get(col)[0]
                display = str(datetime.fromtimestamp(value))
            else:
                value = meta_dict.get(col)
                display = str(value)

            tab_item = QtWidgets.QTableWidgetItem(display)
            self.setItem(self.rowcount, idx, tab_item)

        self.rowcount += 1
        if self.scroll_to_bottom:
            self.updateTrigger.emit()
Exemplo n.º 37
0
 def handle_pdu(self, pdu):
     # PMT TYPE CHECK AND UNPACKING
     if pmt.is_pair(pdu):
         msg = pdu_to_str(pdu)
         self.top_block.on_pkt_rcv()