Ejemplo n.º 1
0
def download(C, F):

	# global variables
	global node

	MY_CONNS = {}

	# open file and look for CONN_LIST
	if os.path.isfile('my_conns'):
		with open('my_conns', 'r') as fp:
			MY_CONNS = json.load(fp)
			fp.close()	

	if str(C) in MY_CONNS:
		for item in MY_CONNS:
			if item == str(C):
				dest_nid = MY_CONNS[C]

	else:
		print "download(" + str(C) + ", " + F + ") - CID=" + str(C) + " does not exist"
		return	

	# set variables
	code = '60' # request a file
	filename = F
	CID = C
	string = {}
	string['code'] = code
	string['filename'] = filename
	string['source_nid'] = node.GetNID()
	data = json.dumps(string)

	Transport.l4_sendto(node, dest_nid, data)
Ejemplo n.º 2
0
def l3_recvfrom(node, message):
  
  # decode payload
  data = json.loads(message)

  # get destination nid from payload
  dest_nid = data['destination_nid']

  # get last nid from payload
  last_nid = data['last_nid']

  # reset last nid
  data['last_nid'] = node.GetNID()

  # set variable for segment
  segment = data['payload']

  # if it is for this node, pass it up to layer 4
  if str(dest_nid) == str(node.GetNID()):
    Transport.l4_recvfrom(segment)

  # if its not for this node, send it back down to layer 2
  else:
    ttl = data['ttl']
    new_ttl = (ttl - 1)
    data['ttl'] = new_ttl
    if (data['ttl'] > 0):
      datagram = json.dumps(data)
      Link.l2_sendto(node, last_nid, dest_nid, datagram)
    else:
      pass

 # April 28, 2016
Ejemplo n.º 3
0
def connect(Y, S):

	# global variables
	global node

	dest_nid = Y
	string = {}
	string['code'] = '20'
	string['source_nid'] = str(node.GetNID())
	string['SID'] = S
	data = json.dumps(string)
	Transport.l4_sendto(node, dest_nid, data)
Ejemplo n.º 4
0
    def run(self):
        # Initialize and start the log thread
        routing_logging.init_log_thread()

        ROUTING_LOG.info("Running the routing instance...")

        # Get mac address of the network interface
        node_mac = Transport.get_mac(DEV)
        # Get a list of neighbors MAC addresses to be accepted (if the TOPOLOGY_FLAG is True).
        topology_neighbors = self.get_topology_neighbors(node_mac)
        # Creating a transport for communication with a virtual interface
        app_transport = Transport.VirtualTransport()
        # Creating a transport for communication with network physical interface
        raw_transport = Transport.RawTransport(DEV, node_mac,
                                               topology_neighbors)
        # Create a RouteTable object
        table = RouteTable.Table(node_mac)

        # Create data handler thread to process all incoming and outgoing messages
        data_handler = DataHandler.DataHandler(app_transport, raw_transport,
                                               table)

        # Creating thread for live configuration / interaction with the running program
        uds_server = RoutingManager.Manager(table)

        try:
            # Start data handler thread
            data_handler.run()

            # Start uds_server thread
            uds_server.start()

            while True:
                packet = app_transport.recv_from_app()
                data_handler.app_handler.process_packet(packet)

        # Catch SIGINT signal, raised by the daemon
        except KeyboardInterrupt:
            # Stop the handlers
            data_handler.stop_threads()

            # Stop UDS server
            uds_server.quit()

            # Stop the log thread
            routing_logging.stop_log_thread()

        return 0
Ejemplo n.º 5
0
    def run(self):
        print("Starting " + self.name)
        if not refine:
            #Setting up a new calculation object, data is saved in self.calc
            self.calc = Transport.Calculation(self.data.split())
            print("Setting up matrices")

            # Modifying structure, repeating leads and making matrices
            error = self.calc.setupMatrices()
            if not error:
                print("Starting calculation")
                # Calculating the electronic transport
                error = self.calc.calcTransport()
        else:
            print("Starting calculation")
            #Refinement reuses already defined Calculation object with new input data
            try:
                error = self.calc.calcTransport(self.data.split())
            except:
                print('Transport refinement failed.')

        if (not error):
            print("Transport thread %s complete" % self.name)
            msg = formatTransport(self.calc.energy, self.calc.transmission)
            sendMessage(msg, TRANSPORT_COMPLETE)

            fig = Plot([self.calc.energy], [self.calc.transmission])
            filepath, err = SaveImage('Transport', fig, self.calc.energy,
                                      self.calc.transmission)
            if (not err):
                sendMessage(filepath.absolute().as_posix(), IMAGE_COMPLETE)
        else:
            print("something went wrong in transport calculations")
            sendMessage("something went wrong in transport calculations",
                        ERROR)
def biodigestorNPV0(vector,dict_t=dict_total,lam = 1,multiJ =False,full=False,printt=False,pen=True):
    active_farms= vector[5:12] 
    active_farms = [0 if num<1 or num==False  else 1 for num in active_farms]
    if printt:
        [distance, wIn, total_solids_perc, wComp,Tpath] = T.load_data(*active_farms,printt)
    else:
        [distance, wIn, total_solids_perc, wComp,TPath] = dict_T[tuple(active_farms)]

    # Tdig = vector[2]
    [W_a, typ, V_d, G_in, G_comp, digOut, digOut_comp] = digester(wIn,wComp)

    V_g = B.biomethane(G_in, G_comp) #biomethane
    #bg = B.biomethane_validation(kilos, wComp)
    f_p = B.biofertilizer(digOut) 
    ghg_r, ghg_c = B.ghg(W_a, wComp, G_in, G_comp) #ghg_r: released gas, ghg_c: captured gas
    bgm_total = B.bgm_cost(G_comp, G_in, digOut)
    working_days = dict_t['working_days']
    V_g =V_g*working_days
    ghg = pd.DataFrame()
    ghg['ghg_lf']=ghg_r
    ghg['ghg_tech']=ghg_c
    ghg['gas']= ['CH4','CO2','NOX','SOX']
    list_ghg = []
    for gas in ['CH4','CO2','NOX','SOX']:
        list_ghg.append(ghg[ghg['gas']==gas].values.flatten().tolist())
    list_ghg = do_all_list_cp(W_a,distance,list_ghg)
    
    n_g = vector[1]
    V_gburn = vector[0]*V_g
    debt_level = vector[2]

    V_cng_p = vector[3]
    e_priceSS = vector[4]
    # farmer_npv(n_g,V_gburn,V_d,typ,distance_total,f_p,V_g,debt_level,e_c,e_priceB,e_priceS,f_used,p_bf)
    return -farmer_npv(n_g,V_gburn,V_cng_p,V_d,typ,distance,f_p,V_g,debt_level,e_c,e_priceB,e_priceSS,f_used,p_bf,printt,pen)
Ejemplo n.º 7
0
    def handle_reliable_data_packet_monitoring_mode(self, src_mac, dsr_message,
                                                    packet):
        # Send back the ACK on the received packet in ALL cases
        self.arq_handler.send_ack(dsr_message, src_mac)

        if dsr_message.id in self.reliable_packet_ids:
            # Send the ACK back anyway, but do nothing with the message itself
            DATA_LOG.info(
                "The Data Packet with this ID has been already processed. Sending the ACK back."
            )
            return None

        self.reliable_packet_ids.append(dsr_message.id)

        # Get src_ip, dst_ip from the incoming packet
        src_ip, dst_ip, packet = Transport.get_l3_addresses_from_packet(packet)

        # Check the destination address if it's inside or outside the network
        dst_ip = self.gateway_handler.check_destination_address(dst_ip)

        # Generate and send back a reward message
        self.reward_send_handler.send_reward(dst_ip, src_mac)

        # If the dst_ip matches the node's ip, send data to the App
        if dst_ip in self.table.current_node_ips:
            DATA_LOG.debug(
                "Sending packet to the App... SRC_IP: %s, DST_IP: %s", src_ip,
                dst_ip)
            self.app_handler_thread.send_up(packet)

        # In all other cases, discard the packet
        else:
            DATA_LOG.debug(
                "This data packet is not for me. Discarding the data packet, "
                "since in Monitoring Mode. Dsr header: %s", dsr_message)
Ejemplo n.º 8
0
def biodigestor(DV2_ng,printt=False,pen=True):
    #Use printt to print the text within your modules, when running the optimization it should be set to False
    #Use pen to penalize the function contraints being violated, when running the optimization it should be set to True
    # DOE_n = DOE_n+1
    # print('Design of experiment #%.0f' % (DOE_n))
    #Optimal latitude and longitude for Digestor
    #Digest_location = T.digestor_loc

    #This loads the respective farms - 1 is active, 0 is inactive. Total farms must be at least 3 active (required by annealing)
    #TOTAL_SOLIDS PERCENTAGE IS NOT USED
    vector = [4.83662871e-01, 1.00000000e+00, 2.62359775e+01, 
            1.11820675e-03, 1.00000000e+00, 0.00000000e+00,0.00000000e+00, 
            1.00000000e+00, 0.00000000e+00, 1.00000000e+00,0.00000000e+00]
    print('vector',vector)
    active_farms= vector[4:11] 
    active_farms = [0 if num<1 else 1 for num in active_farms ]
    # [distance, wIn, total_solids_perc, wComp] = T.load_data(1,1,1,1,1,1,1)
    # [distance, wIn, total_solids_perc, wComp] = T.load_data(*active_farms,printt)
    # if sum(active_farms)>2:
    if printt:
        [distance, wIn, total_solids_perc, wComp] = T.load_data(*active_farms,printt)
    else:
        [distance, wIn, total_solids_perc, wComp] = dict_T[tuple(active_farms)]
    
    #output from digester -- will return 9 values & print to console
    Tdig = vector[2]
    
    [W_a, typ, V_d, G_in, G_comp, digOut, digOut_comp] = digester(wIn,wComp,Tdig)
    # H_needed = JtokWh(H_needed*1000)
    # print('----')
    
    #biogas module
    V_g = B.biomethane(G_in, G_comp) #biomethane
    #bg = B.biomethane_validation(kilos, wComp)
    f_p = B.biofertilizer(digOut) 
    ghg_r, ghg_c = B.ghg(W_a, wComp, G_in, G_comp) #ghg_r: released gas, ghg_c: captured gas
    bgm_total = B.bgm_cost(G_comp, G_in, digOut)
    
    #COST Module
    V_g =V_g*working_days
    ghg = pd.DataFrame()
    ghg['ghg_lf']=ghg_r
    ghg['ghg_tech']=ghg_c
    ghg['gas']= ['CH4','CO2','NOX','SOX']
    list_ghg = []
    for gas in ['CH4','CO2','NOX','SOX']:
        list_ghg.append(ghg[ghg['gas']==gas].values.flatten().tolist())
    list_ghg = do_all_list_cp(W_a,distance,list_ghg)
    
    n_g = DV2_ng
    #print("n_g",n_g) #DV1
    V_gburn = vector[0]*V_g
    #print('vector[0]',vector[0])
    debt_level = vector[3]
    
    return -farmer_npv(n_g,V_gburn,V_d,typ,distance,f_p,V_g,debt_level,e_c,e_priceB,f_used,p_bf,printt,pen)
Ejemplo n.º 9
0
 def SendAndReceive(self):
     packet_send = self.PackPacket()
     packet_receive = Transport.SocketTransport(packet_send, self.dest_host, self.sn)
     if packet_receive == None: ## time out
         return -2
     status = self.ParsePacket(packet_receive)
     if status == None:
         return -1
     else:
         return status
Ejemplo n.º 10
0
 def SendAndReceive(self):
     packet_send = self.PackPacket()
     packet_receive = Transport.SocketTransport(packet_send, '0.0.0.0',
                                                self.sn)
     if packet_receive == None:
         return -2
     status = self.ParsePacket(packet_receive)
     if status == None:
         return -1
     else:
         return status
Ejemplo n.º 11
0
 def SendAndReceive(self):
     packet_send = self.PackPacket()
     packet_receive = Transport.SocketTransport(packet_send, self.dest_host,
                                                self.sn)
     if packet_receive == None:  ## time out
         return [-2, self.loglength]
     status = self.ParsePacket(packet_receive)
     if status == None:
         return [-1, self.loglength]
     else:
         return [status, self.loglength]
Ejemplo n.º 12
0
    def run(self):

        routing_logging.init_log_thread()

        ROUTING_LOG.info("Running the routing instance...")

        node_mac = Transport.get_mac(DEV)

        topology_neighbors = self.get_topology_neighbors(node_mac)

        app_transport = Transport.VirtualTransport()

        raw_transport = Transport.RawTransport(
            DEV, node_mac, topology_neighbors)

        table = RouteTable.Table(node_mac)

        data_handler = DataHandler.DataHandler(
            app_transport, raw_transport, table)

        uds_server = RoutingManager.Manager(table)

        try:

            data_handler.run()

            uds_server.start()

            while True:
                packet = app_transport.recv_from_app()
                data_handler.app_handler.process_packet(packet)

        except KeyboardInterrupt:

            data_handler.stop_threads()

            uds_server.quit()

            routing_logging.stop_log_thread()

        return 0
Ejemplo n.º 13
0
    def handle_reliable_data_packet(self, src_mac, dsr_message, packet):
        # Send back the ACK on the received packet in ALL cases
        self.arq_handler.send_ack(dsr_message, src_mac)

        if dsr_message.id in self.reliable_packet_ids:
            # Send the ACK back anyway, but do nothing with the message itself
            DATA_LOG.info(
                "The Data Packet with this ID has been already processed. Sending the ACK back."
            )
            return None

        self.reliable_packet_ids.append(dsr_message.id)

        # Get src_ip, dst_ip from the incoming packet
        src_ip, dst_ip, packet = Transport.get_l3_addresses_from_packet(packet)

        # Check the destination address if it's inside or outside the network
        dst_ip = self.gateway_handler.check_destination_address(dst_ip)

        # Generate and send back a reward message
        self.reward_send_handler.send_reward(dst_ip, src_mac)

        # If the dst_ip matches the node's ip, send data to the App
        if dst_ip in self.table.current_node_ips:
            DATA_LOG.debug(
                "Sending packet to the App... SRC_IP: %s, DST_IP: %s", src_ip,
                dst_ip)
            self.app_handler_thread.send_up(packet)

        # Else, try to find the next hop in the route table
        else:
            next_hop_mac = self.table.get_next_hop_mac(dst_ip)
            DATA_LOG.debug(
                "IncomingTraffic: For DST_IP: %s found a next_hop_mac: %s",
                dst_ip, next_hop_mac)
            DATA_LOG.debug("Current entry: %s", self.table.get_entry(dst_ip))

            # If no entry is found, put the packet to the initial AppQueue
            if next_hop_mac is None:
                self.app_handler_thread.send_back(packet)

            # Else, forward the packet to the next_hop. Start a reward wait thread, if necessary.
            else:
                dsr_message.hop_count += 1
                # Send the raw data with dsr_header to the next hop using ARQ
                self.arq_handler.arq_send(dsr_message, [next_hop_mac],
                                          payload=packet)

                # Process the packet through the reward_wait_handler
                self.reward_wait_handler.wait_for_reward(dst_ip, next_hop_mac)
Ejemplo n.º 14
0
def main():
    AddSystemPath(
        '/Users/jlconlin/Documents/Education/Convergence/Code/python/SourceFiles'
    )
    import Particle
    import Transport
    xs, Histories, Width = Parse()
    Neutron = Particle.Particle(Position=(1, 1, 1))
    #   print "Neutron Position: %r" %(Neutron.Position,)

    import Arnoldi
    Transporter = Transport.Transport(Throw, xs, Width)
    first = Arnoldi.Arnoldi(Histories, Transporter, 3)
    #   first.Transport(Neutron,7)
    first.Iterate()
Ejemplo n.º 15
0
    def __init__(self, truck_type, TransferStation, Processing_Facility,
                 Transfer_Distance, Total_tonnes_collected):
        self.truck_type = truck_type
        self.Transfer_Distance = Transfer_Distance
        self.Waste_stream = 0
        self.Facility_Name = 0

        self.fuel_emission_class = FE.Fuel_Emissions()
        self.truck_class = TR.trucks()

        self.fuel_type = self.truck_class.transfer_trucks[
            self.truck_type]["Fuel_Type"]
        self.fuel_emission_class.derivative_quantities(self.fuel_type)
        self.tCO2_per_km = self.fuel_emission_class.tCO2_per_km
        print(self.fuel_type, self.tCO2_per_km)
        return
Ejemplo n.º 16
0
    def send_raw_hello(self):
        # Try to get L3 ip address (ipv4 or ipv6) assigned to the node, if there are such ones
        node_ips = Transport.get_l3_addresses_from_interface()

        if self.current_node_ips != node_ips:
            # Update entries in RouteTable
            self.update_ips_in_route_table(node_ips)

            # Copy the current list of ips and check for the default routes address in order to properly set
            # the gw_mode value
            if Messages.DEFAULT_ROUTE in node_ips:
                self.message.gw_mode = 1
                ips = node_ips[:-1]

            else:
                self.message.gw_mode = 0
                ips = node_ips

            if ips:
                # Check if the node has IPv4 address assigned
                try:
                    inet_aton(ips[0])
                    self.message.ipv4_count = 1
                    self.message.ipv4_address = ips[0]

                    # If there are some IPv6 addresses in the list -> write them as well
                    self.message.ipv6_count = len(ips[1:])
                    self.message.ipv6_addresses = ips[1:]

                except sock_error:
                    # Otherwise, assign IPv6 addresses
                    self.message.ipv4_count = 0
                    self.message.ipv6_count = len(ips)
                    self.message.ipv6_addresses = ips

            else:
                self.message.ipv4_count = 0
                self.message.ipv6_count = 0

        NEIGHBOR_LOG.debug("Sending HELLO message:\n %s", self.message)

        self.raw_transport.send_raw_frame(self.broadcast_mac, self.message, b"")
        self.message.tx_count += 1
        # Update the current list of ips
        self.current_node_ips = node_ips
Ejemplo n.º 17
0
    def send_raw_hello(self):

        node_ips = Transport.get_l3_addresses_from_interface()

        if self.current_node_ips != node_ips:

            self.update_ips_in_route_table(node_ips)

            if Messages.DEFAULT_ROUTE in node_ips:
                self.message.gw_mode = 1
                ips = node_ips[:-1]

            else:
                self.message.gw_mode = 0
                ips = node_ips

            if ips:

                try:
                    inet_aton(ips[0])
                    self.message.ipv4_count = 1
                    self.message.ipv4_address = ips[0]

                    self.message.ipv6_count = len(ips[1:])
                    self.message.ipv6_addresses = ips[1:]

                except sock_error:

                    self.message.ipv4_count = 0
                    self.message.ipv6_count = len(ips)
                    self.message.ipv6_addresses = ips

            else:
                self.message.ipv4_count = 0
                self.message.ipv6_count = 0

        NEIGHBOR_LOG.debug("Sending HELLO message:\n %s", self.message)

        self.raw_transport.send_raw_frame(self.broadcast_mac, self.message, "")
        self.message.tx_count += 1

        self.current_node_ips = node_ips
Ejemplo n.º 18
0
def createTransportSurrogateModel(dict_total=dict_total):
    x = [[0, 1]] * 7
    allx = list(itertools.product(*x))
    dict_T2 = {}
    count = 1
    for x in allx:
        if count % 4 == 0:
            print(count / 128)
        if sum(x) > 0:
            dict_T2[x] = T.transportDFS(x[0], x[1], x[2], x[3], x[4], x[5],
                                        x[6], dict_total)
        else:
            dict_T2[x] = [inf, 0, 0, [1, 0, 0], 0]
        count = count + 1
    return dict_T2


# dict_T = createTransportSurrogateModel()
# with open('full_transp.p', 'wb') as file:
#       file.write(pickle.dumps(dict_T))
Ejemplo n.º 19
0
 def send_packet_with_arq(self, packet, dst_ip, next_hop_mac):
     # Check if the packet should be transmitted reliably
     upper_proto, src_port, dst_port = Transport.get_upper_proto_info(
         packet)
     if (upper_proto in ARQ_LIST) and (src_port in ARQ_LIST[upper_proto] or
                                       dst_port in ARQ_LIST[upper_proto]):
         # Transmit the packet reliably
         DATA_LOG.debug(
             "This packet should be transmitted reliably: %s, %s, %s",
             upper_proto, src_port, dst_port)
         # Create reliable dsr data message with proper values
         dsr_message = Messages.ReliableDataPacket()
         dsr_message.hop_count = 1
         # Send the message using ARQ
         self.arq_handler.arq_send(dsr_message, [next_hop_mac],
                                   payload=packet)
         # Process the packet through the reward_wait_handler
         self.reward_wait_handler.wait_for_reward(dst_ip, next_hop_mac)
     # Else, transmit the data packet normally
     else:
         self.send_packet(packet, dst_ip, next_hop_mac)
Ejemplo n.º 20
0
 def __init__(self, truck_type, 
              Distance_per_lift, Distance_to_TransferStation, 
              Total_tonnes_collected, Number_bin_per_hhold, number_hhold):
     self.truck_type = truck_type
     self.Distance_per_lift= Distance_per_lift
     self.Distance_to_TransferStation = Distance_to_TransferStation
     self.Total_tonnes_collected = Total_tonnes_collected
     self.Number_bin_per_hhold = Number_bin_per_hhold
     self.number_hhold = number_hhold
     self.Waste_stream = 0
     self.Facility_Name = 0
     self.Waste_Composition = 0
     self.Lift_rate = 0
     
     self.fuel_emission_class = FE.Fuel_Emissions()
     self.truck_class = TR.trucks() 
     
     self.fuel_type = self.truck_class.collection_trucks[self.truck_type]["Fuel_Type"]
     self.fuel_emission_class.derivative_quantities(self.fuel_type)
     self.tCO2_per_km = self.fuel_emission_class.tCO2_per_km
     print (self.fuel_type, self.tCO2_per_km)
     return
Ejemplo n.º 21
0
    def handle_data_packet_monitoring_mode(self, src_mac, dsr_message, packet):
        # Get src_ip, dst_ip from the incoming packet
        src_ip, dst_ip, packet = Transport.get_l3_addresses_from_packet(packet)

        # Check the destination address if it's inside or outside the network
        dst_ip = self.gateway_handler.check_destination_address(dst_ip)

        # Generate and send back a reward message
        self.reward_send_handler.send_reward(dst_ip, src_mac)

        # If the dst_ip matches the node's ip, send data to the App
        if dst_ip in self.table.current_node_ips:
            DATA_LOG.debug(
                "Sending packet to the App... SRC_IP: %s, DST_IP: %s", src_ip,
                dst_ip)
            self.app_handler_thread.send_up(packet)

        # In all other cases, discard the packet
        else:
            DATA_LOG.debug(
                "This data packet is not for me. Discarding the data packet, "
                "since in Monitoring Mode. Dsr header: %s", dsr_message)
Ejemplo n.º 22
0
    def handle_data_packet(self, src_mac, dsr_message, packet):
        # Get src_ip, dst_ip from the incoming packet
        src_ip, dst_ip, packet = Transport.get_l3_addresses_from_packet(packet)

        # Check the destination address if it's inside or outside the network
        dst_ip = self.gateway_handler.check_destination_address(dst_ip)

        # Generate and send back a reward message
        self.reward_send_handler.send_reward(dst_ip, src_mac)

        # If the dst_ip matches the node's ip, send data to the App
        if dst_ip in self.table.current_node_ips:
            DATA_LOG.debug(
                "Sending packet to the App... SRC_IP: %s, DST_IP: %s", src_ip,
                dst_ip)
            self.app_handler_thread.send_up(packet)

        # Else, try to find the next hop in the route table
        else:
            next_hop_mac = self.table.get_next_hop_mac(dst_ip)
            DATA_LOG.debug(
                "IncomingTraffic: For DST_IP: %s found a next_hop_mac: %s",
                dst_ip, next_hop_mac)
            DATA_LOG.debug("Current entry: %s", self.table.get_entry(dst_ip))

            # If no entry is found, put the packet to the initial AppQueue
            if next_hop_mac is None:
                self.app_handler_thread.send_back(packet)

            # Else, forward the packet to the next_hop. Start a reward wait thread, if necessary.
            else:
                dsr_message.hop_count += 1
                # Send the raw data with dsr_header to the next hop
                self.raw_transport.send_raw_frame(next_hop_mac, dsr_message,
                                                  packet)

                # Process the packet through the reward_wait_handler
                self.reward_wait_handler.wait_for_reward(dst_ip, next_hop_mac)
Ejemplo n.º 23
0
#print("Уся колода:\n")
#Coloda.showall()

#print("\nКарта у 9 позиції\n")
#Coloda.findbyindex(9)

#print("\nОдна випадкова карта: \n")
#Coloda.getonecard()

#print("\nШість випадкових карт:\n")
#Coloda.getsixcards()

#print("\nПеремішування колоди: \n")
#Coloda.mixing_the_Deck()


#Task5
#print("Task5:\n")
#word = Vocabulary.Vocabulary()
#print("Усі слова словника: ", word.showVocabulary())
#print(word.translate())


#Task6
#print("Task6:\n")
Lancer = Transport.Car()
Lancer.setval(15000.0)
Lancer.setspeed(300)
Lancer.setyear(2004)
Lancer.setcoord("12:04:255")
Lancer.showCar()
Ejemplo n.º 24
0
        self.tCO2_per_km = self.fuel_emission_class.tCO2_per_km
        print(self.fuel_type, self.tCO2_per_km)
        return
##############################################################

    def total_emissions(self, ):
        self.Distance_per_run = self.Transfer_Distance
        print(self.fuel_type, self.tCO2_per_km)
        self.tCO2 = self.Transfer_Distance * self.tCO2_per_km
        return

    def costs(self, ):
        self.transfer_costs = 0


################################################################################################################
if __name__ == "__main__":
    Trucks = TR.trucks()
    for transfer_truck in Trucks.transfer_trucks:
        Transfer_Distance = 5
        Total_tonnes_transferred = 1
        Transfer_Station = "ManlyDam"
        Processing_Facility = "The Universe"

        TT = Transfer(transfer_truck, Transfer_Station, Processing_Facility,
                      Transfer_Distance, Total_tonnes_collected)
        TT.total_emissions()
        TT.costs()
        print("total emissions in t CO2 = ", TT.tCO2, " total transfercost = ",
              TT.transfer_costs)
Ejemplo n.º 25
0
def main (argv):

	#check for proper input
 	if len(sys.argv) != 3:
		PrintUsage()

    # good input, start program
	else:
		run = 1

  	# initialize node object in physical layer
  	node = Physical.InitializeTopology(sys.argv[1], sys.argv[2])

	#start listen threads
	Link.start_listener(node)


	# begin loop
	while(run == 1):

		# clear screen
		os.system('clear')

		# prompt for input
		message = raw_input("Enter A Command, or 'menu' to see all options: ")

		# for testing node at physical layer
		if (message == "PrintStatus"):
			node.PrintStatus()

		# for testing, send simple text message
		if (message == "send message"):
			dest_nid = raw_input("Enter NID of target: ")
			data = raw_input("Enter Message: ")
			Transport.l4_sendto(node, dest_nid, data)

		# print menu to screen
		if (message == "MENU") or (message == "Menu") or (message == "menu"):
			menu()

		# start new service
		if (message == '1'):
			P = raw_input("Enter the maximum number of connections this service point will accept: ")
			start_service(P)

		# stop service
		if (message == '2'):
			S = raw_input("Enter the Service ID of the node you wish to stop service with: ")
			stop_service(S)

		# connect to node x
		if (message == '3'):
			Y = raw_input("Enter the node you would like to connect to: ")
			S = raw_input("Enter the SID of the node: ")
			W = raw_input("Enter a value between 1-5 to set the window for packets in flight")
			connect(Y, S, W)

		# close connection with node x
		if (message == '4'):
			C = raw_input("Enter the CID of the connection you would like to close: ")
			close(C)

		# download from node x
		if (message == '5'):
			C = raw_input("Enter the CID of the peer from whom you would like to download: ")
			F = raw_input("Enter the name of the file you would like to download")
			download(C, F)

		# set garbler probability
		if (message == '6'):
			L = raw_input("Set the probability of packet loss (1-100): ")
			C = raw_input("Set the probability of packet corruption (1-100): ")
			set_garbler(L, C)

		# display next hop data
		if (message == '7'):
			route_table(node)

		# down link to node x
		if (message == '8'):
			N = raw_input("Enter the node with whom you would like to down a link: ")
			link_down(node, N)

		# up link to node x
		if (message == '9'):
			N = raw_input("Enter the node with whom you would like to up a link: ")
			link_up(node, N)

		# exit program
		if (message == 'Exit') or (message == 'Exit') or (message == 'exit'):
			run = 0
Ejemplo n.º 26
0
    def __init__(
        self,
        Facility_Name,
        facility_type,
        Distance_per_lift,
        Distance_to_TransferStation,
        Total_tonnes_collected,
        Number_bin_per_hhold,
        number_hhold,
        Transfer_Station,
        Processing_Facility,
        Transfer_Distance,
    ):

        self.Facility_Name = Facility_Name
        self.facility_type = facility_type
        self.Distance_per_lift = Distance_per_lift
        self.Distance_to_TransferStation = Distance_to_TransferStation
        self.Total_tonnes_collected = Total_tonnes_collected
        self.Number_bin_per_hhold = Number_bin_per_hhold
        self.number_hhold = number_hhold
        self.Transfer_Station = Transfer_Station
        self.Processing_Facility = Processing_Facility
        self.Transfer_Distance = Transfer_Distance

        ###########################################################################################################
        #processing facility

        #grab composition
        self.waste_composition_class = Co.Waste_Composition()
        #grab mat diversion per facility
        self.Material_Diversion_class = WF.Facility_Type()

        self.WP = Prcss.Processing(self.Facility_Name,
                                   self.waste_composition_class,
                                   self.Material_Diversion_class)
        self.WP.Material_Recovery(facility_type)

        self.total_landfill_in_t = self.WP.total_for_landfill
        self.total_processed = self.WP.total_processed
        print("total landfill in t = ", self.WP.total_for_landfill,
              " total processed = ", self.WP.total_processed)

        ###########################################################################################################
        #waste stream
        self.WasteCompo = self.waste_composition_class.Waste_Composition
        self.WS = wststream.WasteStream(self.WasteCompo)

        #self.WS.verification()
        for compo in self.WS.Waste_Composition:
            self.WS.landfill_emissions_per_t(compo)
            print(compo, " total emissions per t = ",
                  self.WS.total_emission_per_t)

        ###########################################################################################################
        #trip from households to transfer station
        self.Trucks = TR.trucks()
        for collection_truck in self.Trucks.collection_trucks:
            self.TRP = Trp.Trip(collection_truck, self.Distance_per_lift,
                                self.Distance_to_TransferStation,
                                self.Total_tonnes_collected,
                                self.Number_bin_per_hhold, self.number_hhold)
            self.TRP.total_emissions()
            self.TRP.costs()
            print("Collection truck = ", collection_truck,
                  " total emissions in t CO2 = ", self.TRP.tCO2,
                  " total liftcost = ", self.TRP.lift_costs)

        ###########################################################################################################
        #transfert from transfert station to processing facility
        for transfer_truck in self.Trucks.transfer_trucks:
            self.TRANS = Trf.Transfer(transfer_truck, self.Transfer_Station,
                                      self.Processing_Facility,
                                      self.Transfer_Distance,
                                      self.Total_tonnes_collected)
            self.TRANS.total_emissions()
            self.TRANS.costs()
            print("transfer truck = ", transfer_truck,
                  " total emissions in t CO2 = ", self.TRANS.tCO2,
                  " total transfercost = ", self.TRANS.transfer_costs)

        return
Ejemplo n.º 27
0
 def transport(self):
     Transport.run_program(self.app_log)
Ejemplo n.º 28
0
    def process_packet(self, packet):
        # Get the src_ip and dst_ip from the packet
        try:
            src_ip, dst_ip, packet = Transport.get_l3_addresses_from_packet(
                packet)
        except TypeError:
            DATA_LOG.error(
                "The packet has UNSUPPORTED L3 protocol! Dropping the packet..."
            )
            return 1

        # ## Handle multicast traffic ## #
        # Check if the packet's destination address is IPv6 multicast
        # Always starts from "ff0X::",
        # see https://en.wikipedia.org/wiki/IPv6_address#Multicast_addresses
        if dst_ip[:2] == "ff":
            DATA_LOG.info("Multicast IPv6: %s", dst_ip)
            # Create a broadcast dsr message
            dsr_message = Messages.BroadcastPacket()
            dsr_message.broadcast_ttl = 1
            # Put the dsr broadcast id to the broadcast_list
            self.broadcast_list.append(dsr_message.id)
            # Broadcast it further to the network
            self.raw_transport.send_raw_frame(self.broadcast_mac, dsr_message,
                                              packet)
            return None

        # Check if the packet's destination address is IPv4 multicast or broadcast.
        # The IPv4 multicasts start with either 224.x.x.x or 239.x.x.x
        # See: https://en.wikipedia.org/wiki/Multicast_address#IPv4
        elif dst_ip[:3] == "224" or dst_ip[:3] == "239":
            DATA_LOG.info("Multicast IPv4: %s", dst_ip)
            # Create a broadcast dsr message
            dsr_message = Messages.BroadcastPacket()
            dsr_message.broadcast_ttl = 1
            # Put the dsr broadcast id to the broadcast_list
            self.broadcast_list.append(dsr_message.id)
            # Broadcast it further to the network
            self.raw_transport.send_raw_frame(self.broadcast_mac, dsr_message,
                                              packet)
            return None

        # Check if the packet's destination address is IPv4 broadcast.
        # The IPv4 broadcasts ends with .255
        # See: https://en.wikipedia.org/wiki/IP_address#Broadcast_addressing
        elif dst_ip[-3:] == "255":
            DATA_LOG.info("Broadcast IPv4: %s", dst_ip)
            # Create a broadcast dsr message
            dsr_message = Messages.BroadcastPacket()
            dsr_message.broadcast_ttl = 1
            # Put the dsr broadcast id to the broadcast_list
            self.broadcast_list.append(dsr_message.id)
            # Broadcast it further to the network
            self.raw_transport.send_raw_frame(self.broadcast_mac, dsr_message,
                                              packet)
            return None

        # ## Handle Unicast Traffic ## #
        # Check the destination address if it's inside or outside the network
        dst_ip = self.gateway_handler.check_destination_address(dst_ip)
        # Try to find a mac address of the next hop where the packet should be forwarded to
        next_hop_mac = self.table.get_next_hop_mac(dst_ip)

        # If next_hop_mac is None, it means that there is no current entry with dst_ip.
        # In that case, start a PathDiscovery procedure
        if next_hop_mac is None:
            DATA_LOG.info(
                "No such Entry with given dst_ip in the table. Starting path discovery..."
            )
            # ## Initiate PathDiscovery procedure for the given packet ## #
            self.path_discovery_handler.run_path_discovery(
                src_ip, dst_ip, packet)

        # Else, the packet is unicast, and has the corresponding Entry.
        # Check if the packet should be transmitted using ARQ.
        # Forward packet to the next hop. Start a thread for waiting an ACK with reward.
        else:
            DATA_LOG.debug("For DST_IP: %s found a next_hop_mac: %s", dst_ip,
                           next_hop_mac)
            self.send_unicast_packet(packet, dst_ip, next_hop_mac)
Ejemplo n.º 29
0
def main (argv):

	# global variables
	global node

	#check for proper input
 	if len(sys.argv) != 3:
		PrintUsage()

    # good input, start program
	else:
		run = 1

  	# initialize node object in physical layer
  	node = Physical.InitializeTopology(sys.argv[1], sys.argv[2])

  	# wait for node to propagate
  	time.sleep(2)

	#start listen threads
	Link.start_listener(node)

	# begin loop
	while(run == 1):

		# clear screen
		os.system('clear')

		# print menu
		menu()

		# prompt for input
		message = raw_input("Enter your selection: ")

		# start new service
		if (message == '1'):
			P = raw_input("Enter the maximum number of connections this service point will accept: ")
			start_service(P)

		# stop service
		if (message == '2'):
			S = raw_input("Enter the Service ID of the node you wish to stop service with: ")
			stop_service(S)

		# list service points
		if (message == '3'):
			list_service_points()

		# connect to node x
		if (message == '4'):
			Y = raw_input("Enter the node you would like to connect to: ")
			S = raw_input("Enter the SID of the node: ")
			#connect(Y, S)
			thread.start_new_thread(connect, (Y,S))

		# close connection with node x
		if (message == '5'):
			C = raw_input("Enter the CID of the connection you would like to close: ")
			close(C)

		# download from node x
		if (message == '6'):
			C = raw_input("Enter the CID of the peer from whom you would like to download: ")
			F = raw_input("Enter the name of the file you would like to download: ")
			thread.start_new_thread(download, (C,F))

		# set garbler probability
		if (message == '7'):
			L = raw_input("Set the probability of packet loss (1-100): ")
			C = raw_input("Set the probability of packet corruption (1-100): ")
			set_garbler(L, C)

		# display next hop data
		if (message == '8'):
			route_table(node)

		# down link to node x
		if (message == '9'):
			N = raw_input("Enter the node with whom you would like to down a link: ")
			link_down(N)

		# up link to node x
		if (message == '10'):
			N = raw_input("Enter the node with whom you would like to up a link: ")
			link_up(N)

		# for testing, send simple text message
		if (message == "11"):
			dest_nid = raw_input("Enter NID of target: ")
			text = raw_input("Enter Text Message: ")
			string = {}
			string['code'] = '10'
			string['message'] = text
			data = json.dumps(string)
			Transport.l4_sendto(node, dest_nid, data)

		# for testing node at physical layer
		if (message == "12"):
			node.PrintStatus()

		# exit program
		if (message == '13') or (message == 'Exit') or (message == 'exit'):
			run = 0
Ejemplo n.º 30
0
def l5_recvfrom(source_nid, dest_nid, data):

	# global variables
	global node

	SID_LIST = {}
	CONN_LIST = {}
	MY_CONNS = {}

	# open file and look for SID_LIST
	if os.path.isfile('sid_data'):
		with open('sid_data', 'r') as fp1:
			SID_LIST = json.load(fp1)
			fp1.close()

	# open file and look for CONN_LIST
	if os.path.isfile('conn_data'):
		with open('conn_data', 'r') as fp2:
			CONN_LIST = json.load(fp2)
			fp2.close()

	# open file and look for MY_CONNS
	if os.path.isfile('my_conns'):
		with open('my_conns', 'r') as fp3:
			MY_CONNS = json.load(fp3)
			fp3.close()			

	data = json.loads(data)
	code = data['code']

	# if incoming message is a text message
	if (code == '10'):
		text = data['message']
		print '\n'
		os.system('clear')
		print "text: ", text
		print "Press enter to continue..."

	# if incoming message is a connection request
	elif (code == '20'):
		dest_nid = data['source_nid']
		SID = data['SID']
		CID = randint(1000, 9999)

		if (SID in SID_LIST):

			if int(len(CONN_LIST)) < int(SID_LIST[SID]):
				CONN_LIST[CID] = dest_nid
				string = {}
				string['code'] = '30'
				string['CID'] = str(CID)
				string['source_nid'] = str(node.GetNID())
				data = json.dumps(string)
			else:
				string = {}
				string['code'] = '40'
				data = json.dumps(string)
		else:
			string = {}
			string['code'] = '50'
			data = json.dumps(string)

		Transport.l4_sendto(node, dest_nid, data)
		#print ("Press enter to continue... ")

	# if incoming message is a connection response
	if (code == '30'):
		print '\n'
		CID = data['CID']
		source_nid = data['source_nid']
		os.system('clear')
		print ("CID: " + CID)
		MY_CONNS[CID] = source_nid

	# if incoming message is a connection response
	if (code == '40'):
		print '\n'
		os.system('clear')
		print 'No connections for that SID available'
		print 'Press enter to continue...'

	# if incoming message is a connection response
	if (code == '50'):
		print '\n'
		os.system('clear')
		print 'SID does not exist'
		print 'Press enter to continue'

	# if incoming message is a connection response
	if (code == '60'):

		print '\n'
		filename = data['filename']
		os.system('clear')
		exists = os.path.isfile(filename)
		if (exists == True):
			os.system('clear')
			print ("yup, it's here. I'll send it!")
			dest_nid = data['source_nid']

			text = ''
			with open(filename, 'rb') as f:
				bytes = f.read()
				encodedbytes = base64.b64encode(bytes)
				text += str(encodedbytes)
			print text

			string = {}
			string['code'] = '70'
			string['message'] = 'Your file has been delivered...'
			string['filename'] = filename
			string['file'] = text
			data = json.dumps(string)

			Transport.l4_sendto(node, dest_nid, data)

		else:
			os.system('clear')
			print ("that file isn't here")
			dest_nid = data['source_nid']
			string = {}
			string['code'] = '80'
			string['message'] = "file " + filename + " does not exist, sorry!"
			data = json.dumps(string)
			Transport.l4_sendto(node, dest_nid, data)


		print ("Press enter to continue... ")

	if (code == '70'):
		os.system('clear')
		answer = data['message']
		print answer
		incoming = data['file']
		filename = data['filename']

		text = base64.b64decode(incoming)
		f = open(filename, 'wb')
		f.write(text)
		f.close()

		print 'Press enter to continue...'

	if (code == '80'):
		os.system('clear')
		answer = data['message']
		print answer
		print 'Press enter to continue...'

	else:
		pass

	# store dict to file for later
	with open('sid_data', 'w') as fp1:
		json.dump(SID_LIST, fp1)
		fp1.close()

	# store dict to file for later
	with open('conn_data', 'w') as fp2:
		json.dump(CONN_LIST, fp2)
		fp2.close()

	# store dict to file for later
	with open('my_conns', 'w') as fp3:
		json.dump(MY_CONNS, fp3)
		fp3.close()