def ContentList_Request(self, type): if type == const.ContentType['END']: for t in const.ContentType: if t == 'BEGIN' or t == 'END': continue self.ContentList_Request(const.ContentType[t]) return p = DataPacket(0, const.PACKET_CONTENT_CLIENT_INFO_LIST) p.send_uint8(type) p.send_uint32(version.generate_newgrf_version(1,1,0,False,0)) # XXX find better way? self.sendMsg_TCP(p.command, p.data)
def getGRFInfo(self, grfs, addr=None): p = DataPacket(0, const.PACKET_UDP_CLIENT_GET_NEWGRFS) p.send_uint8(len(grfs)) for grf in grfs: p.send_something('4s16s', grf) self.sendMsg_UDP(p.command, p.data, addr=addr) p = self.receiveMsg_UDP(True, useaddr=not addr is None) if p is None: LOG.debug("unable to receive UDP packet") return None newgrfs = [] if p.command == const.PACKET_UDP_SERVER_NEWGRFS: reply_count = p.recv_uint8() for i in range(0, reply_count): [grfid, md5sum] = p.recv_something('4s16s') grfname = p.recv_str() newgrfs.append([grfid, md5sum, grfname]) LOG.debug("Got reply to grf request with %d grfs:" % reply_count) for grf in newgrfs: LOG.debug(" %s - %s - %s" % (grf[0].encode("hex"), grf[1].encode("hex"), grf[2])) if not addr is None: return p.addr, newgrfs else: return newgrfs else: raise _error.UnexpectedResponse("PACKET_UDP_CLIENT_GET_NEWGRFS", str(p.command))
def setUp(self): self.packet = Packet(self.SRC, self.FLOW_ID, self.DEST, self.TIMESTAMP, self.LENGTH, self.PACKET_TYPE, self.SEQ_NUM) self.data_packet = DataPacket(self.SRC, self.FLOW_ID, self.DEST, self.TIMESTAMP, self.SEQ_NUM) self.ack_packet = AckPacket(self.SRC, self.FLOW_ID, self.DEST, self.TIMESTAMP, self.SEQ_NUM) self.routing_update_packet = RoutingUpdatePacket( self.SRC, self.FLOW_ID, self.DEST, self.TIMESTAMP, self.SEQ_NUM, self.DIST_ESTIMATES) self.fin_packet = FINPacket(self.SRC, self.FLOW_ID, self.DEST, self.TIMESTAMP, self.SEQ_NUM)
def ContentList_Request_ids(self, ids): count = len(ids) sent = 0 while count > 0: p_count = min((const.SEND_MTU - const.HEADER_SIZE - 4) / 4, count) p = DataPacket(0, const.PACKET_CONTENT_CLIENT_INFO_ID) p.send_uint16(p_count) for i in range(sent, p_count + sent): p.send_uint32(ids[i]) self.sendMsg_TCP(p.command, p.data) count -= p_count sent += p_count
def getGRFInfo(self, grfs, addr=None): p = DataPacket(0, const.PACKET_UDP_CLIENT_GET_NEWGRFS) p.send_uint8(len(grfs)) for grf in grfs: p.send_something('4s16s', grf) self.sendMsg_UDP(p.command, p.data, addr=addr) p = self.receiveMsg_UDP(True, useaddr=not addr is None) if p is None: LOG.debug("unable to receive UDP packet") return None newgrfs = [] if p.command == const.PACKET_UDP_SERVER_NEWGRFS: reply_count = p.recv_uint8() for i in range(0, reply_count): [grfid, md5sum] = p.recv_something('4s16s') grfname = p.recv_str() newgrfs.append([grfid, md5sum, grfname]) LOG.debug("Got reply to grf request with %d grfs:" % reply_count) for grf in newgrfs: LOG.debug(" %s - %s - %s" % (grf[0].encode("hex"), grf[1].encode("hex"), grf[2])) if not addr is None: return p.addr, newgrfs else: return newgrfs else: raise _error.UnexpectedResponse("PACKET_UDP_CLIENT_GET_NEWGRFS", str(p.command))
def create_packet(self, packet_id, delay=0.0): """Creates packet and then adds it to event queue to be sent to the host, along with a timing event to ensure that they are resent if unacknowledged. Args: packet_id (int): Unique id identifying the packet delay (float): delay until sending packet. Should only be used for initial send. """ new_packet = DataPacket(packet_id, self.src.node_id, self.dest.node_id, self.flow_id, self.ns.cur_time + delay) self.unacknowledged_packets.add(new_packet.packet_id) event1 = lambda: self.src.send_packet(new_packet) event1_message = "flow.create_packet: Flow" + str(self.flow_id) + \ ": made data packet " + str(new_packet.packet_id) self.ns.add_event(event1, event1_message, delay=delay) event2 = lambda: self.time_out(new_packet.packet_id) event2_message = "flow.create_packet: Adding to time_out_packets, packet " + \ str(new_packet.packet_id) self.ns.add_event(event2, event2_message, delay=TIMEOUT_DELAY + delay)
def tahoe_monitor_incoming_pkts(self, env): """ Process to handle incoming packets for Tahoe """ while self.data_amt > 0: yield self.receive_packet_event received_packet = self.received_packets.pop() # Throw error if packet not an ack packet. assert(received_packet.get_packet_type() == Packet.PacketTypes.ack_packet) req_num = received_packet.get_seq_num() # Update sum RTT self.rtt = self.env.now - received_packet.get_timestamp() self.sum_RTT_delay += self.rtt # Reset event self.receive_packet_event = env.event() # Ignore ack packets from previous window iterations. if (received_packet.get_timestamp() < self.window_start_time): continue if (req_num > self.batch_start): self.data_amt -= (req_num - self.batch_start) * \ SendingFlow.DATA_PCK_SIZE self.dup_ack = 0 # CA if self.is_CA: for i in range(req_num - self.batch_start): self.window_size += 1.0 / self.window_size # SS else: self.window_size += 1 if self.window_size >= self.ssthresh: self.is_CA = True self.batch_start = req_num elif req_num == self.batch_start: if self.env.now - self.last_dup >= 16: self.dup_ack += 1 self.last_dup = self.env.now if self.dup_ack == SendingFlow.DUP_ACK: data_packet = DataPacket(self.src_host_id, self.flow_id, self.dest_host_id, self.env.now, self.batch_start) self.send_packet(data_packet) self.dup_ack = 0 self.enter_slow_start() if (self.batch_start == self.window_end + 1): self.received_batch_event.succeed() yield self.receive_packet_event received_packet = self.received_packets.pop() if (received_packet.get_packet_type() == Packet.PacketTypes.fin_packet): self.received_fin_event.succeed()
def receiveMsg_TCP(self, datapacket=False): if self.socket_tcp is None: raise _error.ConnectionError("no tcp socket for receiving") raw = "" note = "" data, readcounter = self.receive_bytes(self.socket_tcp, const.HEADER.size) if readcounter > 1: note += "HEADER SEGMENTED INTO %s SEGMENTS!" % readcounter raw += data size, command = networking.parsePacketHeader(data) if not command in (const.PACKET_SERVER_FRAME, const.PACKET_SERVER_SYNC): if command in const.packet_names: LOG.debug("received size: %d, command: %s (%d)" % (size, const.packet_names[command], command)) else: LOG.debug("received size: %d, command: %d" % (size, command)) size -= const.HEADER.size # remove size of the header ... data, readcounter = self.receive_bytes(self.socket_tcp, size) if readcounter > 1: note += "DATA SEGMENTED INTO %s SEGMENTS!" % readcounter raw += data if not self.running: return None if len(note) > 0: LOG.info(note) content = data if datapacket: return DataPacket(size, command, content) else: return size, command, content
def handle_data_packet(self, arr): """Handle a data packet by extracting it's fields. """ if len(arr) != DataPacketSize: logging.warning( f"Incorrect data size. Is: {len(arr)}, expected: {DataPacketSize}. Packet: {arr}" ) return # stupid manual struct unpacking is stupid s = struct.unpack(DataPacketStruct, arr) dp = DataPacket(type=s[0], size=s[1], crc16=s[2], packetID=s[3], us_start=s[4], us_end=s[5], states=s[6:14], digitalIn=s[14], digitalOut=s[15], padding=None) # let the TeensyCommander deal with the actual packet content if self.commander: self.commander.handle_packet(dp)
def send_file(self, file_path, destination): self.socket.settimeout(5) last_packet = 0 last_ack_packet = 0 file_size = os.path.getsize(file_path) total_packet = math.ceil(file_size / 50000) sent_packets = [] with open(file_path, "rb") as f: while True: while last_packet - last_ack_packet < WINDOW_SIZE and last_packet < total_packet: data = f.read(50000) packet = DataPacket(data, last_packet, last_packet == total_packet - 1) self.socket.sendto(pickle.dumps(packet), destination) sent_packets.append(packet) last_packet += 1 try: packet, _ = self.socket.recvfrom(65000) pckSeq = int(packet) if pckSeq == total_packet: break last_ack_packet = max(last_ack_packet, pckSeq) except socket.timeout: for i in range(last_ack_packet, last_packet): packet = pickle.dumps(sent_packets[i]) self.socket.sendto(packet, destination)
def send_data(self, p_id, destination, is_retransmit, env): if not is_retransmit: self.send_times[destination][p_id] = env.now else: self.send_times[destination].pop(p_id, None) if debug_state: print('Sending DataPacket', p_id, 'at', env.now) packet = DataPacket(p_id=p_id, source=self.ip, destination=destination) env.process(self.links[0].send_packet(packet=packet, source=self.ip, env=env))
def receiveMsg_UDP(self, datapacket = False, useaddr = False): if self.socket_udp is None: raise _error.ConnectionError("no udp socket for receiving") if useaddr: data, addr = self.socket_udp.recvfrom(4096) else: data = self.socket_udp.recv(4096) addr = None #print data size, command = networking.parsePacketHeader(data) LOG.debug("received size: %d, command: %d"% (size, command)) content = data[const.HEADER.size:] if datapacket: ret = DataPacket(size, command, content) ret.addr = addr else: if useaddr: ret = addr, size, command, content else: ret = size, command, content return ret
def setUp(self): self.packet = Packet(self.SRC, self.FLOW_ID, self.DEST, self.TIMESTAMP, self.LENGTH, self.PACKET_TYPE, self.SEQ_NUM) self.data_packet = DataPacket(self.SRC, self.FLOW_ID, self.DEST, self.TIMESTAMP, self.SEQ_NUM) self.ack_packet = AckPacket(self.SRC, self.FLOW_ID, self.DEST, self.TIMESTAMP, self.SEQ_NUM) self.routing_update_packet = RoutingUpdatePacket( self.SRC, self.FLOW_ID, self.DEST, self.TIMESTAMP, self.SEQ_NUM, self.DIST_ESTIMATES) self.fin_packet = FINPacket(self.SRC, self.FLOW_ID, self.DEST, self.TIMESTAMP, self.SEQ_NUM)
def receiveMsg_UDP(self, datapacket=False, useaddr=False): if self.socket_udp is None: raise _error.ConnectionError("no udp socket for receiving") if useaddr: data, addr = self.socket_udp.recvfrom(4096) else: data = self.socket_udp.recv(4096) addr = None #print data size, command = networking.parsePacketHeader(data) LOG.debug("received size: %d, command: %d" % (size, command)) content = data[const.HEADER.size:] if datapacket: ret = DataPacket(size, command, content) ret.addr = addr else: if useaddr: ret = addr, size, command, content else: ret = size, command, content return ret
def generate_packets_to_send(self): ''' Fill self.packets with the packets that we want to send ''' npackets = self.amount // globals_.DATA_PACKET_SIZE if self.amount % globals_.DATA_PACKET_SIZE != 0: npackets += 1 for id_ in xrange(npackets): self.packets_to_send.append( DataPacket(id_=id_, src=self.src_obj.id_, dst=self.dst_obj.id_, flow=self))
def ContentList_Request(self, type): if type == const.ContentType['END']: for t in const.ContentType: if t == 'BEGIN' or t == 'END': continue self.ContentList_Request(const.ContentType[t]) return p = DataPacket(0, const.PACKET_CONTENT_CLIENT_INFO_LIST) p.send_uint8(type) p.send_uint32(version.generate_newgrf_version( 1, 1, 0, False, 0)) # XXX find better way? self.sendMsg_TCP(p.command, p.data)
def ContentList_Request_ids(self, ids): count = len(ids) sent = 0 while count > 0: p_count = min((const.SEND_MTU - const.HEADER_SIZE - 4) / 4, count) p = DataPacket(0, const.PACKET_CONTENT_CLIENT_INFO_ID) p.send_uint16(p_count) for i in range(sent, p_count + sent): p.send_uint32(ids[i]) self.sendMsg_TCP(p.command, p.data) count -= p_count sent += p_count
def send_data(self, env): """Sends a batch of data packets starting at batch_start.""" seq_num = self.batch_start self.window_start_time = self.env.now self.window_start = self.batch_start if self.data_amt >= SendingFlow.DATA_PCK_SIZE * self.window_size: self.window_end = int(self.batch_start + self.window_size - 1) else: self.window_end = int(self.data_amt / SendingFlow.DATA_PCK_SIZE) \ + self.batch_start - 1 while (seq_num <= self.window_end): data_packet = DataPacket(self.src_host_id, self.flow_id, self.dest_host_id, self.env.now, seq_num) self.send_packet(data_packet) seq_num += 1 yield env.timeout(SendingFlow.DATA_PCK_SIZE / self.src_host.get_link_rate())
def CompanyInfo_Process(self, data="", p=None): """ Processes a companyinfo response @param p: DataPacket to read from @type p: DataPacket @param data: data to use when p is not given @type data: string @returns: processed data @rtype: DataStorageClass """ if p is None: p = DataPacket(len(data), const.PACKET_UDP_SERVER_DETAIL_INFO, data) info_version = p.recv_uint8() player_count = p.recv_uint8() if info_version == const.NETWORK_COMPANY_INFO_VERSION or info_version == 5 or info_version == 4: companies = [] for i in range(0, player_count): company = DataStorageClass() company.number = p.recv_uint8() + 1 company.company_name = p.recv_str() company.inaugurated_year = p.recv_uint32() company.company_value = p.recv_uint64() company.money = p.recv_uint64() company.income = p.recv_uint64() company.performance = p.recv_uint16() company.password_protected = p.recv_bool() company.vehicles = p.recv_something('H' * 5) company.stations = p.recv_something('H' * 5) if info_version == 4: # get the client information from version 4 players = [] while p.recv_bool(): player = DataStorageClass() player.client_name = p.recv_str() player.unique_id = p.recv_str() player.join_date = p.recv_uint32() players.append(player) company.clients = players companies.append(company) if info_version == 4: # get the list of spectators from version 4 players = [] while p.recv_bool(): player = DataStorageClass() player.client_name = p.recv_str() player.unique_id = p.recv_str() player.join_date = p.recv_uint32() players.append(player) ret = DataStorageClass() ret.info_version = info_version ret.player_count = player_count ret.companies = companies if info_version == 4: ret.spectators = players return ret
def GameInfo_Process(self, data="", p=None, encode_grfs=False, short=False): """ Processes a gameinfo response @param p: DataPacket to read from @type p: DataPacket @param data: data to use when p is not given @type data: string @param encode_grfs: return the grfs in hex if True @type encode_grfs: bool @param short: only return the things that could change? @type short: bool @returns: processed data @rtype: DataStorageClass """ if p is None: p = DataPacket(len(data), const.PACKET_UDP_SERVER_RESPONSE, data) info = DataStorageClass() info.game_info_version = p.recv_uint8() if info.game_info_version >= 4: grfcount = p.recv_uint8() grfs = [] for i in range(0, grfcount): [grfid, md5sum] = p.recv_something('4s16s') if encode_grfs: grfs.append((grfid.encode('hex'), md5sum.encode('hex'))) else: grfs.append((grfid, md5sum)) if not short: info.grfs = grfs if info.game_info_version >= 3: info.game_date = p.recv_uint32() if not short: info.start_date = p.recv_uint32() else: p.recv_uint32() if info.game_info_version >= 2: info.companies_max = p.recv_uint8() info.companies_on = p.recv_uint8() info.spectators_max = p.recv_uint8() if info.game_info_version >= 1: info.server_name = p.recv_str() if not short: info.server_revision = p.recv_str() else: p.recv_str() info.server_lang = p.recv_uint8() info.use_password = p.recv_bool() info.clients_max = p.recv_uint8() info.clients_on = p.recv_uint8() info.spectators_on = p.recv_uint8() if info.game_info_version < 3: # 16-bit dates were removed from version 3 info.game_date = p.recv_uint16( ) + const.DAYS_TILL_ORIGINAL_BASE_YEAR if not short: info.start_date = p.recv_uint16( ) + const.DAYS_TILL_ORIGINAL_BASE_YEAR else: p.recv_uint16() if not short: info.map_name = p.recv_str() info.map_width = p.recv_uint16() info.map_height = p.recv_uint16() info.map_set = p.recv_uint8() info.dedicated = p.recv_bool() else: p.recv_something("zHBB") return info
class PacketTest(unittest.TestCase): """Test definitions and methods of Packet base class.""" # Various test constants SRC = 1 FLOW_ID = 2 DEST = 3 TIMESTAMP = 30 LENGTH = 64 PACKET_TYPE = Packet.PacketTypes.data_packet SEQ_NUM = 15 DATA_PACKET_LENGTH = 1024 ACKNOWLEDGMENT_PACKET_LENGTH = 64 ROUTING_UPDATE_PACKET_LENGTH = 1024 FIN_PACKET_LENGTH = 64 NEW_SRC = 10 NEW_DEST = 20 NEW_TIMESTAMP = 31 NEW_SEQ_NUM = 49 DIST_ESTIMATES = [(1, 0), (2, 3), (3, 10), (4, 11)] def setUp(self): self.packet = Packet(self.SRC, self.FLOW_ID, self.DEST, self.TIMESTAMP, self.LENGTH, self.PACKET_TYPE, self.SEQ_NUM) self.data_packet = DataPacket(self.SRC, self.FLOW_ID, self.DEST, self.TIMESTAMP, self.SEQ_NUM) self.ack_packet = AckPacket(self.SRC, self.FLOW_ID, self.DEST, self.TIMESTAMP, self.SEQ_NUM) self.routing_update_packet = RoutingUpdatePacket( self.SRC, self.FLOW_ID, self.DEST, self.TIMESTAMP, self.SEQ_NUM, self.DIST_ESTIMATES) self.fin_packet = FINPacket(self.SRC, self.FLOW_ID, self.DEST, self.TIMESTAMP, self.SEQ_NUM) def test_initialization(self): """Checks that packets are initialized with correct specifications. This tests the correctness of the accessors in the process. """ self.assertEqual(self.SRC, self.packet.get_source()) self.assertEqual(self.FLOW_ID, self.packet.get_flow_id()) self.assertEqual(self.DEST, self.packet.get_destination()) self.assertEqual(self.TIMESTAMP, self.packet.get_timestamp()) self.assertEqual(self.PACKET_TYPE, self.packet.get_packet_type()) self.assertEqual(self.DATA_PACKET_LENGTH, self.data_packet.get_length()) self.assertEqual(self.ACKNOWLEDGMENT_PACKET_LENGTH, self.ack_packet.get_length()) self.assertEqual(self.ROUTING_UPDATE_PACKET_LENGTH, self.routing_update_packet.get_length()) self.assertEqual(self.FIN_PACKET_LENGTH, self.fin_packet.get_length()) self.assertEqual(Packet.PacketTypes.data_packet, self.data_packet.get_packet_type()) self.assertEqual(Packet.PacketTypes.ack_packet, self.ack_packet.get_packet_type()) self.assertEqual(Packet.PacketTypes.routing_update_packet, self.routing_update_packet.get_packet_type()) self.assertEqual(Packet.PacketTypes.fin_packet, self.fin_packet.get_packet_type()) self.assertEqual(self.SEQ_NUM, self.packet.get_seq_num()) self.assertItemsEqual(self.DIST_ESTIMATES, self.routing_update_packet.get_distance_estimates()) def test_mutators(self): """Checks that packet attributes are modified correctly.""" # Mutate packet fields. self.packet.set_source(self.NEW_SRC) self.packet.set_destination(self.NEW_DEST) self.packet.set_timestamp(self.NEW_TIMESTAMP) self.packet.set_seq_num(self.NEW_SEQ_NUM) # Check packet fields have been updated correctly. self.assertEqual(self.NEW_SRC, self.packet.get_source()) self.assertEqual(self.NEW_DEST, self.packet.get_destination()) self.assertEqual(self.NEW_TIMESTAMP, self.packet.get_timestamp()) self.assertEqual(self.NEW_SEQ_NUM, self.packet.get_seq_num())
def make_packet(self, packet_no): """Make a data packet with the given packet number.""" return DataPacket(self.src, self.dest, self.id, packet_no, self.env.now)
def GameInfo_Process(self, data="", p=None, encode_grfs=False, short=False): """ Processes a gameinfo response @param p: DataPacket to read from @type p: DataPacket @param data: data to use when p is not given @type data: string @param encode_grfs: return the grfs in hex if True @type encode_grfs: bool @param short: only return the things that could change? @type short: bool @returns: processed data @rtype: DataStorageClass """ if p is None: p = DataPacket(len(data), const.PACKET_UDP_SERVER_RESPONSE, data) info = DataStorageClass() info.game_info_version = p.recv_uint8() if info.game_info_version >= 4: grfcount = p.recv_uint8() grfs = [] for i in range(0, grfcount): [grfid, md5sum] = p.recv_something('4s16s') if encode_grfs: grfs.append((grfid.encode('hex'), md5sum.encode('hex'))) else: grfs.append((grfid, md5sum)) if not short: info.grfs = grfs if info.game_info_version >=3: info.game_date = p.recv_uint32() if not short: info.start_date = p.recv_uint32() else: p.recv_uint32() if info.game_info_version >=2: info.companies_max = p.recv_uint8() info.companies_on = p.recv_uint8() info.spectators_max = p.recv_uint8() if info.game_info_version >=1: info.server_name = p.recv_str() if not short: info.server_revision = p.recv_str() else: p.recv_str() info.server_lang = p.recv_uint8() info.use_password = p.recv_bool() info.clients_max = p.recv_uint8() info.clients_on = p.recv_uint8() info.spectators_on = p.recv_uint8() if info.game_info_version < 3: # 16-bit dates were removed from version 3 info.game_date = p.recv_uint16() + const.DAYS_TILL_ORIGINAL_BASE_YEAR if not short: info.start_date = p.recv_uint16() + const.DAYS_TILL_ORIGINAL_BASE_YEAR else: p.recv_uint16() if not short: info.map_name = p.recv_str() info.map_width = p.recv_uint16() info.map_height = p.recv_uint16() info.map_set = p.recv_uint8() info.dedicated = p.recv_bool() else: p.recv_something("zHBB") return info
def CompanyInfo_Process(self, data="", p=None): """ Processes a companyinfo response @param p: DataPacket to read from @type p: DataPacket @param data: data to use when p is not given @type data: string @returns: processed data @rtype: DataStorageClass """ if p is None: p = DataPacket(len(data), const.PACKET_UDP_SERVER_DETAIL_INFO, data) info_version = p.recv_uint8() player_count = p.recv_uint8() if info_version == const.NETWORK_COMPANY_INFO_VERSION or info_version == 5 or info_version == 4: companies = [] for i in range(0, player_count): company = DataStorageClass() company.number = p.recv_uint8() + 1 company.company_name = p.recv_str() company.inaugurated_year = p.recv_uint32() company.company_value = p.recv_uint64() company.money = p.recv_uint64() company.income = p.recv_uint64() company.performance = p.recv_uint16() company.password_protected = p.recv_bool() company.vehicles = p.recv_something('H'*5) company.stations = p.recv_something('H'*5) if info_version == 4: # get the client information from version 4 players = [] while p.recv_bool(): player = DataStorageClass() player.client_name = p.recv_str() player.unique_id = p.recv_str() player.join_date = p.recv_uint32() players.append(player) company.clients = players companies.append(company) if info_version == 4: # get the list of spectators from version 4 players = [] while p.recv_bool(): player = DataStorageClass() player.client_name = p.recv_str() player.unique_id = p.recv_str() player.join_date = p.recv_uint32() players.append(player) ret = DataStorageClass() ret.info_version = info_version ret.player_count = player_count ret.companies = companies if info_version == 4: ret.spectators = players return ret
class PacketTest(unittest.TestCase): """Test definitions and methods of Packet base class.""" # Various test constants SRC = 1 FLOW_ID = 2 DEST = 3 TIMESTAMP = 30 LENGTH = 64 PACKET_TYPE = Packet.PacketTypes.data_packet SEQ_NUM = 15 DATA_PACKET_LENGTH = 1024 ACKNOWLEDGMENT_PACKET_LENGTH = 64 ROUTING_UPDATE_PACKET_LENGTH = 1024 FIN_PACKET_LENGTH = 64 NEW_SRC = 10 NEW_DEST = 20 NEW_TIMESTAMP = 31 NEW_SEQ_NUM = 49 DIST_ESTIMATES = [(1, 0), (2, 3), (3, 10), (4, 11)] def setUp(self): self.packet = Packet(self.SRC, self.FLOW_ID, self.DEST, self.TIMESTAMP, self.LENGTH, self.PACKET_TYPE, self.SEQ_NUM) self.data_packet = DataPacket(self.SRC, self.FLOW_ID, self.DEST, self.TIMESTAMP, self.SEQ_NUM) self.ack_packet = AckPacket(self.SRC, self.FLOW_ID, self.DEST, self.TIMESTAMP, self.SEQ_NUM) self.routing_update_packet = RoutingUpdatePacket( self.SRC, self.FLOW_ID, self.DEST, self.TIMESTAMP, self.SEQ_NUM, self.DIST_ESTIMATES) self.fin_packet = FINPacket(self.SRC, self.FLOW_ID, self.DEST, self.TIMESTAMP, self.SEQ_NUM) def test_initialization(self): """Checks that packets are initialized with correct specifications. This tests the correctness of the accessors in the process. """ self.assertEqual(self.SRC, self.packet.get_source()) self.assertEqual(self.FLOW_ID, self.packet.get_flow_id()) self.assertEqual(self.DEST, self.packet.get_destination()) self.assertEqual(self.TIMESTAMP, self.packet.get_timestamp()) self.assertEqual(self.PACKET_TYPE, self.packet.get_packet_type()) self.assertEqual(self.DATA_PACKET_LENGTH, self.data_packet.get_length()) self.assertEqual(self.ACKNOWLEDGMENT_PACKET_LENGTH, self.ack_packet.get_length()) self.assertEqual(self.ROUTING_UPDATE_PACKET_LENGTH, self.routing_update_packet.get_length()) self.assertEqual(self.FIN_PACKET_LENGTH, self.fin_packet.get_length()) self.assertEqual(Packet.PacketTypes.data_packet, self.data_packet.get_packet_type()) self.assertEqual(Packet.PacketTypes.ack_packet, self.ack_packet.get_packet_type()) self.assertEqual(Packet.PacketTypes.routing_update_packet, self.routing_update_packet.get_packet_type()) self.assertEqual(Packet.PacketTypes.fin_packet, self.fin_packet.get_packet_type()) self.assertEqual(self.SEQ_NUM, self.packet.get_seq_num()) self.assertItemsEqual( self.DIST_ESTIMATES, self.routing_update_packet.get_distance_estimates()) def test_mutators(self): """Checks that packet attributes are modified correctly.""" # Mutate packet fields. self.packet.set_source(self.NEW_SRC) self.packet.set_destination(self.NEW_DEST) self.packet.set_timestamp(self.NEW_TIMESTAMP) self.packet.set_seq_num(self.NEW_SEQ_NUM) # Check packet fields have been updated correctly. self.assertEqual(self.NEW_SRC, self.packet.get_source()) self.assertEqual(self.NEW_DEST, self.packet.get_destination()) self.assertEqual(self.NEW_TIMESTAMP, self.packet.get_timestamp()) self.assertEqual(self.NEW_SEQ_NUM, self.packet.get_seq_num())
def complete_data_to_packet(data): size, command = parsePacketHeader(data) size -= const.HEADER_SIZE return DataPacket(size, command, data[const.HEADER_SIZE:])