Add 'car/' from commit 'eee0e8dc445691e600680f4abc77f2814b20b054'
git-subtree-dir: car git-subtree-mainline:1d29a5526cgit-subtree-split:eee0e8dc44
This commit is contained in:
119
car/DecisionSystem/CentralisedDecision/commander.py
Normal file
119
car/DecisionSystem/CentralisedDecision/commander.py
Normal file
@@ -0,0 +1,119 @@
|
||||
import time
|
||||
from DecisionSystem.messages import Message, CommanderWill, RequestVote, GetSwarmParticipants, deserialise, ClientVoteRequest, VoteResult
|
||||
import json
|
||||
import numpy as np
|
||||
|
||||
class Commander:
|
||||
currentVote = None
|
||||
|
||||
# Stores voters that connect to maintain a majority.
|
||||
# Voters who do not vote in latest round are removed.
|
||||
_connectedVoters = []
|
||||
# Dict has format: {clientId: vote}
|
||||
_votes = {}
|
||||
_taking_votes = False
|
||||
|
||||
def __init__(self, messenger, timeout = 60):
|
||||
'''
|
||||
Initial/default waiting time is 1 minute for votes to come in.
|
||||
'''
|
||||
self.timeout = timeout
|
||||
|
||||
self._messenger = messenger
|
||||
self._messenger.add_connect(self.on_connect)
|
||||
self._messenger.add_message_callback(self.on_message)
|
||||
self._messenger.add_disconnect_callback(self.on_disconnect)
|
||||
print('Connecting')
|
||||
|
||||
def make_decision(self):
|
||||
# Should change this to follow strategy pattern, for different implementations of
|
||||
# making a decision on the votes.
|
||||
print("Making a decision")
|
||||
votes = self._votes.values()
|
||||
print(type(votes))
|
||||
dif_votes = {}
|
||||
|
||||
for vote in votes:
|
||||
# Get the count of different votes.
|
||||
if vote in dif_votes:
|
||||
dif_votes[vote] = dif_votes[vote] + 1
|
||||
else:
|
||||
dif_votes[vote] = 1
|
||||
|
||||
max_vote = ""
|
||||
max_vote_num = 0
|
||||
# Should try using a numpy array for this.
|
||||
|
||||
for vote in dif_votes.keys():
|
||||
if dif_votes[vote] > max_vote_num:
|
||||
max_vote = vote
|
||||
max_vote_num = dif_votes[vote]
|
||||
|
||||
print("Made Decision!")
|
||||
return max_vote
|
||||
|
||||
def get_votes(self):
|
||||
# Should abstract messaging to another class.
|
||||
print("Gathering Votes")
|
||||
self._taking_votes = True
|
||||
# Publish a message that votes are needed.
|
||||
print("Sending request message")
|
||||
self._messenger.broadcast_message(self._messenger.swarm, RequestVote(self._messenger.id).serialise())
|
||||
print("published message")
|
||||
time.sleep(self.timeout)
|
||||
self._taking_votes = False
|
||||
# TODO: Work out how to broadcast votes back to the swarm, maybe using raft?
|
||||
return self.make_decision()
|
||||
|
||||
def on_message(self, message):
|
||||
print("Message Received")
|
||||
messageD = None
|
||||
try:
|
||||
messageD = deserialise(message.payload)
|
||||
except:
|
||||
print("Incorrect Message Has Been Sent")
|
||||
return
|
||||
|
||||
# Need to consider that a malicious message may have a type with incorrect subtypes.
|
||||
if messageD.type == "connect":
|
||||
print("Voter connected!")
|
||||
# Voter just connected/reconnnected.
|
||||
if not messageD["client"] in self._connectedVoters:
|
||||
self._connectedVoters.append(messageD["client"])
|
||||
elif messageD.type == "vote":
|
||||
print("Received a vote!")
|
||||
# Voter is sending in their vote.
|
||||
print(messageD.data["vote"])
|
||||
print("From: ", messageD.sender)
|
||||
if self._taking_votes:
|
||||
# Commander must have requested their taking votes, and the timeout
|
||||
# has not occurred.
|
||||
# Only add vote to list if the client has not already voted.
|
||||
if messageD.sender not in self._votes:
|
||||
self._votes[messageD.sender] = int(messageD.data["vote"])
|
||||
elif messageD.type == ClientVoteRequest().type:
|
||||
# received a request to get votes/consensus.
|
||||
self.get_votes()
|
||||
|
||||
elif messageD.type == "disconnected":
|
||||
print("Voter disconnected :(")
|
||||
self._connectedVoters.remove(messageD.sender)
|
||||
|
||||
def on_connect(self, rc):
|
||||
# Subscribes now handled by the mqtt messenger, this is just here
|
||||
# for convenience later.
|
||||
pass
|
||||
|
||||
def get_participants(self):
|
||||
self._messenger.broadcast_message(self._messenger.swarm, GetSwarmParticipants().serialise())
|
||||
# Commander needs a will message too, for the decentralised version, so the
|
||||
# voters know to pick a new commander.
|
||||
# If using apache zookeeper this won't be needed.
|
||||
# That's the wrong method for setting a will.
|
||||
# self.client.publish("swarm1/voters", CommanderWill(self.client._client_id).serialise())
|
||||
|
||||
def on_disconnect(self, rc):
|
||||
pass
|
||||
|
||||
def propogate_result(self, result):
|
||||
self._messenger.broadcast_message(self._messenger.swarm, )
|
||||
Reference in New Issue
Block a user