Example #1
0
    def _recv(self):
        """
            Receive a node message over UDP
        """
        if self.SOCK is None:
            try:
                self._connect()
            except:
                logger.error("No socket exist.  Aborting receive.")
                return None

        (msg_data, addr) = self.SOCK.recvfrom(G.UDP_MAX_SIZE)

        # Strip off IP header
        ip_header_len = (ord(msg_data[0]) & 0xf) * 4
        msg_data = msg_data[ip_header_len:]

        udp_header = UDPHeader(msg_data[:8])

        if udp_header.port_dst != self.port:
            return None

        # Strip off UDP header
        msg_data = msg_data[8:]

        if len(msg_data) < MESSAGE_HEADER_LEN:
            logger.error("Did not receive enough data to be a NodeMessage.")
            logger.error( ` msg_data `)
            return None

        # Extract our header
        node_message = NodeMessage(msg_data)

        #return a list of (message, addr) tuples
        return [(node_message, addr)]
Example #2
0
    def handle(self):
        """
            This function handles any inputs to our tx socket
        """
        sock = self.request

        logger.debug("Handler got message, forwarding to scheduler...")

        # Receive our header
        msg = NodeMessage()
        header = sock.recv(len(msg))

        # Receive our data
        msg._unpack(header)
        if msg.length > 0:
            msg.data = sock.recv(msg.length)

        # Forward data along to our scheduler
        TX_QUEUE.put(msg)
Example #3
0
 def handle(self):
     """
         This function handles any inputs to our tx socket
     """
     sock = self.request
     
     logger.debug("Handler got message, forwarding to scheduler...")
     
     # Receive our header
     msg = NodeMessage()
     header = sock.recv(len(msg))
     
     # Receive our data
     msg._unpack(header)
     if msg.length > 0:
         msg.data = sock.recv(msg.length)
     
     # Forward data along to our scheduler
     TX_QUEUE.put(msg)
Example #4
0
    def handle(self):
        """
            This function handles any inputs to our tx socket
        """
        sock = self.request

        logger.debug("Database handler got message, processing...")

        # Receive our header
        node_message = NodeMessage()
        header = sock.recv(len(node_message))

        # Receive our data
        node_message._unpack(header)
        if node_message.length > 0:
            node_message.data = sock.recv(node_message.length)

        # Grab our mutex to ensure only 1 write at time.
        with db_mutex:
            if node_message.type == G.MESSAGE_TYPE.DB_GPS:
                update_fn = DatabaseServer.DB.update_gps
            elif node_message.type == G.MESSAGE_TYPE.DB_PERSON:
                update_fn = DatabaseServer.DB.update_person
            elif node_message.type == G.MESSAGE_TYPE.DB_SERVICE:
                update_fn = DatabaseServer.DB.update_service
            else:
                logger.error("Got unrecognized DB packet. (Type: %d)" %
                             node_message.type)
                return False

            rtn_data = update_fn(node_message)
            if rtn_data is not False:
                logger.debug("Successfully updated db.")
                sock.sendall( ` rtn_data `)
            else:
                logger.debug("Db update failed.")
                sock.sendall("0")
Example #5
0
    def handle(self):
        """
            This function handles any inputs to our tx socket
        """
        sock = self.request

        logger.debug("Database handler got message, processing...")
        
        # Receive our header
        node_message = NodeMessage()
        header = sock.recv(len(node_message))
        
        # Receive our data
        node_message._unpack(header)
        if node_message.length > 0:
            node_message.data = sock.recv(node_message.length)

        # Grab our mutex to ensure only 1 write at time.
        with db_mutex:
            if node_message.type == G.MESSAGE_TYPE.DB_GPS:
                update_fn = DatabaseServer.DB.update_gps
            elif node_message.type == G.MESSAGE_TYPE.DB_PERSON:
                update_fn = DatabaseServer.DB.update_person
            elif node_message.type == G.MESSAGE_TYPE.DB_SERVICE:
                update_fn = DatabaseServer.DB.update_service
            else:
                logger.error("Got unrecognized DB packet. (Type: %d)"%
                             node_message.type)
                return False
            
            rtn_data = update_fn(node_message)
            if rtn_data is not False:
                logger.debug("Successfully updated db.")
                sock.sendall(`rtn_data`)
            else:
                logger.debug("Db update failed.")
                sock.sendall("0")
Example #6
0
 def get_sent_message(self,message_id,source_node_id,message_type):
     """
         Retrieve the sent message from our database.
         
         @param message_id: Message ID
         @param source_node_id: Source ID of original message
         @param message_type: Message type
     """
     
     SQL = """
         SELECT data FROM messages_sent
         WHERE message_id=?
         AND source_node_id=?
         AND message_type=?
         ORDER BY timestamp
         """
     
     result = self._sql(SQL, [message_id,
                              source_node_id,
                              message_type]).fetchone()
     if result is None:
         return result
     else:
         return NodeMessage(result[0])
Example #7
0
    def send(self, message_type, data="", destination=G.MESSAGE_BROADCAST_ADDRESS):
        """
            Craft a Node message and send it over our local UNIX socket
        """
        # Define a node message
        msg = NodeMessage()

        msg.source = 0  # Set by lower-level protocol
        msg.my_node_id = 0  # Set by lower-level protocol
        msg.path = 0  # Will be populated by our underlying
        # routing algorithm
        msg.visited = 0  # Always starts at 0
        # Must fill these in
        msg.type = message_type
        msg.data = data
        msg.destination = destination
        msg.frag_id = 0
        msg.frag_num = 1

        # Set the Length
        msg.length = len(msg.data)

        return self._send(msg)
Example #8
0
def gen_people(n, db, start_lat, stop_lat, start_long, stop_long):
    """
    Generates n people, random male/female ratio between 5 and 90 years of age
    """
    assert n > 0

    # open male first names file
    f = open("dist.male.first", "r")
    male_first_names = [name.strip().split()[0] for name in f.readlines()]
    f.close()

    # open female first names file
    f = open("dist.female.first", "r")
    female_first_names = [name.strip().split()[0] for name in f.readlines()]
    f.close()

    # open last names file
    f = open("dist.all.last", "r")
    family_names = [name.strip().split()[0] for name in f.readlines()]
    f.close()

    # generate people
    for i in range(n):

        catanDBObj = catan.db.CatanDatabaseObject()

        # bio
        sex = random.randint(0, 1)
        if sex == 0:  # male
            catanDBObj.person_bio.name_given = male_first_names[random.randint(0, len(male_first_names) - 1)]
            catanDBObj.person_bio.sex = "male"
        else:  # female
            catanDBObj.person_bio.name_given = female_first_names[random.randint(0, len(female_first_names) - 1)]
            catanDBObj.person_bio.sex = "female"

        catanDBObj.person_bio.name_family = family_names[random.randint(0, len(family_names) - 1)]
        catanDBObj.person_bio.age = random.randint(5, 90)

        # message (message, status, location, etc.)

        # location
        lat = round(random.uniform(start_lat, stop_lat), 6)
        lng = round(random.uniform(start_long, stop_long), 6)

        catanDBObj.person_message.person_message = "Hi Mom"

        catanDBObj.person_message.status_gps_latitude = lat
        catanDBObj.person_message.status_gps_longitude = lng
        catanDBObj.person_message.status_gps_accuracy = 0

        # status
        catanDBObj.person_message.status = STATUS_LIST[random.randint(0, len(STATUS_LIST) - 1)]
        catanDBObj.person_message.status_location = "Test status location"

        # generate a NodeMessage for the database
        # it only cares about the data and source fields, so we can ignore other fields
        nmsg = NodeMessage()
        nmsg.source = random.randint(0, 31)  # random node 0-31
        nmsg.data = catanDBObj.pack()

        db.update_db(nmsg)

    # Create some random updates
    for i in range(1, n + 1):
        update = random.randint(0, 1)
        if update == 0:

            catanDBObj = catan.db.CatanDatabaseObject()
            catanDBObj.person_id = i

            # location
            lat = round(random.uniform(start_lat, stop_lat), 6)
            lng = round(random.uniform(start_long, stop_long), 6)

            catanDBObj.person_message.person_message = "Location update 1"

            catanDBObj.person_message.status_gps_latitude = lat
            catanDBObj.person_message.status_gps_longitude = lng
            catanDBObj.person_message.status_gps_accuracy = 0

            n = NodeMessage()
            n.source = random.randint(0, 31)
            n.data = catanDBObj.pack()

            db.update_db(n)
Example #9
0
    def _recv(self):
        """
            Called repeatedly by RxServer.server_forever
            May return None or one or more messages
        """
        #Do once per call
        msgs = []

        # Read from serial device
        if self.ser:
            s = self.ser.read(1000)
            try:
                n = len(s)
            except TypeError:
                n = 0
        else:
            logger.error("No serial device")
            self._connect()
            time.sleep(5)
            n = 0

        #logger.debug("Received %d bytes" % n)

        # Process received data
        if n > 0:
            lst = []

            w = s.split(chr(0xc0))
            n = len(w)

            # No 0xc0 in frame
            if n == 1:
                self.buf += w[0]

            # Single 0xc0 in frame
            elif n == 2:
                # Closing 0xc0 found
                if not w[0] == '':
                    # Partial frame continued, otherwise drop
                    lst.append(self.buf + w[0])
                    self.buf = ''

                # Opening 0xc0 found
                else:
                    lst.append(self.buf)
                    self.buf = w[1]

            # At least one complete frane received
            elif n >= 3:
                for i in range(0, n - 1):
                    st = self.buf + w[i]
                    if not st == '':
                        lst.append(st)
                        self.buf = ''
                if not w[n - 1] == '':
                    self.buf = w[n - 1]

            # Loop through received frames
            for p in lst:
                if len(p) == 0:
                    continue
                if ord(p[0]) == 0:  #received a data frame
                    #hex_str = " ".join([ "{:02x}".format(ord(c)) for c in p[1:] ])
                    #logger.debug("MSG RAW (HEX): "+hex_str)
                    raw_str = ax25.kiss2raw(p[1:])
                    msg_tuple = ax25.parse_raw_msg(raw_str)
                    if msg_tuple:
                        strfrom, strto, msg_data, digis = msg_tuple
                        #logger.debug(msg_data)
                        if len(msg_data) < MESSAGE_HEADER_LEN:
                            logger.error("Did not receive enough "
                                         "data to be a NodeMessage.")
                            #logger.error(`msg_data`)
                            continue
                #Convert to Node Message
                        node_msg = NodeMessage(msg_data)
                        if node_msg is not None:
                            msgs.append((node_msg, strfrom))

        #return a list of (message, addr) tuples
        if msgs:
            return msgs
        else:
            return None
Example #10
0
import logging
import time
import IN
logger = logging.getLogger(__name__)

# CATAN
import catan.globals as G
from catan.data import NodeMessage

# AX25
from data import UDPHeader
import catan.ax25 as ax25
import serial

# Constansts
MESSAGE_HEADER_LEN = len(NodeMessage())


class LinkTransmitter:
    def send(self, node_message):
        """
           Send a NodeMessage to the proper node referenced by its node id.
           
            @param node_message: an object that is of type NodeMessage
        """
        logger.debug("LinkTransmitter sending message of length %d" %
                     len(node_message))

        self._send(node_message)

    def _send(self, node_message):
Example #11
0
def gen_people(n, db, start_lat, stop_lat, start_long, stop_long):
    """
    Generates n people, random male/female ratio between 5 and 90 years of age
    """
    assert n > 0

    # open male first names file
    f = open('dist.male.first', 'r')
    male_first_names = [name.strip().split()[0] for name in f.readlines()]
    f.close()

    # open female first names file
    f = open('dist.female.first', 'r')
    female_first_names = [name.strip().split()[0] for name in f.readlines()]
    f.close()

    # open last names file
    f = open('dist.all.last', 'r')
    family_names = [name.strip().split()[0] for name in f.readlines()]
    f.close()

    # generate people
    for i in range(n):

        catanDBObj = catan.db.CatanDatabaseObject()

        # bio
        sex = random.randint(0, 1)
        if sex == 0:  # male
            catanDBObj.person_bio.name_given = male_first_names[random.randint(
                0,
                len(male_first_names) - 1)]
            catanDBObj.person_bio.sex = 'male'
        else:  # female
            catanDBObj.person_bio.name_given = female_first_names[
                random.randint(0,
                               len(female_first_names) - 1)]
            catanDBObj.person_bio.sex = 'female'

        catanDBObj.person_bio.name_family = family_names[random.randint(
            0,
            len(family_names) - 1)]
        catanDBObj.person_bio.age = random.randint(5, 90)

        # message (message, status, location, etc.)

        # location
        lat = round(random.uniform(start_lat, stop_lat), 6)
        lng = round(random.uniform(start_long, stop_long), 6)

        catanDBObj.person_message.person_message = 'Hi Mom'

        catanDBObj.person_message.status_gps_latitude = lat
        catanDBObj.person_message.status_gps_longitude = lng
        catanDBObj.person_message.status_gps_accuracy = 0

        # status
        catanDBObj.person_message.status = STATUS_LIST[random.randint(
            0,
            len(STATUS_LIST) - 1)]
        catanDBObj.person_message.status_location = 'Test status location'

        # generate a NodeMessage for the database
        # it only cares about the data and source fields, so we can ignore other fields
        nmsg = NodeMessage()
        nmsg.source = random.randint(0, 31)  # random node 0-31
        nmsg.data = catanDBObj.pack()

        db.update_db(nmsg)

    # Create some random updates
    for i in range(1, n + 1):
        update = random.randint(0, 1)
        if update == 0:

            catanDBObj = catan.db.CatanDatabaseObject()
            catanDBObj.person_id = i

            # location
            lat = round(random.uniform(start_lat, stop_lat), 6)
            lng = round(random.uniform(start_long, stop_long), 6)

            catanDBObj.person_message.person_message = 'Location update 1'

            catanDBObj.person_message.status_gps_latitude = lat
            catanDBObj.person_message.status_gps_longitude = lng
            catanDBObj.person_message.status_gps_accuracy = 0

            n = NodeMessage()
            n.source = random.randint(0, 31)
            n.data = catanDBObj.pack()

            db.update_db(n)
Example #12
0
 def send(self, message_type, data="", destination=G.MESSAGE_BROADCAST_ADDRESS):
     """
         Craft a Node message and send it over our local UNIX socket
     """
     # Define a node message
     msg = NodeMessage()
     
     msg.source = 0                  # Set by lower-level protocol
     msg.my_node_id = 0              # Set by lower-level protocol
     msg.path = 0                    # Will be populated by our underlying
                                     # routing algorithm
     msg.visited = 0                 # Always starts at 0
     # Must fill these in
     msg.type = message_type
     msg.data = data
     msg.destination = destination
     msg.frag_id = 0
     msg.frag_num = 1
     
     # Set the Length
     msg.length = len(msg.data)
     
     return self._send(msg)