Beispiel #1
0
def sendData(dataloda=[]):

    dataPacketObject = DataPacket()


    packet = dataPacketObject.createDataPacket(dataload)
    return  packet
def start_transmission(queues, transmission_event):
    count = 0
    for i in range(150000):
        count = count + 1
    start_trans = raw_input("Do you want to start Data Transmission?\n")
    if str(start_trans) in ['y', 'Y', 'yes', 'Yes', 'start', 'Start']:
        node_num_transmit = raw_input(
            "Enter the node number to start transmission\n")
        if (int(node_num_transmit) not in neighbor_dict.keys()
                or int(node_num_transmit) == sink_node):
            print "The node number is invalid. Try again."
            return
        else:
            import random
            run_sim_time = raw_input(
                "Enter the time duration for running the simulation\n")
            exec("start_transmit_q = queues.get_from_repository(" + "'" +
                 "q_" + str(node_num_transmit) + "'" + ")")
            transmit_que_obj = queues.get_object_by_name(start_transmit_q)
            sim_time = run_sim_time * 100
            pkt_num = 1
            for sim_time_sec in sim_time:
                data_to_transmit = random.randrange(1023)
                from DataPacket import DataPacket
                data_pkt = DataPacket(data_to_transmit)
                data_pkt.packet_id = generate_uuid()
                print "Data Packet  " + str(pkt_num) + " sent"
                transmit_start_status = queues.put_to_queue(
                    transmit_que_obj, data_pkt)
                pkt_num = pkt_num + 1
            transmission_event.set()
    return True
 def __sendData(self, data):
     retval = 0
     packet = DataPacket(self.__deviceId, data)
     if self.__port.isOpen():
         retval = self.__port.write(packet.getByteCode())
         #print("sendData:", packet.getByteCode())
     else:
         raise SensorException(SERIAL_PORT_ERROR,0)
     return retval
Beispiel #4
0
 def __sendData(self, data):
     retval = 0
     packet = DataPacket(self.__deviceId, data)
     if self.__port.isOpen():
         retval = self.__port.write(packet.getByteCode())
         #print("sendData:", packet.getByteCode())
     else:
         raise SensorException(SERIAL_PORT_ERROR, 0)
     return retval
Beispiel #5
0
def retrieve_status(did):
    packet=DataPacket(id=did,instr=0x01,data=[0x01])
    a=packet.getCharPacket()
    packet.writeToSerial(a)
    time.sleep(0.03)
    temp=packet.readSerial(6)
    ret=[]
    for i in range(0,6):
        ret.append(ord(temp[i]))
        
    return ret[4] 
Beispiel #6
0
    def __sendDataChnk(self, arr, ser):
        dataPacket = DataPacket()
        packedData = dataPacket.createDataPacket(arr)
        # ser.write(packedData)

        # Hexlify dataPkt for verification
    #Calling the Processing Response for ACK/NAK
        if (self.__processPacket(ser,0, packedData))== ERROR_ACK:
            pass
    #Check the WrittePacket data after writing-- On Hexlify
        print('Chunks written.....')
        print(hexlify(packedData))
Beispiel #7
0
 def create_packages(self, file_name: str) -> None:
     byte_list = FileReader.read_file(file_name, CommunicationSettings.data_bytes)
     for index, data in enumerate(byte_list): #Convert words to packages
         self.packages_to_send.append(DataPacket(index, data))
     
     #Create an end of transmition packet and add it to the end of the queue
     end_packet = DataPacket()
     end_packet.mark_as_eot()
     self.packages_to_send.append(end_packet)
     self.stats.min_packages = 2 * len(self.packages_to_send) - 1 
     if CommunicationSettings.logging:
         print(f"Created {len(self.packages_to_send)} packages")
Beispiel #8
0
def serialWritePacketStream(packetStr):
    lst = list(splitToChunks(packetStr, 128))
    time.sleep(0.5)

    print("Size of....: ", len(lst))

    for i in range(0, len(lst)):
        # arr = np.array(lst[i])
        arr = np.array(lst[i])

        dataPacket = DataPacket()
        packedData = dataPacket.createDataPacket(arr)
        return packedData
Beispiel #9
0
    def handle_packets(self) -> None:
        packet = self.recieved_packets.pop(0)

        if isinstance(packet, DataPacket):
            #Scrable packet
            message = packet.to_binary()
            data_packet = DataPacket()
            data_packet.to_packet(
                CommunicationSettings.scramble_message(message))

            is_eot = False
            if data_packet.get_valid():
                #If this is the end of transmition and all packets in the window are valid then recreate the image
                if data_packet.is_eot() and self.all_packets_valid:
                    is_eot = True

                #If the content isn't the same then the error wasn't detected
                if message != data_packet.to_binary():
                    self.stats.undetected_errors += 1
            else:
                self.stats.detected_errors += 1
                self.all_packets_valid = False  #Not all packets in this window were valid

            if is_eot == False:
                self.current_window.append(data_packet.get_data(
                ))  #Add data to the current window if not end of transmition

            #Send a response when the amount of recieved packets is equal to the window size or eot
            if len(self.current_window
                   ) == CommunicationSettings.window_size or is_eot:
                response = ResponsePacket()
                #If all packets in the window were valid add the to the good data
                if self.all_packets_valid:
                    if CommunicationSettings.logging:
                        print(f"{self.name}: Valid window")

                    response.mark_as_not_retransmit()
                    self.good_packets.extend(self.current_window)
                else:
                    if CommunicationSettings.logging:
                        print(f"{self.name}: Invalid window")

                    response.mark_as_retransmit()

                #Clear the window after sending the response
                self.current_window.clear()
                #Reset window retransmition flag
                self.all_packets_valid = True

                if is_eot:
                    self.simulate = False
                    self.recreate_image()

                self.sender.recieve_packet(response)

        else:
            #Is a response packet. That means that we should transmit our last response again
            response = ResponsePacket(data=self.last_response)
            self.sender.recieve_packet(response)
Beispiel #10
0
    def __receiveDataPack(self, length):
        if self.__port.isOpen():
            received = self.__port.read(length)
            #print("dataRec:", received)
            if len(received) == 0:
                raise SensorException(SERIAL_PORT_TIMEOUT, DATA_PACK_ERROR)
            if length == len(received):
                dataPack = DataPacket(received)
                if dataPack.getDeviceId() != self.__deviceId:
                    raise SensorException(ID_ERROR, DATA_PACK_ERROR)
            else:
                raise SensorException(LENGTH_ERROR, DATA_PACK_ERROR)
        else:
            raise SensorException(SERIAL_PORT_ERROR, 0)

        return dataPack.getData()
Beispiel #11
0
def change_led(did,value):
    
    
    cmd=0x03
    
    if value=='TOGGLE':
        cmd = 0x02
    if value == 'ON':
        cmd = 0x01
    if value == 'OFF':
        cmd = 0x00
    packet=DataPacket(id=did,instr=0x02,data=[0x05,cmd])
    a=packet.getCharPacket()
    packet.writeToSerial(a)
    
    return retrieve_status(did)
 def __receiveDataPack(self, length):
     if self.__port.isOpen():
         received = self.__port.read(length)
         #print("dataRec:", received)
         if len(received) == 0:
             raise SensorException(SERIAL_PORT_TIMEOUT,DATA_PACK_ERROR)
         if length == len(received):
             dataPack = DataPacket(received)
             if dataPack.getDeviceId() != self.__deviceId:
                 raise SensorException(ID_ERROR,DATA_PACK_ERROR)   
         else:
             raise SensorException(LENGTH_ERROR,DATA_PACK_ERROR)
     else:
         raise SensorException(SERIAL_PORT_ERROR,0)       
             
     return dataPack.getData()
Beispiel #13
0
 def StopWait(self, chunks):
     for chunk in chunks:
         print "\n"
         while True:
             PACKET = DataPacket(chunk, self.SEQNO, self.CHECKSUM)
             self.sendData(PACKET)
             print "Waiting for Ack #" + str(self.ACKNO)
             try:
                 recvMsg = self.connection.recvfrom(1024)
             except socket.timeout:
                 print "Timeout"
                 continue
             recvGram = pickle.loads(recvMsg[0])
             recvPacket = recvGram  #.packet
             if (type(recvPacket) is AckPacket):
                 print "Received Ack #" + str(recvPacket.ackNo)
                 if (recvPacket.ackNo == self.ACKNO):
                     self.SEQNO = 1 - self.SEQNO
                     # stop timer
                     print "Timer Stopped"
                     break
                 else:
                     print "Unexpected Ack"
                     # stop timer
                     print "Timer Stopped"
                     print "Resending Packet #" + str(self.SEQNO)
             else:
                 print "Received a corrupted packet"
                 # stop timer
                 print "Timer Stopped"
                 print "Resending Packet #" + str(self.SEQNO)
             print "\n"
     print "All Packets are sent successfully"
     print "Closing the server"
Beispiel #14
0
    def send_traffic(self):
        print "Cover traffic"
        self.cover_traffic_rate = 1
        how_often = 1. / self.cover_traffic_rate
        threading.Timer(how_often, self.send_traffic).start()

        # Randomly add and drop nodes from the network
        self.add_node()
        self.drop_node()

        # Randomly generate real data for each time step
        # self.queue_real_data()

        # May need to reset data
        # if len(self.real_data_queue) == 0:
        #    self.seed_queue()

        blacklist = []  # A list of which nodes have sent data in this round
        process_limit = len(self.real_data_queue) - 1
        for i, info in enumerate(self.real_data_queue):
            nodeA = info[0]
            nodeB = info[1]
            packet = info[2]

            # Real traffic can go inter- or intra-clique
            if (nodeA, nodeB) not in blacklist:
                # Intra-clique
                nodeA.send_packet(nodeB, packet)
                blacklist.append((nodeA, nodeB))
                self.real_data_queue[i] = "dirty"  # Mark for removal

            # Additions to the queue go beyond the limit,
            # and should only be processed on the next time step
            if i == process_limit:
                break

        # Remove processed data
        self.real_data_queue = [
            e for e in self.real_data_queue if e != 'dirty'
        ]

        # Dummy nodes for the rest of them
        for cliqueA in self.cliques:
            for nodeA in cliqueA:
                for cliqueB in self.cliques:
                    for nodeB in cliqueB:
                        if cliqueA == cliqueB and (nodeA,
                                                   nodeB) not in blacklist:
                            # Dummy data must only go inter-clique
                            payload = "dummy"
                            dummy_packet = DataPacket(
                                length=self.packet_length,
                                payload=payload,
                                dummy=True)
                            nodeA.send_packet(nodeB, dummy_packet)

        return self.result
Beispiel #15
0
    def pollData(self):
        self.port.write(bytes('P', 'utf-8'))  # send POLL

        # ============================== BEGIN DATA ==============================

        packetId = int(self.waitAndReadLine())
        handProximity = int(self.waitAndReadLine())
        #         leftLegFrontProximity = int(self.waitAndReadLine())
        #         rightLegFrontProximity = int(self.waitAndReadLine())
        #         leftLegLeftProximity = int(self.waitAndReadLine())
        #         rightLegRightProximity = int(self.waitAndReadLine())
        leftArmLeftProximity = int(self.waitAndReadLine())
        rightArmRightProximity = int(self.waitAndReadLine())
        initialHeading = int(self.waitAndReadLine())
        numLeftTurns = int(self.waitAndReadLine())
        numRightTurns = int(self.waitAndReadLine())
        numStepsWalked = int(self.waitAndReadLine())

        checksum = int(self.waitAndReadLine())

        # ============================== END DATA ==============================

        # to verify checksum
        expectedChecksum = 0
        expectedChecksum += packetId + \
                            handProximity + \
                            leftArmLeftProximity + \
                            rightArmRightProximity + \
                            initialHeading + \
                            numLeftTurns + \
                            numRightTurns + \
                            numStepsWalked

        # to compile the data received into a single `DataPacket` object
        bytestream = str(packetId) + ',' + \
                     str(handProximity) + ',' + \
                     str(leftArmLeftProximity) + ',' + \
                     str(rightArmRightProximity) + ',' + \
                     str(initialHeading) + ',' + \
                     str(numLeftTurns) + ',' + \
                     str(numRightTurns) + ',' + \
                     str(numStepsWalked) + ',' + \
                     str(checksum) + ';'
        bytestream = bytestream.encode('utf-8')
        #         print(stringHelper.MESSAGE + 'Bytestream: ' + str(bytestream))

        if checksum != expectedChecksum:
            print(
                stringHelper.WARNING +
                ' at PiMegaCommunicator.pollData(): Checksum does not match. Expected: '
                + str(expectedChecksum) + '. Actual: ' + str(checksum) +
                '. Dropping this erroneous data packet.')
            return None
        else:
            dataPacket = DataPacket(bytestream)
            return dataPacket
Beispiel #16
0
    def seed_queue(self):
        src_node = self.nodes[20]
        dest_node = self.nodes[60]
        msg = "MESSAGE BETWEEN %s AND %s" % (src_node.public_key,
                                             dest_node.public_key)

        onion, onion_layers, betas = \
                self.construct_onion(src_node, dest_node, msg)
        packet = DataPacket(length=self.packet_length,
                            payload=onion,
                            dummy=False)
        src_node.queue_packet(dest_node, packet)
Beispiel #17
0
    def test_NWK_10():
        """
        Tests a DataPacket
        """

        # basic logging init
        log = logging.getLogger('jumpy')
        log_format = logging.Formatter(
            '%(filename)s - %(lineno)d - %(levelname)s - %(message)s')
        log.setLevel(logging.DEBUG)

        # logging console init
        log_handler_console = logging.StreamHandler()
        log_handler_console.setLevel(logging.DEBUG)
        log_handler_console.setFormatter(log_format)
        log.addHandler(log_handler_console)

        # imports
        from DataPacket import DataPacket
        from NetworkHandler import NetworkHandler
        import time

        helper = Helper()

        # base setup
        net_hand = NetworkHandler(helper.parse_message)
        net_hand.establish_connection()

        time.sleep(1)

        assert net_hand.is_connected

        packet: DataPacket = DataPacket()
        assert packet.data_dict.keys().__contains__('packet-name')
        assert packet.data_dict.keys().__contains__('mac-addr')
        assert packet.data_dict.keys().__contains__('time-of-creation')
        assert not packet.data_dict.keys().__contains__('time-of-send')

        assert packet.data_dict.get('packet-name').__eq__('DataPacket')
        assert packet.data_dict.get('mac-addr') is not None
        assert packet.data_dict.get('time-of-creation') is not None

        packet.set_time_of_send()
        assert packet.data_dict.keys().__contains__('time-of-send')
        assert packet.data_dict.get('time-of-send') is not None

        net_hand.send_packet(packet)
        time.sleep(1)
        net_hand.close_connection()
        assert helper.packet_received_data_dict is not None
        pass
Beispiel #18
0
    def pollData(self):
        self.port.write(MSG_POLL_DATA)
        print('MESSAGE: Pi sent POLL_DATA to Mega.')

        while True:
            bytestreamReceived = self.port.read()
            if bytestreamReceived != None:
                decodedBytestream = self.decode(bytestreamReceived)
                if decodedBytestream == None:  # if the bytestream received is erroneous
                    self.port.write(MSG_NAK)
                else:
                    self.port.write(MSG_ACK)
                    dataPacket = DataPacket(decodedBytestream)
                    break

        return dataPacket
Beispiel #19
0
    def handle_packets(self) -> None:
        packet = self.recieved_packets.pop(0)

        response = ResponsePacket()  # Create the response

        if isinstance(packet, DataPacket):
            #Scrable packet
            message = packet.to_binary()
            data_packet = DataPacket()
            data_packet.to_packet(
                CommunicationSettings.scramble_message(message))

            if data_packet.get_valid():
                if CommunicationSettings.logging:
                    print(f"{self.name}: Valid packet")

                if data_packet.is_eot():
                    self.simulate = False
                    self.recreate_image()
                else:
                    self.good_packets.append(
                        data_packet.get_data())  #Add good data
                response.mark_as_not_retransmit(
                )  #Say that there is no need for retransmition

                #If the content isn't the same then the error wasn't detected
                if message != data_packet.to_binary():
                    self.stats.undetected_errors += 1
            else:
                self.stats.detected_errors += 1
                response.mark_as_retransmit()
                if CommunicationSettings.logging:
                    print(f"{self.name}: Invalid packet")

            #Save the last response
            self.last_response = response.get_data()
            self.sender.recieve_packet(response)
        else:
            #Is a response packet. That means that we should transmit our last response again
            response = ResponsePacket(data=self.last_response)
            self.sender.recieve_packet(response)
Beispiel #20
0
    def pollData(self):
        self.port.write(MSG_POLL_DATA)
        print(stringHelper.MESSAGE +
              ' at PiMegaCommunicator.pollData(): Pi sent POLL_DATA to Mega.')

        while True:
            bytestreamReceived = self.port.read()
            if bytestreamReceived != None:
                decodedBytestream = hammingCode.decode(bytestreamReceived)
                if decodedBytestream == None:  # if the bytestream received is erroneous
                    print(
                        stringHelper.WARNING +
                        ' at PiMegaCommunicator.pollData():' +
                        ' The data packet received is erroneous; dropping this data packet.'
                    )
                    return None
                else:
                    dataPacket = DataPacket(decodedBytestream)
                    return dataPacket
Beispiel #21
0
    def queue_real_data(self):
        # Randomly generate real data between nodes probability % of the time.
        prob = 0.1  # %
        # Markov transition possibility
        for cliqueA in self.cliques:
            for nodeA in cliqueA:
                for cliqueB in self.cliques:
                    for nodeB in cliqueB:
                        # Num messages = threshold * N^2
                        if nodeA.public_key != nodeB.public_key \
                           and random() <= prob/100:
                            src_node = nodeA
                            dest_node = nodeB
                            msg = "%s MESSAGE BETWEEN %s AND %s" % (
                                dest_node.public_key, src_node.public_key,
                                dest_node.public_key)

                            onion, onion_layers, betas = \
                                    self.construct_onion(src_node, dest_node, msg)
                            packet = DataPacket(length=self.packet_length,
                                                payload=onion,
                                                dummy=False)
                            src_node.queue_packet(dest_node, packet)
                            return  # Remove this line to create >1 "real" message
    def handle_packets(self) -> None:
        packet = self.recieved_packets.pop(0)
        if isinstance(packet, DataPacket):
            #Scrable packet
            message = packet.to_binary()
            data_packet = DataPacket()
            data_packet.to_packet(CommunicationSettings.scramble_message(message))

            if data_packet.get_valid():
                if message != data_packet.to_binary():
                    self.stats.undetected_errors += 1
            else:
                self.stats.detected_errors += 1

            if len(self.current_window) < CommunicationSettings.window_size:
                self.current_window.append(data_packet) #Append packet if window isn't full
            else:
                position = data_packet.get_key()
                #Set the packet in the correct place if it makes sense (position is good and the packet is valid)
                if position < CommunicationSettings.window_size and data_packet.get_valid():
                    self.current_window[position] = data_packet

            is_eot = data_packet.is_eot()

            #Evaluate window if is end of transmition or the window is full
            if len(self.current_window) == CommunicationSettings.window_size or is_eot:
                for i in range(len(self.current_window)):
                    #If the packet isn't valid ask for retransmition and break the check
                    if self.current_window[i].get_valid() == False:
                        if CommunicationSettings.logging:
                            print(f"{self.name}: Invalid window on packet {i}")
                        response = ResponsePacket(key=i)
                        response.mark_as_retransmit()
                        self.sender.recieve_packet(response)
                        return

                #If no packet is detected as invalid, then the window is valid
                if CommunicationSettings.logging:
                    print(f"{self.name}: Valid window")

                #Add data
                for packet in self.current_window:
                    if packet.is_eot() == False:
                        self.good_packets.append(packet.get_data())
                    else:
                        is_eot = True

                #Clear the current window
                self.current_window.clear()

                #If end of transmition then stop the simulation end recreate the image
                if is_eot:
                    self.simulate = False
                    self.recreate_image()

                #Send a request for a new window
                response = ResponsePacket()
                response.mark_as_not_retransmit()
                response.set_max_key()
                self.sender.recieve_packet(response)

        else:
            #Is a response packet. That means that we should transmit our last response again
            response = ResponsePacket(self.last_response_key, self.last_response)
            self.sender.recieve_packet(response)
Beispiel #23
0
def change_did(old_did,new_did):
    packet=DataPacket(id=old_did,instr=0x02,data=[0x04,new_did])
    a=packet.getCharPacket()
    packet.writeToSerial(a)
    
    return retrieve_status(new_did)
Beispiel #24
0
    def queue_packet(self, from_who, packet):
        if type(packet.payload) == str:
            # Dummy cover traffic
            # receiving_node = self.network.cliques[clique_id][node_id]
            receiving_node = from_who
            self.network.real_data_queue.append((self, receiving_node, packet))
        else:
            # An onion's next node is randomly determined
            # according to a mixing probability
            if random() <= self.network.mixing_probability:
                # print "Randomizing what should've been between %s and %s" \
                #        % (from_who.public_key, self.public_key)

                # 1. Pick random node in same clique as sender
                same_clique = self.network.cliques[from_who.clique_id]

                # Possible infinite loop if cliques are of size 1
                # Make sure cliques have >1 node
                rand_i = randint(0, len(same_clique) - 1)
                rand_node = same_clique[rand_i]
                while rand_node.public_key == from_who.public_key:
                    rand_i = randint(0, len(same_clique) - 1)
                    rand_node = same_clique[rand_i]

                # 2. Queue it. Note that we leave the onion untouched
                receiving_node = rand_node
                self.network.count += 1
                print "RANDOM from %s to %s" % (from_who.public_key,
                                                receiving_node.public_key)
                if self.network.node_exists(receiving_node.public_key):
                    self.network.real_data_queue.append(
                        (self, receiving_node, packet))
                else:
                    print "Coming from a random mix"
                    self.authority_node.reroute((self, receiving_node, packet))
            else:
                # Otherwise, peel it and queue it.
                onion = packet.payload
                if not hasattr(onion, 'O'):
                    pdb.set_trace()
                print "\t- onion.O: " + str(onion.O)
                info = onion.get_info()
                if type(info) == str:
                    # Get the message body from the encrypted string
                    message = info
                    while message[0] == '~':
                        message = message[1:]

                    print "Message: " + message
                    self.network.result = 1

                    # Remove the message from the path object
                    onion.O[0] = ''.join([c for c in onion.O[0] if c == '~'])
                    cur_layer = onion.prev_layer + 1
                    onion.prev_layer += 1
                else:
                    cur_layer = info
                    if cur_layer == -1:
                        return  # The onion can no longer be decrypted
                    onion.prev_layer = cur_layer

                # Occasionally happens
                if cur_layer > len(onion.onion_layers):
                    return

                dest_cid = from_who.clique_id
                dest_nid = from_who.node_id

                # Queue data for each real onion node per layer
                # because fake ones cannot source data
                print "Cur_layer: " + str(cur_layer)
                if not packet.dummy:
                    for clique_num, clique in enumerate(
                            onion.onion_layers[cur_layer]):
                        onion_node = onion.onion_nodes[str(cur_layer) + "," +
                                                       str(clique_num)]
                        print "Receiving node: " + str(onion_node)
                        print "\tSender: " + str(self)

                        onion_copy = deepcopy_with_sharing(
                            onion, ['onion_nodes'])
                        onion_copy.peel()
                        print "\t- peeledO: " + str(onion_copy.O)
                        dummy = False if clique_num == 0 else True
                        packet = DataPacket(length=packet.length,
                                            payload=onion_copy,
                                            dummy=dummy)

                        receiving_node = onion_node
                        self.network.count += 1
                        if self.network.node_exists(receiving_node.public_key):
                            self.network.real_data_queue.append(
                                (self, receiving_node, packet))
                        else:
                            print "Coming from a determined route"
                            self.authority_node.reroute(
                                (self, receiving_node, packet))
Beispiel #25
0
def dispense(did):
    packet=DataPacket(id=did,instr=0x02,data=[0x01])
    a=packet.getCharPacket()
    packet.writeToSerial(a)
Beispiel #26
0
class AuthorityNode:
    '''A node with special privileges and powers'''

    def __init__(self, network):
        self.network = network
        self.route_map = {}
        self.dist_map = {}
        self.needs_update = False

    def setup_routes(self):
        for nodeA in self.network.nodes:
            if nodeA.public_key not in self.route_map:
                self.route_map[nodeA.public_key] = {}
                ttl = randint(1, 5)
                cur_ttl = ttl
                self.dist_map[nodeA.public_key] = (ttl, cur_ttl)

            for nodeB in self.network.nodes:
                if nodeA.public_key != nodeB.public_key and \
                   nodeB.public_key not in self.route_map[nodeA.public_key]:

                    ttl = randint(1, 5)  # Making assumption that furthest node is 5 hops
                    cur_ttl = ttl  # Used to keep track of what the current ttl is
                    route = []  # Dummy array that would really hold a route
                    self.route_map[nodeA.public_key][nodeB.public_key] = (ttl, cur_ttl, route)

    def create_cliques(self, N, M):
        n_per_clique = N / M
        start = 0 if N % M == 0 else 1
        cliques = []
        # For simplicity, cliques are uniform
        for i in xrange(start, N, n_per_clique):
            cur_clique = []
            if start and i == 1:
                cur_clique.append(self.network.nodes[0])
            for j in range(i, i+n_per_clique):
                if j < N: cur_clique.append(self.network.nodes[j])
            cliques.append(cur_clique)

        return cliques

    def reroute(self, (source, destination, packet)):
        '''Called when source cannot successfully send a message to 
            the destination node. The authority node will instead try
            to find another route to the final onion destination. This
            rerouting code can be modified as deemed necessary. For example,
            to wait until the destination packet again comes online.'''
        print "\t| Rerouting from %s to %s" % (source.public_key, destination.public_key)

        onion = packet.payload
        onion_dest_key = self.decrypt_onion(onion)
        
        onion_dest = None
        for node in self.network.nodes:
            if node.public_key == onion_dest_key:
                onion_dest = node
                break
        if not onion_dest:
            print "Dropping packet because %s not in network" % (onion_dest_key,)
            self.network.result = -1 if not self.network.result else self.network.result
            return  # The final destination is not in the network. Drop packet.

        # if self.alternate_path(source.public_key, onion_dest.public_key):
            # Onion clique, node, and layer information needs to be moved
            # into the Onion class from the Network class.
        msg = "%s MESSAGE BETWEEN %s AND %s" % (
            onion_dest.public_key, source.public_key, onion_dest.public_key
        )
        new_onion = self.network.construct_onion(source, onion_dest, msg)[0]
        packet = DataPacket(
            length=self.network.packet_length, payload=new_onion, dummy=False
        )
        print "Successfully rerouted packet"
        source.queue_packet(
            onion_dest, packet
        )
        '''
        else:
            # No path exists
        '''
        '''Modify this block to deal with no alternative paths existing.
Beispiel #27
0
def retract(did):
    packet=DataPacket(id=did,instr=0x02,data=[0x02])
    a=packet.getCharPacket()
    packet.writeToSerial(a)    
Beispiel #28
0
    def parse_message(self, packet_str: DataPacket):
        data_dict = json.loads(packet_str)
        packet_name = data_dict.get('packet-name')
        if data_dict.get('mac-addr') == self.mac:
            self.log.debug('received packet from self, ignoring...')
        else:
            self.log.debug('Received a \'{}\''.format(packet_name))
            print(data_dict)

            if packet_name == 'DataPacket':
                self.log.debug('Received a DataPacket')

            elif packet_name == 'DataPacketDocumentEdit':
                self.log.debug('Received a DataPacketDocumentEdit')

                cursor_index = self.code.text.index(INSERT)

                packet: DataPacketDocumentEdit = DataPacketDocumentEdit()
                packet.parse_json(packet_str)
                self.workspace.apply_data_packet_document_edit(packet)
                current_doc = self.current_file_name.get().split('/')[-1]
                if packet.get_document() == current_doc:
                    self.code.text.delete("1.0", END)
                    self.code.text.insert(END, packet.get_text())
                    self.syntax_highlighting()

                self.code.text.mark_set(INSERT, cursor_index)

            elif packet_name == 'DataPacketCursorUpdate':
                u2_pos = data_dict.get('position')
                name = data_dict.get('mac-addr')
                self.cursor_update(u2_pos, str(name))

            elif packet_name == 'DataPacketRequestJoin':
                packet: DataPacketRequestJoin = DataPacketRequestJoin()
                packet.parse_json(packet_str)
                if self.is_host:
                    result = messagebox.askyesno(
                        "jumpy request",
                        "Allow \'{}\' to join the lobby?".format(
                            data_dict.get(DataPacketRequestJoin.KEY_NAME)))
                    dprr = DataPacketRequestResponse()
                    dprr.set_target_mac(packet.get_mac_addr())
                    dprr.set_can_join(result)
                    self.net_hand.send_packet(dprr)
                    if result:
                        sleep(3)
                        name_broadcast = DataPacketNameBroadcast()
                        name_broadcast.set_name(self.mac_name.get(self.mac))
                        self.net_hand.send_packet(name_broadcast)
                        to_send = self.workspace.get_save_dump()
                        for packet in to_send:
                            self.net_hand.send_packet(packet)

            elif packet_name == 'DataPacketRequestResponse':
                packet: DataPacketRequestResponse = DataPacketRequestResponse()
                packet.parse_json(packet_str)
                if packet.get_target_mac() == DataPacket.get_mac_addr_static():
                    self.log.debug('Received a DataPacketRequestResponse')
                    can_join = packet.get_can_join()

                    # todo: fix
                    if can_join:
                        self.log.debug('allowed into the lobby')
                        self.workspace.use_temp_workspace()
                        self.have_perms = True
                        messagebox.showinfo(
                            "jumpy", "You have been accepted into the lobby!")
                    else:
                        self.log.debug('rejected from the lobby')
                        self.have_perms = False
                        messagebox.showerror(
                            "jumpy",
                            "You have NOT been accepted into the lobby...")
                        self.net_hand.close_connection()

                name_broadcast = DataPacketNameBroadcast()
                name_broadcast.set_name(self.mac_name.get(self.mac))
                self.net_hand.send_packet(name_broadcast)

            elif packet_name == 'DataPacketSaveDump':
                packet: DataPacketSaveDump = DataPacketSaveDump()
                packet.parse_json(packet_str)
                self.workspace.apply_data_packet_save_dump(packet)
                if self.workspace.new_file_added:
                    if len(self.workspace.files) == packet.get_workspace_size(
                    ):
                        self.log.debug(
                            'received whole workspace, setting code.text state to normal'
                        )
                        self.code.text.config(state='normal')
                        self.open_folder(self.workspace.directory)

            elif packet_name == 'DataPacketSaveRequest':
                to_send = self.workspace.get_save_dump_from_document(
                    data_dict.get('document'))
                self.net_hand.send_packet(to_send)

            elif packet_name == 'DataPacketNameBroadcast':
                packet = DataPacketNameBroadcast()
                packet.parse_json(packet_str)
                self.log.debug('mac_name updating {} to {}'.format(
                    packet.get_mac_addr(), packet.get_name()))
                self.mac_name.update(
                    {packet.get_mac_addr(): packet.get_name()})

            else:
                self.log.warning(
                    'Unknown packet type: \'{}\''.format(packet_name))
                return False
Beispiel #29
0
 def fillWindow(self, chunks):
     while not self.WINDOW.full() and self.SEQNO < len(chunks):
         PACKET = DataPacket(chunks[self.SEQNO], self.SEQNO, self.CHECKSUM)
         self.WINDOW.put(PACKET)
         self.SEQNO = self.SEQNO + 1
     return PACKET
Beispiel #30
0
'''
Created on 19 Oct 2016

@author: chen-zhuo
'''

from DataPacket import DataPacket
import stringHelper
from time import sleep

dataPackets = [
    DataPacket('0,0,0,0,45,0,0,0,45;'.encode('utf-8')),
    # at #1211, facing "up" (feedback: turn right 90 degrees)
    DataPacket('1,0,0,0,45,0,2,0,48;'.encode('utf-8')),
    # at #1211, facing "right" (feedback: go straight)
    DataPacket('2,0,0,0,45,0,2,0,2333;'.encode('utf-8')),
    # erronous data packet; drop this (feedback: go straight)
    DataPacket('3,0,0,0,45,0,2,5,58;'.encode('utf-8')),
    # between #1211 and #1214, facing "right" (feedback: go straight)
    DataPacket('4,0,0,0,45,0,2,24,75;'.encode('utf-8')),
    # near #1214, facing "right" (feedback: turn right 90 degrees)
    DataPacket('5,0,0,0,45,0,4,24,78;'.encode('utf-8')),
    # at #1214, facing "down" (feedback: go straight)
    DataPacket('6,0,0,0,45,0,4,28,83;'.encode('utf-8')),
    # at #1237, facing "down" (feedback: go straight)
    DataPacket('7,0,0,0,45,0,4,41,182;'.encode('utf-8')),
    # at #1216; destination reached
]


class PiMegaCommunicator():