Example #1
0
    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 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))

        if len(packet) != 64:
            print('Error: signalling packet length != 64')
            return

        prbs = np.frombuffer(packet[:-6], dtype = 'uint8')
        ber_prbs = np.sum((np.unpackbits(prbs) ^ np.unpackbits(signalling_prbs[6:])).astype('int')) / (prbs.size * 8)

        flags = np.unpackbits(np.frombuffer(packet[-6:], dtype = 'uint8')).reshape((-1, 8))
        decoded_flags = 1*(np.sum(flags, axis = 1) > 4)

        try:
            downlink_speed = downlink_speeds[np.packbits(decoded_flags[:3])[0] >> 5]
        except IndexError:
            print(f'Error: invalid downlink speed {decoded_flags[:3]}')
            return

        try:
            coding = codings[np.packbits(decoded_flags[3:])[0] >> 5]
        except IndexError:
            print(f'Error: invalid coding {decoded_flags[3:]}')
            return

        print(f'Signalling packet: BER {ber_prbs:.4f}, rate {downlink_speed} baud, coding {coding}')
Example #3
0
    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
Example #4
0
    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

        buff = list()
        buff.append(FEND)
        buff.append(numpy.uint8(0))
        for x in pmt.u8vector_elements(msg):
            if x == FESC:
                buff.append(FESC)
                buff.append(TFESC)
            elif x == FEND:
                buff.append(FESC)
                buff.append(TFEND)
            else:
                buff.append(numpy.uint8(x))
        buff.append(FEND)

        buff = array.array('B', buff)

        self.message_port_pub(
            pmt.intern('out'),
            pmt.cons(pmt.PMT_NIL, pmt.init_u8vector(len(buff), buff)))
Example #5
0
 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)
Example #6
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)
Example #7
0
 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)
Example #8
0
 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:
         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)
Example #9
0
    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
Example #10
0
    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))))
Example #11
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)
Example #12
0
    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

        if pmt.length(msg) + 2 > self.mtu:
            print "[ERROR] Transmitted frame is too long (%d bytes).  Cannot exceed %d bytes." % (pmt.length(msg), self.mtu - 2)
            return

        #length = struct.pack('h', pmt.length(msg))
        #print length, pmt.length(msg)

        buff = list()
        #buff.extend([x for x in length])
        #buff.extend(pmt.u8vector_elements(msg))
        length = pmt.length(msg)
        buff.append(length >> 8) # MSB
        buff.append(length & 0xFF) # LSB
        buff.extend(pmt.u8vector_elements(msg))

        pad_length = self.mtu - len(buff)
        if pad_length:
            buff.extend([self.pad_byte] * pad_length)

        if debug:
            print "Pushing a packet of length %d bytes" % length

        self.message_port_pub(pmt.intern('out'), pmt.cons(pmt.PMT_NIL, pmt.init_u8vector(len(buff), buff)))
Example #13
0
 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')
     # put initial padding to account for the AX.25 header we've lost
     initial_padding = np.zeros(17, dtype='uint8')
     packet = np.concatenate((initial_padding, packet))
     if packet.size != 40 * 9:
         print("[ERROR] Invalid packet size")
         return
     packet = packet.reshape((9, 40))
     # save AX.25 header. we take it from the 2nd message
     header = packet[1, 1:16]
     # drop AX.25 headers and final 0x7e
     packet = packet[:, 17:-1].ravel()
     # drop final padding
     packet = packet[:-11]
     # check CRC
     crc = crc16_ccitt_false(packet[4:-2])  # do not include first 4 bytes
     if crc != struct.unpack('<H', packet[-2:])[0]:
         if self.verbose:
             print('CRC failed')
             return
     elif self.verbose:
         print('CRC OK')
     # drop CRC
     packet = packet[:-2]
     # put AX.25 header back
     packet = np.concatenate((header, packet))
     packet = bytes(packet)  # remove conversion to bytes for GNU Radio 3.9
     self.message_port_pub(
         pmt.intern('out'),
         pmt.cons(pmt.PMT_NIL, pmt.init_u8vector(len(packet), packet)))
Example #14
0
    def app_rx(self,msg):
        try:            
            meta = pmt.car(msg)
            data =  pmt.cdr(msg)
        except:
            raise NameError("mac - input not a PDU")
            
        if pmt.is_u8vector(data):
            data = pmt.u8vector_elements(data)
        else:
            raise NameError("Data is not u8 vector")

        meta_dict = pmt.to_python(meta)
        if not (type(meta_dict) is dict):
            meta_dict = {}
        
        #double check to make sure correct meta data was in pdu
        if 'EM_USE_ARQ' in meta_dict.keys() and 'EM_DEST_ADDR' in meta_dict.keys():
            #assign tx path depending on whether PMT_BOOL EM_USE_ARQ is true or false
            if(meta_dict['EM_USE_ARQ']):
                self.queue.put( (data,meta_dict) )
            else:
                self.tx_no_arq(( data,meta_dict) ,USER_IO_PROTOCOL_ID)
        else:
            raise NameError("EM_USE_ARQ and/or EM_DEST_ADDR not specified in PDU")
Example #15
0
    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 = pmt.u8vector_elements(msg)

        if self.packet_len is not None:
            packet = packet[:self.packet_len]

        if (self.packet_len is not None and len(packet) < self.packet_len) \
          or (self.packet_len is None and len(packet) < 2):
            if self.verbose:
                print("Packet too short")
            return

        packet_out = packet[:-2]
        msg_out = pmt.cons(pmt.PMT_NIL,
                           pmt.init_u8vector(len(packet_out), packet_out))
        if crc16_arc(packet) == 0:
            if self.verbose:
                print("CRC OK")
            self.message_port_pub(pmt.intern('ok'), msg_out)
        else:
            if self.verbose:
                print("CRC failed")
            self.message_port_pub(pmt.intern('fail'), msg_out)
Example #16
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)
Example #17
0
    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 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)))
Example #19
0
    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 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))

        if len(packet) <= 4 + 8:
            return
        csp = CSP(packet[:4])

        packet_number = struct.unpack('<I', packet[-8:-4])[0]

        if csp.destination == 6:
            print('Packet number', packet_number, '(camera)')
            return

        # destination 5 is used for telemetry
        if csp.destination != 5:
            return

        data = by701_telemetry.beacon_parse(packet[4:])
        if data:
            print('Packet number', packet_number, '(telemetry)')
            print('--------------------------------------------')
            print(data)
            print()
        else:
            print('Could not parse beacon')
            print()
Example #21
0
 def radio_rx(self, msg):
     # message structure is a meta data-data?
     try:
         meta = pmt.car(msg)
         data = pmt.cdr(msg)
     except:
         if self.debug_stderr:
             # log the error
             sys.stderr.write("in radio_rx(): message is not a PDU\n")
         return
     # data is a vector of unsigned chars?
     if pmt.is_u8vector(data):
         data = pmt.u8vector_elements(data)
     else:
         if self.debug_stderr:
             # log the error
             sys.stderr.write("in radio_rx(): data is not a u8vector\n")
         return
     # convert meta data dictionary from PMT to Python type
     meta_dict = pmt.to_python(meta)
     if not (type(meta_dict) is dict):
         meta_dict = {}
     # Get exclusive access
     with self.lock:
         self._radio_rx(data, meta_dict)
Example #22
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)))
Example #23
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 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 = pmt.u8vector_elements(msg)
        self.data_length = len(packet)
        self.packet_sequence_count += 1
        count_or_name = self.packet_sequence_count if self.packet_type == 0 or self.count_or_name == 0 else self.packet_sequence_name

        finalHeader = array.array(
            'B',
            space_packet.PrimaryHeader.build(
                dict(ccsds_version=self.ccsds_version,
                     packet_type=self.packet_type,
                     secondary_header_flag=self.secondary_header_flag,
                     AP_ID=self.AP_ID,
                     sequence_flags=self.sequence_flags,
                     packet_sequence_count_or_name=count_or_name,
                     data_length=self.data_length))).tolist()

        finalPacket = numpy.append(finalHeader, packet)
        finalPacket = array.array('B', finalPacket[:])
        finalPacket = pmt.cons(
            pmt.PMT_NIL, pmt.init_u8vector(len(finalPacket), finalPacket))
        self.message_port_pub(pmt.intern('out'), finalPacket)
Example #25
0
    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)))
Example #26
0
    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))
        '''
Example #27
0
    def app_rx(self, msg):
        try:
            meta = pmt.car(msg)
            data = pmt.cdr(msg)
        except:
            raise NameError("mac - input not a PDU")

        if pmt.is_u8vector(data):
            data = pmt.u8vector_elements(data)
        else:
            raise NameError("Data is not u8 vector")

        meta_dict = pmt.to_python(meta)
        if not (type(meta_dict) is dict):
            meta_dict = {}

        #double check to make sure correct meta data was in pdu
        if 'EM_USE_ARQ' in meta_dict.keys(
        ) and 'EM_DEST_ADDR' in meta_dict.keys():
            #assign tx path depending on whether PMT_BOOL EM_USE_ARQ is true or false
            if (meta_dict['EM_USE_ARQ']):
                self.queue.put((data, meta_dict))
            else:
                self.tx_no_arq((data, meta_dict), USER_IO_PROTOCOL_ID)
        else:
            raise NameError(
                "EM_USE_ARQ and/or EM_DEST_ADDR not specified in PDU")
    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 = pmt.u8vector_elements(msg)

        finalHeader = array.array(
            'B',
            telemetry.OCFTrailer.build(
                dict(control_word_type=self.control_word_type,
                     clcw_version_number=self.clcw_version_number,
                     status_field=self.status_field,
                     cop_in_effect=self.cop_in_effect,
                     virtual_channel_identification=self.
                     virtual_channel_identification,
                     rsvd_spare1=self.rsvd_spare1,
                     no_rf_avail=self.no_rf_avail,
                     no_bit_lock=self.no_bit_lock,
                     lockout=self.lockout,
                     wait=self.wait,
                     retransmit=self.retransmit,
                     farmb_counter=self.farmb_counter,
                     rsvd_spare2=self.rsvd_spare2,
                     report_value=self.report_value))).tolist()

        finalPacket = numpy.append(packet, finalHeader)
        finalPacket = array.array('B', finalPacket[:])
        finalPacket = pmt.cons(
            pmt.PMT_NIL, pmt.init_u8vector(len(finalPacket), finalPacket))
        self.message_port_pub(pmt.intern('out'), finalPacket)
    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))

        if len(packet) <= 4 + 8:
            return
        csp = CSP(packet[:4])

        # destination 5 is used for telemetry
        if csp.destination != 5:
            return

        data = by701_telemetry.beacon_parse(packet[4:])

        if not data or 'latitude' not in data:
            return

        line = array.array(
            'B', '{},{},{}\n'.format(data.longitude, data.latitude,
                                     data.altitude))

        self.message_port_pub(pmt.intern('out'), pmt.cons(pmt.PMT_NIL,\
                            pmt.init_u8vector(len(line), line)))
    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))
        size = len(packet) - 6
        try:
            header = telemetry.PrimaryHeader.parse(packet[:])
            if header.ocf_flag == 1:
                size -= 4
        except:
            print("Could not decode telemetry packet")
            return

        parsed = telemetry.FullPacket.parse(packet[:], size=size)

        payload = parsed.payload
        #The number 6 is used here, because that's the length of the Primary Header.
        #todo: Add a variable for this
        while len(payload) != 0:
            if len(self.space_packet) < 6:
                left = 6 - len(self.space_packet)
                self.space_packet.extend(payload[:left])
                payload = payload[left:]
            if len(self.space_packet) >= 6:
                self.length_of_space_packet = space_packet.PrimaryHeader.parse(
                    bytearray(self.space_packet)).data_length
                left = self.length_of_space_packet + 6 - len(self.space_packet)
                self.space_packet.extend(payload[:left])
                payload = payload[left:]
                if 6 + self.length_of_space_packet == len(self.space_packet):
                    self.sendPacket()
Example #31
0
    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))

        # check packet length
        # an AX.25 header with 2 addresses, control and PID is 16 bytes
        if len(packet) < 16:
            self.message_port_pub(pmt.intern('fail'), msg_pmt)
            return

        if self.direction == 'to':
            address = packet[:7]
        else:
            address = packet[7:14]

        callsign = bytes([c >> 1 for c in address[:6]]).decode('ascii').rstrip(' ')
        ssid = (address[6] >> 1) & 0x0f

        if callsign != self.callsign or (self.ssid != None and ssid != self.ssid):
            # incorrect address
            self.message_port_pub(pmt.intern('fail'), msg_pmt)
        else:
            # correct address
            self.message_port_pub(pmt.intern('ok'), msg_pmt)
Example #32
0
    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 = list(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)

        self.message_port_pub(
            pmt.intern('out'),
            pmt.cons(pmt.PMT_NIL, pmt.init_u8vector(len(buff), buff)))
Example #33
0
    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))
        beacon = tlm.parse(packet)
        
        # check that message is beacon
        if beacon.csp_header.destination != 10 or beacon.csp_header.destination_port != 30:
            return

        if beacon.csp_header.source != 1 or beacon.beacon_type != 0:
            return

        adsb = beacon.beacon.adsb

        
        print("""<Placemark>
        <name>{}</name>
        <description>Altitude: {}ft Time: {}</description>
        <styleUrl>#plane</styleUrl>
        <Point><coordinates>{},{}</coordinates></Point>
</Placemark>""".format(hex(adsb.last_icao), adsb.last_alt,
                        adsb.last_time,
                        adsb.last_lon if adsb.last_lon <= 180 else adsb.last_lon - 360,
                        adsb.last_lat))
Example #34
0
    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))

        # check packet length
        # an AX.25 header with 2 addresses, control and PID is 16 bytes
        if len(packet) < 16:
            self.message_port_pub(pmt.intern('fail'), msg_pmt)
            return

        if self.direction == 'to':
            address = packet[:7]
        else:
            address = packet[7:14]

        callsign = array.array('B', map(lambda c: c >> 1,
                                        address[:6])).tostring().rstrip(' ')
        ssid = int((address[6] >> 1) & 0x0f)

        if callsign != self.callsign or (self.ssid != None
                                         and ssid != self.ssid):
            # incorrect address
            self.message_port_pub(pmt.intern('fail'), msg_pmt)
        else:
            # correct address
            self.message_port_pub(pmt.intern('ok'), 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 = pmt.u8vector_elements(msg)

        next_pointer = 0

        while len(packet) > 0:
            limit = self.size - len(self.list)
            if len(packet) > limit:
                if len(packet) >= limit + self.size:
                    next_pointer = 0x3ff
                else:
                    next_pointer = len(packet) - limit
            elif len(packet) == limit:
                next_pointer = 0

            self.list.extend(packet[:limit])
            packet = packet[limit:]

            if len(self.list) == self.size:
                finalPacket = numpy.append(self.calculateFinalHeader(), self.list)
                self.sendPacket(finalPacket)
                self.list = []
                self.first_header_pointer = next_pointer
Example #36
0
    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)
Example #37
0
    def handle_msg(self, msg_pmt):
        # check that callsign and QTH have been entered
        if self.request['source'] == '':
            return
        if self.request['longitude'] == 0.0 and self.request['latitude'] == 0.0:
            return

        msg = pmt.cdr(msg_pmt)
        if not pmt.is_u8vector(msg):
            print("[ERROR] Received invalid message type. Expected u8vector")
            return

        self.request['frame'] = bytes(pmt.u8vector_elements(msg)).hex().upper()

        now = datetime.datetime.utcnow()
        timestamp = now - self.startTimestamp + self.initialTimestamp \
          if self.initialTimestamp else now
        self.request['timestamp'] = timestamp.isoformat()[:-3] + 'Z'

        params = bytes(urllib.parse.urlencode(self.request), encoding='ascii')
        f = urllib.request.urlopen('{}?{}'.format(self.url, params),
                                   data=params)
        reply = f.read()
        code = f.getcode()
        if code < 200 or code >= 300:
            print("Server error while submitting telemetry")
            print("Reply:")
            print(reply)
            print("URL:", f.geturl())
            print("HTTP code:", f.getcode())
            print("Info:")
            print(f.info())
        f.close()
Example #38
0
    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'
Example #39
0
 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:
         print(csp_header.CSP(packet[:4]))
     except ValueError as e:
         print e
Example #40
0
 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 = packet[:4]
     header.reverse()
     packet = header + packet[4:]
     msg_pmt = pmt.cons(pmt.PMT_NIL, pmt.init_u8vector(len(packet), bytearray(packet)))
     self.message_port_pub(pmt.intern('out'), 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 = str(bytearray(pmt.u8vector_elements(msg)))

        try:
            print(str(beacon.Beacon(packet[4:])))
        except ValueError as e:
            print e
Example #42
0
  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))
Example #43
0
 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
 def demux(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)
     if len(buf) <= 1:
         return
     
     meta_dict = pmt.to_python(meta)
     if not (type(meta_dict) is dict):
         meta_dict = {}
     
     self._demux(buf, meta_dict)
Example #45
0
  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)])

    num_mtus = (len(msg_str) // self.max_mtu_size)
    if len(msg_str) % self.max_mtu_size != 0:
      num_mtus = num_mtus + 1
      
    #Fragment packet?
    
    mtu_index_start = 0
    mtu_index_end = 0
    last = False
    frag = False
    frag_index = 0
    
    if num_mtus > 1:
      frag = True;
      
    for i in range(num_mtus):
      
      if (len(msg_str) - mtu_index_start) > self.max_mtu_size:
        mtu_index_end = mtu_index_start + self.max_mtu_size
      else:
        mtu_index_end = len(msg_str)
        last = True

      fragment_str = msg_str[mtu_index_start:mtu_index_end]
     
      packet = self.build_packet(fragment_str, frag, last, i)
      
      mtu_index_start += self.max_mtu_size

      # 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))
Example #46
0
    def fragment_packet(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)])
        print '[stop_and_wait] :: App message: Len: '+ str(len(msg_str))

        num_mtus = (len(msg_str) // self.max_mtu_size)
        if len(msg_str) % self.max_mtu_size != 0:
          num_mtus = num_mtus + 1

        mtu_index_start = 0
        mtu_index_end = 0
        last = False
        frag = False
        frag_index = 0

        packet_list = []

        if num_mtus > 1:
          frag = True;

        for i in range(num_mtus):

          if (len(msg_str) - mtu_index_start) > self.max_mtu_size:
            mtu_index_end = mtu_index_start + self.max_mtu_size
          else:
            mtu_index_end = len(msg_str)
            last = True

          fragment_str = msg_str[mtu_index_start:mtu_index_end]

          packet = self.add_frag_hdr(fragment_str, frag, last, i)

          mtu_index_start += self.max_mtu_size

          # Send the message:
          packet_list.append(packet)

        print '[stop_and_wait] :: #Fragments: '+ str(len(packet_list))

        return packet_list
	def handle_string_msg(self, msg_pmt):
		""" Receiver a u8vector on the input port, and print it out. """
		# Collect metadata, convert to Python format:
		meta = pmt.to_python(pmt.car(msg_pmt))
		# Collect message, convert to Python format:
		msg = pmt.cdr(msg_pmt)
		# 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)])
		# Just for good measure, and to avoid attacks, let's filter again:
		msg_str = filter(lambda x: x in string.printable, msg_str)
		# Print string, and if available, the metadata:
		print msg_str
		if meta is not None:
			print "[METADATA]: ", meta
Example #48
0
    def handle_binary(self,msg):

        data =  pmt.cdr(msg)
        if not pmt.is_u8vector(data):
            raise NameError("Data is not u8 vector")
        payload  = array.array("B",pmt.u8vector_elements(data))

        buf = payload
        
        #print buf
        
        for i in buf:
            if self.rx_state == GET_FEND:
                if i == FEND:
                    self.rx_state = GET_LEN
                    self.count = 0 
                    self.incoming_len = 0
                    
            elif self.rx_state == GET_LEN:
                self.incoming_len |= ( ( i & 0xFF ) << ( 8 * (3 - self.count ) ) )
                self.count += 1
                if self.count == 4:
                    #print "PDU Link(TTY): Receiving Payload Frame of Length:",self.incoming_len,self.last_time - time.time()
                    print "<binary_to_pdu> Receiving Payload Frame of Length:", self.incoming_len
                    self.last_time = time.time()
                    if self.incoming_len < 2048:
                        self.count = 0
                        self.rx_state = GET_PAYLOAD
                    else:
                        print "Received unreasonable payload length: ",self.incoming_len, "Aborting!"
                        self.rx_state = GET_FEND
            
            elif self.rx_state == GET_PAYLOAD:
                #print self.count,len(self.out_buf),self.incoming_len
                self.out_buf[self.count] = i
                self.count += 1
                if self.count == self.incoming_len:
                    #print buf
                    self.rx_state = GET_FEND
                    packet = self.out_buf[0:self.incoming_len]
                    print "<binary_to_pdu>", packet
                    self.message_port_pub(pmt.intern('pdu_out'),pmt.cons(pmt.PMT_NIL,pmt.init_u8vector(len(packet),packet)))
                    self.count = 0
Example #49
0
    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))
        satellite = None
        if len(packet) < 2 + 6 + 2:  # 2byte header, 6byte callsign, 2byte callsign crc
            return
        callsign = struct.unpack("6s", packet[2:8])[0]
        if callsign == 'DP0BEE':
            satellite = 'BEESAT-1'
        elif callsign == 'DP0BEF':
            satellite = 'BEESAT-2'
        elif callsign == 'DP0BEH':
            satellite = 'BEESAT-4'

        if satellite:
            self.message_port_pub(pmt.intern(satellite), msg_pmt)
Example #50
0
 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:
         return
     if not header.crc:
         self.message_port_pub(pmt.intern('ok'), msg_pmt)
     else:
         if len(packet) < 8: # bytes CSP header, 4 bytes CRC-32C
             # malformed
             return
         crc = packet[-4:]
         crc.reverse()
         packet = packet[:-4] + crc
         msg_pmt = pmt.cons(pmt.PMT_NIL, pmt.init_u8vector(len(packet), bytearray(packet)))
         self.message_port_pub(pmt.intern('out'), msg_pmt)
    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
Example #52
0
    def handle_pdu(self,msg):
        #print msg
        data =  pmt.cdr(msg)
        if not pmt.is_u8vector(data):
            raise NameError("Data is not u8 vector")

        payload  = array.array("B",pmt.u8vector_elements(data))
        payload_len = len(payload)

        packet = array.array('B',(0 for i in range(0,payload_len + 5)))

        packet[0] = 0x55
        packet[1] = ( payload_len & 0xFF000000 ) >> 24
        packet[2] = ( payload_len & 0x00FF0000 ) >> 16
        packet[3] = ( payload_len & 0x0000FF00 ) >> 8
        packet[4] = ( payload_len & 0x000000FF ) >> 0
        packet[5:]= payload
        src = (packet[5] >> 1) & 0b11111
        #print src
        #print "incoming from radio",packet
        if 1:
            self.message_port_pub(pmt.intern('binary_out'),pmt.cons(pmt.PMT_NIL,pmt.init_u8vector(len(packet),packet)))
Example #53
0
    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

        buff = list()
        buff.append(FEND)
        buff.append(numpy.uint8(0))
        for x in pmt.u8vector_elements(msg):
            if x == FESC:
                buff.append(FESC)
                buff.append(TFESC)
            elif x == FEND:
                buff.append(FESC)
                buff.append(TFEND)
            else:
                buff.append(numpy.uint8(x))
        buff.append(FEND)

        buff = array.array('B', buff)

        self.message_port_pub(pmt.intern('out'), pmt.cons(pmt.PMT_NIL, pmt.init_u8vector(len(buff), buff)))
Example #54
0
 def radio_rx(self, msg):
     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 = {}
     
     #sys.stderr.write("[r+]");sys.stderr.flush();
     with self.lock:
         self._radio_rx(data, meta_dict)
    def pdu_handler(self, msg_pmt):

        # Collect metadata, convert to Python format:
        meta = pmt.to_python(pmt.car(msg_pmt))

        # Collect message, convert to Python format:
        msg = pmt.cdr(msg_pmt)

        # Make sure it's a u8vector
        if not pmt.is_u8vector(msg):
            print "[ERROR] Received invalid message type.\n"
            return

        # create the AX.25 packet
        packeddata = DynamicPack(msg)
        frame = AX25_Frame(packeddata.packed)
        CRC = CheckCRC(frame.Frame)
        Stuffeddata = BitStuffer(CRC.appendmodulus)
        fullframe = HDLCFramer(Stuffeddata.Stuffed)


        # send the message on
        self.message_port_pub(pmt.intern('pdu_out'),msg_pmt)
Example #56
0
 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))
     '''