Пример #1
0
    def done(self, node, message):

        if message.header == 'Token_location':
            if node.memory['Dft_source'] == True:
                node.memory['DFT_done_counter'] -= 1
                if node.memory['DFT_done_counter'] > 1:
                    node.send(Message(destination=node.memory['Token_exit'],
                                      header='Start_DFT'))  
            node.status = 'VISITED'
                   
        if message.header == 'Termination_complete':
            node.memory['Termination_counter'] -= 1
            if node.memory['Termination_counter'] == 0:
                if node.memory['Source'] == True:
                    node.memory['Source'] == False
                    node.status = 'VISITED'

                    if node.memory['Dft_source'] == True:
                        node.memory['DFT_done_counter'] = len(node.memory[self.routingTableKey])
                        node.memory["DFT_parent"] = None
                        node.memory["DFT_unvisited"] = list(node.memory[self.neighborsKey])
                        self.visit(node)
                    else:
                        node.send(Message(destination=node.memory['DFT_parent'],
                                          header='Token_location'))  
                else:
                    node.send(Message(destination=node.memory['Parent'],
                                      header='Termination_complete'))

                    if node.memory['Visited_status'] == True: 
                        node.status = 'VISITED'    
                    else:
                        node.status = 'DFT_IDLE'  
Пример #2
0
    def active(self, node, message):
        if message.header=='M':
            if message.data > node.memory['Maxtemp']:
                node.memory['Maxtemp'] = message.data
            if (message.source in node.memory['Susjedi']):
                (node.memory['Susjedi']).remove(message.source)
            if (node.memory['Ini'] == 1):
                if (len(node.memory['Susjedi']) == 0):
                    node.send(Message(header='Flood', data=node.memory['Maxtemp'], destination=node.memory['Neighbors']))
                    node.status = 'SATURATED'
            else:
                if (len(node.memory['Susjedi']) == 1):
                    node.send(Message(header='M', data=node.memory['Maxtemp'], destination=node.memory['Susjedi']))
                    node.status = 'PROCESSING'



        if message.header=='Wakeup':
            if (message.source in node.memory['Susjedi']):
                (node.memory['Susjedi']).remove(message.source)
            node.send(Message(header='Backedge', destination=message.source))
            if (len(node.memory['Susjedi']) == 1): 
                node.send(Message(header='M', data=node.memory['Maxtemp'], destination=node.memory['Susjedi']))
                node.status = 'PROCESSING'

        if message.header=='Backedge':
            if (message.source in node.memory['Susjedi']):
                (node.memory['Susjedi']).remove(message.source)
            if (len(node.memory['Susjedi']) == 1): 
                node.send(Message(header='M', data=node.memory['Maxtemp'], destination=node.memory['Susjedi']))
                node.status = 'PROCESSING'
Пример #3
0
    def idle(self, node, message):
        if node.type == 'N' and message.data == "Request for data":
            dst = node.memory['cluster_head']
            data = "Sensor Id: %s" % str(node.id)
            node.send(Message(header='Information', data=data, destination=dst))
        elif node.type == 'C' and message.data.startswith("Sensor Id"):
            if message.source.id not in node.memory['recv_list']:
                node.memory['recv_list'].append(message.source.id)
                node.memory['aggregate_data'].append(message.data.split(": ")[1])
                node.memory['recv_count'] += 1
                print("Cluster_head Id %s: recv_count %s" % (str(node.id), str(node.memory['recv_count'])))
                if node.memory['recv_count'] == 9:
                    dst = node.memory['cluster_head']
                    nodeIds = node.memory['aggregate_data']
                    if node.memory['attacker'] == True:
                        nodeIds = 'BLOCKED'
                    node.send(Message(header='Information', data=nodeIds, destination=dst))

        elif node.type == 'B' and type(message.data) is list and message.destination == node:
            aggregate_data = message.data
            to_save = "Node %s was responsible for %s" % (str(message.source.id), aggregate_data)
            self.done_count += 1
            node.memory['aggregate_data'].append(to_save)
            if self.done_count == 10:
                node.status = 'DONE'

        if message.data == "Request for data":
            destination_nodes = list(node.memory[self.neighborsKey])
            destination_nodes.remove(message.source)
            if destination_nodes:
                node.send(Message(destination=destination_nodes, header='Information', data=message.data))
Пример #4
0
    def awake(self, node, message):

        if message.header == 'Expand':
            # u message.data[1] se nalazi 'My_distance' od cvora koji je poslao poruku
            node.memory['My_distance'] = message.data[1]
            node.memory['Parent'] = message.source
            node.memory['Children'] = []                       

            if len(node.memory[self.neighborsKey]) > 1:
                destination_nodes = node.memory[self.neighborsKey][:]
                destination_nodes.remove(message.source) 
                node.send(Message(destination=destination_nodes,
                                  header='Notify'))
                number_of_neighbors = len(node.memory[self.neighborsKey])
                node.memory['Ackcount'] = number_of_neighbors - 1
                node.status = 'WAITING_FOR_ACK'
            else:
                node.send(Message(destination=node.memory['Parent'],
                                  header='Iteration_Completed',
                                  data=node))
                node.status = 'ACTIVE'

        if message.header == 'Notify':
            node.memory['Unvisited'].remove(message.source)
            node.send(Message(destination=message.source,
                              header='Ack'))
 def working(self, node, message):
     if (message.header == "Q") and (node.memory['counter'] >= 1):
         node.send(Message(header='No', destination=message.source))
     if message.header == "Yes":
         node.memory['tree-neighbors'].append(message.source)
         node.memory['counter'] += 1
         self.process_message(node, message.data)
         if node.memory['counter'] >= len(node.memory['Neighbors']) and \
             node.memory['root'] == False:
             node.send(
                 Message(header='Yes',
                         destination=node.memory['parent'],
                         data=node.memory['maxTemperature']))
             node.status = 'WAITING'
         if node.memory['counter'] >= len(node.memory['Neighbors']) and \
             node.memory['root'] == True:
             node.send(
                 Message(header="T",
                         destination=node.memory['tree-neighbors'],
                         data=node.memory['maxTemperature']))
             node.status = 'DONE'
     if message.header == "No":
         node.memory['counter'] += 1
         if node.memory['counter'] == len(node.memory['Neighbors']):
             node.send(
                 Message(header='Yes',
                         destination=node.memory['parent'],
                         data=node.memory['maxTemperature']))
             node.status = 'WAITING'
Пример #6
0
 def idle(self, node, message):
     if message.header == 'Information':
         print "Message:", message.data, " Temp:", node.memory[
             'Temperature']
         node.memory['Maxtemp'] = message.data
         node.memory[self.informationKey] = message.data
         destination_nodes = list(node.memory[self.neighborsKey])
         destination_nodes.remove(
             message.source)  # send to every neighbor-sender
         if destination_nodes:
             #Je li dobivena tj. primljena  poruka (temp) veca od temperature ovog cvora?
             if node.memory[
                     self.informationKey] > node.memory['Temperature']:
                 node.send(
                     Message(destination=destination_nodes,
                             header='Information',
                             data=message.data))
                 node.memory['Maxtemp'] = message.data
             else:
                 node.send(
                     Message(destination=destination_nodes,
                             header='Information',
                             data=node.memory['Temperature']))
                 node.memory['Maxtemp'] = node.memory['Temperature']
     node.status = 'DONE'
    def available(self, node, message):
        #inicijatori
        if message.header == NodeAlgorithm.INI:  #Spontaneously
            node.send(Message(header='Activate', data='Activate'))
            if len(node.memory[self.neighborsKey]) == 1:  #ako je čvor list
                node.memory[self.parentKey] = list(
                    node.memory[self.neighborsKey])[0]  ## [0]
                updated_data = self.prepare_message(node)
                node.send(
                    Message(header='M',
                            data=updated_data,
                            destination=node.memory[self.parentKey]))
                node.status = 'PROCESSING'
            else:
                node.status = 'ACTIVE'

        if message.header == 'Activate':
            destination_nodes = list(
                node.memory[self.neighborsKey])  ##treeKey?
            destination_nodes.remove(message.source)
            node.send(
                Message(header='Activate',
                        data='Activate',
                        destination=destination_nodes))
            if len(node.memory[self.treeKey]) == 1:
                node.memory[self.parentKey] = list(
                    node.memory[self.treeKey])[0]
                updated_data = self.prepare_message(node)
                node.send(
                    Message(header='M',
                            data=updated_data,
                            destination=node.memory[self.parentKey]))
                node.status = 'PROCESSING'
            else:
                node.status = 'ACTIVE'
Пример #8
0
    def awake(self, node, message):
        if message.header == 'Expand':
            self.messageCounter += 1

            #postavi myDistance na dobivenu udaljenost, postavi posiljatelja poruke za roditelja
            node.memory[self.myDistanceKey] = message.data[1]
            node.memory[self.parentKey] = message.source
            node.memory[self.childrenKey] = []
            #ako nisi list
            if len(node.memory[self.neighborsKey]) > 1:
                #posalji svim susjedima osim roditelju Notify poruku s informacijom o trenutnoj macro iteraciji
                destination = list(node.memory[self.neighborsKey])
                destination.remove(message.source)
                node.send(
                    Message(header='Notify',
                            destination=destination,
                            data=node.memory[self.macroIterationKey]))
                #postavi ack brojac i prijedji u stanje WAITING_FOR_ACK
                node.memory[self.ackCountKey] = len(
                    node.memory[self.neighborsKey]) - 1
                node.status = 'WAITING_FOR_ACK'
            #ako si list
            else:
                #dodaj sebe u routing listu
                routingList = [node]
                #obavijesti roditelja o zavrsetku iteracije i posalji mu routing listu
                node.send(
                    Message(header='IterationCompleted',
                            destination=node.memory[self.parentKey],
                            data=routingList))
                node.status = 'ACTIVE'

        elif message.header == 'Notify':
            self.messageCounter += 1
            self.processNotify(node, message)
    def friendly_merger(self, node, message, param_begining=False, orientation_of_roads=False):
        if param_begining == True:
#            Only when node is the root
            if node.memory[self.Let_us_merge_FriendlyMergerKey] == False:
                node.send(Message(header='Let_us_merge', data={'Level': node.memory[self.levelKey]}, destination=message.source))
            b = message.source
            new_downtown = self.min_id_two_nodes(node, b)
            self.change_name_level(node, None, new_downtown.id, 'friendly_merger')
            self.change_link_status_key_internal(node, b)
#           without parent, message is being sent to everyone!!
            if node.memory[self.parentKey] != None:
                node.send(Message(header="friendly_merger+orientation_of_roads", data=0, destination=node.memory[self.parentKey]))
#           because we change parent, we need to send the message first.
            if new_downtown.id != node.id:
                node.memory[self.parentKey] = b
            else:
                node.memory[self.parentKey] = None
            node.memory['I am late'] = node.memory[self.lateKey]
            self.send_Outside(node)
        else:
            if orientation_of_roads == True: 
                if node.memory[self.parentKey] != None:
                    node.send(Message(header="friendly_merger+orientation_of_roads", data=0, destination=node.memory[self.parentKey]))
                else:
                    pass
            else:
                destination_nodes = list(filter(lambda neighbor:  neighbor != node.memory[self.parentKey] and neighbor != message.source
                    and node.memory[self.linkStatusKey][neighbor] == 'INTERNAL', node.memory[self.neighborsKey])) 
                node.send(Message(header="friendly_merger", data=0, destination=destination_nodes))
Пример #10
0
 def available(self, node, message):
     # OVO JE ZA PRVOG (INIT)
     if message.header == NodeAlgorithm.INI:
         node.send(Message(header='Wakeup'))
         if (
                 len(node.memory['neighbors']) == 1
         ):  # Poseban slucaj kad init ima samo 1 susjeda? (Graf ima 2 cvora)
             prepared_data = self.prepare_message(node)
             node.send(
                 Message(header='M',
                         data=prepared_data,
                         destination=node.memory['neighbors']))
             node.status = 'PROCESSING'
         else:
             node.status = 'ACTIVE'
     # OVO JE ZA SVE OSTALE CVOROVE
     if message.header == 'Wakeup':
         destination_nodes = list(node.memory['neighbors'])
         destination_nodes.remove(
             message.source)  # Pobrisali smo sendera iz liste primatelja
         node.send(Message(header='Wakeup', destination=destination_nodes))
         if (len(node.memory['neighbors']) == 1):
             '''#prepared_data = ""
             #self.prepare_message(prepared_data)
             prepared_data = "Saturation"'''
             prepared_data = self.prepare_message(node)
             node.send(
                 Message(header="M",
                         data=prepared_data,
                         destination=node.memory['neighbors']))
             node.status = 'PROCESSING'
         else:
             node.status = 'ACTIVE'
Пример #11
0
    def checkForTermination(self, node):
        #ako ti je u min zapisan infinity
        if node.memory[self.minPathKey] == float("inf"):
            #posalji Terminate poruku svoj djeci i incijaliziraj potrebne varijable
            node.send(
                Message(header='Terminate',
                        destination=node.memory[self.childrenKey]))

            self.initializeVariables(node)

            #ako imas susjeda kojima nisi poslao Token
            if node.memory[self.tokenNeighboursKey]:
                #uzmi prvog susjeda kojem nisi poslao Token
                tokenNeighbour = node.memory[self.tokenNeighboursKey][0]

                #povecaj brojac makro iteracije, posalji Token odabranom susjedu i makni ga iz liste
                node.memory[self.macroIterationKey] += 1
                node.send(
                    Message(header='Token',
                            destination=tokenNeighbour,
                            data=node.memory[self.macroIterationKey]))
                tokenNeighbours = list(node.memory[self.tokenNeighboursKey])
                tokenNeighbours.remove(tokenNeighbour)
                node.memory[self.tokenNeighboursKey] = tokenNeighbours
            #ako je svima poslan Token
            else:
                #ako nisi master posalji Token roditelju s informacijom o makroiteraciji
                if not node.memory[self.masterKey]:
                    node.send(
                        Message(header='Token',
                                destination=node.memory[self.parentMasterKey],
                                data=node.memory[self.macroIterationKey]))

            node.status = 'IDLE'

        else:
            #ako su ti exit i myChoice isti cvor
            if (node.memory[self.exitKey] == node.memory[self.myChoiceKey]):
                #ako ti exit nije u listi djece, dodaj ga
                children = list(node.memory[self.childrenKey])
                if node.memory[self.exitKey] not in children:
                    children.append(node.memory[self.exitKey])
                node.memory[self.childrenKey] = children

                #ako ti je exit u listi neposjecenih cvorova, makni ga
                unvisited = list(node.memory[self.unvisitedKey])
                if node.memory[self.exitKey] in unvisited:
                    unvisited.remove(node.memory[self.exitKey])
                node.memory[self.unvisitedKey] = unvisited

            #posalji Expand poruku svom exit cvoru s informacijama o trenutnoj iteracij i minimumom
            node.send(
                Message(header='Expand',
                        destination=node.memory[self.exitKey],
                        data=[
                            node.memory[self.iterationKey],
                            node.memory[self.minPathKey]
                        ]))
            node.status = 'ACTIVE'
Пример #12
0
    def idle(self, node, message):
        if message.header == 'Notify':
            self.messageCounter += 1
            self.processNotify(node, message, True)
            node.status = 'AWAKE'

        elif message.header == 'Token':
            self.messageCounter += 1
            #spremi informaciju o broju makroiteracije
            node.memory[self.macroIterationKey] = message.data
            #ako vec imas routing table
            if node.memory[self.routingTableKey]:
                #provjera ako postoji dijete kojemu jos nisi poslao token
                if node.memory[self.tokenNeighboursKey]:
                    tokenNeighbour = node.memory[self.tokenNeighboursKey][0]
                    node.memory[self.macroIterationKey] += 1
                    #slanje tokena dijetetu kojemu jos nije poslan
                    node.send(
                        Message(header='Token',
                                destination=tokenNeighbour,
                                data=node.memory[self.macroIterationKey]))
                    #makni iz liste dijete kojemu si poslao token
                    tokenNeighbours = list(
                        node.memory[self.tokenNeighboursKey])
                    tokenNeighbours.remove(tokenNeighbour)
                    node.memory[self.tokenNeighboursKey] = tokenNeighbours
                #ako si poslao svoj djeci token
                else:
                    #ako nisi master salji token roditelju
                    if not node.memory[self.masterKey]:
                        node.send(
                            Message(
                                header='Token',
                                destination=node.memory[self.parentMasterKey],
                                data=node.memory[self.macroIterationKey]))
                    #ako si master, algoritam je gotov i broadcasta se poruka o zavrsetku algoritma
                    else:
                        node.send(
                            Message(header='Done',
                                    destination=node.memory[
                                        self.masterChildrenKey]))
                        node.status = 'DONE'

            #ako nemas routing table postani iniciator i pokreni novu makroiteraciju
            else:
                node.send(Message(header=NodeAlgorithm.INI, destination=node))

                node.status = 'INITIATOR'

        #ako si primio header Done javi svojoj djeci da je algoritam zavrsen i postani DONE
        elif message.header == 'Done':
            self.messageCounter += 1

            node.send(
                Message(header='Done',
                        destination=node.memory[self.masterChildrenKey]))
            node.status = 'DONE'

            print self.messageCounter
Пример #13
0
    def flooding(self, node, message):
        if message.header == NodeAlgorithm.INI:
            node.send(Message(header='Flood', data=self.initiator_data(node)))

        if message.header == 'Flood':
            updated_data = self.handle_flood_message(node, message)
            if updated_data:
                node.send(Message(header='Flood', data=updated_data))
Пример #14
0
 def visit(self, node, message):
     if (node.memory['unvisited']):
         node.memory['next'] = node.memory['unvisited'].pop()
         node.send(Message(header='T', destination=node.memory['next']))
     else:
         if not node.memory['initiator']:
             node.send(
                 Message(header='Return', destination=node.memory['entry']))
         node.status = 'DONE'
Пример #15
0
    def send_responses(self, node, no_received=False):
        # Find min id
        min_id = min(node.memory[self.RECEIVED_IDS_KEY])
        no_nodes = []
        prune_nodes = []

        received_ids = node.memory[self.RECEIVED_IDS_KEY]
        for received_id in received_ids:
            if no_received:
                # Send NO to all node that sent an id
                node.send(
                    Message(destination=received_ids[received_id],
                            header='response',
                            data=(False, )))
                no_nodes.extend(received_ids[received_id])

            elif received_id == min_id:
                # Send YES responses to all inNeighbors that send min_id

                if len(received_ids) == 1 and \
                        len(node.memory[self.outNeighborsKey]) == 0:
                    # If node received only min_id and has no outNeighbors
                    # remaining after inverting and pruning
                    # it will become a LEAF SINK,
                    # so send a PRUNE request with the YES response as well
                    node.send(
                        Message(destination=received_ids[received_id][0],
                                header='response',
                                data=(True, self.PRUNE_REQUEST)))
                    prune_nodes.append(received_ids[received_id][0])
                else:
                    node.send(
                        Message(destination=received_ids[received_id][0],
                                header='response',
                                data=(True, )))

                # Send PRUNE request to extra nodes that sent min_id
                # and add them to prune_nodes to be pruned
                node.send(
                    Message(destination=received_ids[received_id][1:],
                            header='response',
                            data=(True, self.PRUNE_REQUEST)))
                prune_nodes.extend(received_ids[received_id][1:])

            else:
                # Send NO responses to all inNeighbors that didn't
                # send min_id and add them to no_nodes to be inverted
                node.send(
                    Message(destination=received_ids[received_id],
                            header='response',
                            data=(False, )))
                no_nodes.extend(received_ids[received_id])

        return no_nodes, prune_nodes
Пример #16
0
 def visit(self, node):
     if len(node.memory["unvisited"]) == 0:
         if node.memory["parent"] is not None:
             node.send(
                 Message(header='Return',
                         destination=node.memory["parent"]))
         node.status = "DONE"
     else:
         next_unvisited = node.memory["unvisited"].pop()
         node.send(Message(header='Token', destination=next_unvisited))
         node.status = "VISITED"
Пример #17
0
 def visit(self, node, message):
     if (node.memory['unvisited']):
         node.memory['next'] = node.memory['unvisited'].pop()
         node.send(Message(header='T',
                           destination=node.memory['next']))
     else:
         if node.memory['entry'] != None:
             node.send(Message(header='Return',
                               destination=node.memory['entry'], 
                               data=node.memory[self.maxTempKey]))
         node.status = 'DONE'
 def check_and_send_late_absorption(self, node, header, destination):
     node.memory['debug2323'] = node.memory[self.lateKey
     ]
     if node.memory[self.lateKey] == True and node.memory[self.nodeEdgeKey].keys()[0].id != destination.id:
             node.send(Message(header=header+"+late", data=0, destination=destination))
     else:
         node.send(Message(header=header, data=0, destination=destination))
     if node.memory[self.nodeEdgeKey].keys()[0].id == destination:
         node.memory[self.lateKey] = False
         if self.check_if_city_has_one_node(node):
             self.check_report(node)
    def check_Outside_header(self, node, message):
        if message.source.memory[self.nameKey]==node.memory[self.nameKey]:
                node.send(Message(header='Internal', data=0, destination=message.source))
                self.change_link_status_key_internal(node, message.source)
        elif node.memory[self.levelKey] >= message.source.memory[self.levelKey]:
            node.send(Message(header='External', data=0, destination=message.source))
            self.change_link_status_key_external(node, message.source)
            #self.check_outbox_Outside_remove_redundant(node, temp_message)
        else:
#           if the merge egde is the one being suspended, node would always pick that edge for merge.
            #self.change_link_status_key_external(node, message.source)
            node.memory[self.let_us_merge_queue_key].append(message)
Пример #20
0
    def initiator(self, node, message):
        if message.header == NodeAlgorithm.INI:
            #brojac poruka (za testiranje slozenosti)
            self.messageCounter += 1

            #svaki initiator mora postaviti defautne vrijednosti
            node.memory[self.sourceKey] = True
            node.memory[self.myDistanceKey] = 0
            node.memory[self.ackCountKey] = len(node.memory[self.neighborsKey])

            #slanje notify poruke svim susjedima
            node.send(
                Message(header='Notify',
                        destination=node.memory[self.neighborsKey],
                        data=node.memory[self.macroIterationKey]))

        elif (message.header == 'Ack'):
            #brojac poruka (za testiranje slozenosti)
            self.messageCounter += 1

            #brojac za ack poruke
            node.memory[self.ackCountKey] -= 1

            #ako su primljene ack poruke od svih susjeda, brojac je 0
            if node.memory[self.ackCountKey] == 0:
                node.memory[self.iterationKey] = 1
                #odaberi najblizeg susjeda
                minNeighbour = min(
                    node.memory[self.weightKey],
                    key=(lambda k: node.memory[self.weightKey][k]))
                v = node.memory[self.weightKey][minNeighbour]
                node.memory[self.pathLengthKey] = v
                #najblizeg susjeda dodaj u listu djece
                childrenList = list(node.memory[self.childrenKey])
                childrenList.append(minNeighbour)
                node.memory[self.childrenKey] = childrenList
                #najblizem susjedu posalji Expand poruku
                node.send(
                    Message(header='Expand',
                            destination=node.memory[self.childrenKey],
                            data=[
                                node.memory[self.iterationKey],
                                node.memory[self.pathLengthKey]
                            ]))

                #najblizeg susjeda izbaci iz unvisited liste
                unvisited = list(node.memory[self.neighborsKey])
                for child in node.memory[self.childrenKey]:
                    unvisited.remove(child)

                node.memory[self.unvisitedKey] = unvisited
                node.status = 'ACTIVE'
Пример #21
0
 def visit(self, node):
     if len(node.memory["DFT_unvisited"]) == 0:
         if node.memory["DFT_parent"] is not None:
             node.send(Message(header='Return',
                               destination=node.memory["DFT_parent"]))
         node.status = "DFT_IDLE"
     else:
         next_unvisited = node.memory["DFT_unvisited"].pop()
         node.memory['Token_status'] = False
         node.memory['Token_exit'] = next_unvisited
         node.send(Message(header='Token',
                           destination=next_unvisited))
         node.status = "VISITED"
Пример #22
0
 def initiator(self, node, message):
     if message.header == NodeAlgorithm.INI:
         node.memory['entry'] = None
         node.memory['unvisited'] = list(node.memory[self.neighborsKey])
         node.memory['next'] = node.memory['unvisited'].pop()
         if (node.memory['unvisited']):
             node.send(Message(header='T',
                               destination=node.memory['next']))
             node.send(Message(header='Visited',
                               destination=node.memory['unvisited']))
             node.status = 'VISITED'
         else:
             node.status = 'DONE'
Пример #23
0
    def active(self, node, message):       

        if message.header == 'Iteration_Completed':
            if not node.memory['Source']:
                node.send(Message(destination=node.memory['Parent'],
                                  header='Iteration_Completed',
                                  data=message.data))
            else:
                node.memory[self.routingTableKey][message.data] = message.source
                node.memory['Iteration'] += 1
                node.send(Message(destination=node.memory['Children'],
                                  header='Start_Iteration',
                                  data = node.memory['Iteration']))  
                self.compute_local_minimum(node, message)
                node.memory['Childcount'] = 0
                node.status = 'COMPUTING'

        if message.header == 'Start_Iteration':
            # u message.data se nalazi poslani 'Iteration'
            node.memory['Iteration'] = message.data
            self.compute_local_minimum(node, message)

            if len(node.memory['Children']) == 0:
                node.send(Message(destination=node.memory['Parent'],
                                  header='MinValue',
                                  data = node.memory['Minpath']))
            else:
                node.send(Message(destination=node.memory['Children'],
                                  header='Start_Iteration',
                                  data = node.memory['Iteration']))
                node.memory['Childcount'] = 0
                node.status = 'COMPUTING' 

        if message.header == 'Expand':
            node.send(Message(destination=node.memory['Exit'],
                              header='Expand',
                              data = (node.memory['Iteration'], message.data[1])))  
            if node.memory['Exit'] == node.memory['Mychoice'] not in node.memory['Children']:
                node.memory['Children'].append(node.memory['Mychoice'])   
                node.memory['Unvisited'].remove(node.memory['Mychoice'])
                node.memory['Termination_counter'] += 1  
           
        if message.header == 'Notify':
            node.memory['Unvisited'].remove(message.source)
            node.send(Message(destination=message.source,
                              header='Ack')) 

        if message.header == 'Terminate':            
            node.send(Message(destination=node.memory['Children'],
                              header='Terminate'))
            node.status='DONE' 

            # Ako si list, pocni slat Termination_complete
            if len(node.memory['Children']) == 0:
                node.send(Message(destination=node.memory['Parent'],
                                  header='Termination_complete'))
                if node.memory['Visited_status'] == True:
                    node.status = 'VISITED'
                else:
                    node.status = 'DFT_IDLE'
    def idle(self, node, message):
        header = 'Information'
        status = 'IDLE'
        node.memory[self.maxTempKey] = node.memory[self.temperatureKey]

        if message.header == 'Information' and not (
                node.memory[self.isReceivedKey]):

            node.memory[self.isReceivedKey] = True

            maxTemp = float(node.memory[self.temperatureKey])
            destination_nodes = list(node.memory[self.neighborsKey])
            node.memory[self.pathKey] = message.source
            destination_nodes.remove(message.source)

            if destination_nodes:
                for destination_node in destination_nodes:
                    if destination_node.status == 'INITIATOR':
                        destination_nodes.remove(destination_node)

            else:
                header = 'Max Temperature'
                destination_nodes = message.source
                status = 'DONE'

            node.send(
                Message(destination=destination_nodes,
                        header=header,
                        data=maxTemp))

        else:
            if (message.header == 'Max Temperature'):
                if node.memory[self.maxTempKey] < message.data:
                    node.memory[self.maxTempKey] = message.data

            node.memory[self.numReceived] += 1

            if node.memory[self.numReceived] == node.memory[
                    self.numNeighboursKey] - 1:
                header = 'Max Temperature'
                data = node.memory[self.maxTempKey]
                destination = node.memory[self.pathKey]

                node.send(
                    Message(destination=destination, header=header, data=data))

                status = 'DONE'

        node.status = status
    def receipt_of_test(self, node, message):

        j = message.source
        L = message.data[
            0]  # 0 je level - kasnije pretvoriti u dictionary da bude razumljivije
        N = message.data[1]
        #when a node recieves sush a test message, it checks weather or not its own fragment identity agrees with that of the test message...
        if L > node.memory[self.levelKey]:
            #..if the recieving node's fragment level is less than that of
            #the test message then the recieving node delays any response
            #until its own level increasses sufficiently
            node.memory[self.queueKey].append(
                message)  #then place received message on end of queue
            print(
                node.id, "lvl:", node.memory[self.levelKey], "n:",
                node.memory[self.nameKey],
                "ja sada ne mogu odgovoriti jer je moj level manji od posiljatelja ",
                j.id)
            #self.network.outbox.insert(0, Message(header=message.header,data=message.data,destination=node, source=message.source))
        elif N != node.memory[self.nameKey]:
            # if the node recieving node has a different identity from the test message
            # and if the recieving node's fragment level is greather than or equal to that of the test message
            # then the Accept message is sent back to the sending node

            #Ali to je staro ime? Prije absporba?
            print("posiljatelj, primatelj", N, node.memory[self.nameKey])
            node.send(Message(header="Accept", data=0, destination=j))
            print(node.id, "lvl:", node.memory[self.levelKey], "n:",
                  node.memory[self.nameKey], "Accepting", j.id)
            #Zasto on sebi ne postavlja node u status BRANCH?

            #when a node a sends an Accept message in response to B's Test message,
            #then the fragment identity of A differs and will continue to differ,
            #from B's current fragment identity
            #Zasto on sebi ne postavlja node u status BRANCH?

        else:
            if node.memory[self.linkStatusKey][j] == 'BASIC':  #UNUSED
                node.memory[self.linkStatusKey][j] = 'REJECTED'
                #if node.memory[self.testEdgeKey]!=j or node.memory[self.testEdgeKey]==None:
                print(node.id, "mijenjam status linka prema ", j)
            if node.memory[self.testEdgeKey] != j:  #id!!!
                node.send(Message(header="Reject", data=0, destination=j))
                print(node.id, "lvl:", node.memory[self.levelKey], "n:",
                      node.memory[self.nameKey], "Rejecting", j.id)
            else:
                print("Test!")
                self.test(node)
    def initializer(self):
        ini_nodes = []

        #jedan SIGURAN inicijator
        #one_initiator=self.network.nodes()[randrange(1,len(self.network.nodes()),1)]
        #ini_nodes.append(one_initiator)

        #inicijator node 0
        initiator_1 = self.network.nodes()[0]
        ini_nodes.append(initiator_1)

        for node in self.network.nodes():
            node.memory[
                self.neighborsKey] = node.compositeSensor.read()['Neighbors']
            self.initialize(node)
            node.status = 'SLEEPING'
            # 30% inicijatora
            #if random()<0.3 and node!=one_initiator:  #random initiators
            #    ini_nodes.append(node)

        net = self.network
        for node, neighbors in net.adjacency_iter():
            for neighbor, eattr in neighbors.items():
                weight = eattr['weight']
                node.memory[self.weightKey][neighbor][0] = weight

        for ini_node in ini_nodes:
            self.network.outbox.insert(
                0, Message(header=NodeAlgorithm.INI,
                           destination=ini_node))  # to je spontani impuls
        print("inicijatori", ini_nodes)
    def test(self, node):
        test_nodes = {}

        for key in node.memory[self.linkStatusKey]:
            if node.memory[
                    self.linkStatusKey][key] == 'BASIC':  #mozda ne radi?!
                #test_nodes[key]=node.memory[self.linkStatusKey][key]
                test_nodes[key] = node.memory[self.weightKey][key]

        if len(test_nodes) != 0:
            test_node = self.adjacent_node_of_minimum_weight(test_nodes)
            node.memory[self.testEdgeKey] = test_node
            l = [node.memory[self.levelKey], node.memory[self.nameKey]]  #SHIT

            node.send(
                Message(header="Test",
                        data=l,
                        destination=node.memory[self.testEdgeKey]))
            print(
                node.id, "lvl:", node.memory[self.levelKey], "n:",
                node.memory[self.nameKey], " najlaksi link je prema ",
                test_node.id, "saljem Test"
            )  #edge prestaje biti basic, postaje rejected ili branch, tako se izbjegava da ponovno bude odabran
        else:
            node.memory[self.testEdgeKey] = None
            self.report(node)
Пример #28
0
 def initiator(self, node, message):
     # logger.info("INI")
     if message.header == NodeAlgorithm.INI:
         # default destination: send to every neighbor
         node.send(Message(header='Information',
                           data=node.memory[self.informationKey]))
     node.status = 'RECEIVE'
Пример #29
0
 def initializer(self):
     """ Pass INI message to certain nodes in network based on type."""
     node = self.network.nodes()[0]
     self.network.outbox.insert(0, Message(header=NodeAlgorithm.INI,
                                          destination=node))
     for node in self.network.nodes():
         node.status = 'IDLE'
Пример #30
0
    def send_data(self, node, message):
        # logger.info("SEND")
        # node.status = 'DONE'
        global tries
        for child_node in self.network.nodes():

            # child_node.outbox.insert(0, Message(header="DataPacket", source=child_node,
            #                                    data="Data-" + str(child_node.id)))
            #
            detination = None
            if 'destinaion' in child_node.memory:
                detination = [child_node.memory['destination']]
            child_node.send(Message(header="DataPacket", source=child_node, destination=detination,
                                    data="Data-" + str(self.tries) + "*" + str(child_node.id) + '+' +
                                         str(child_node.power.energy)))

            # str(range(int(rand(1)[0]*10))) ))
        # manage node
        for child_node in self.network.nodes():
            if child_node.mobility.mobile_type != 0:
                x, y, z = child_node.mobility.drift()
                child_node.network.pos[child_node] += (x, y)

            child_node.power.increase_energy(charging_time=DATA_RATE)  # charging
            child_node.power.decrease_energy(discharging_time=DATA_RATE)  # idle discharge
            child_node.energy.append(child_node.power.energy)

        self.tries += 1
        print self.tries
        if self.tries > MAX_TRIES:
            node.status = 'DONE'
        else:
            node.status = 'RECEIVE'
 def prepare_message(self, node, message):
     message = Message()
     message.data = node.memory['distance_sum'][node]
     message.header = 'Message'
     return message