diff --git a/DecisionSystem/CentralisedDecision/ballotvoter.py b/DecisionSystem/CentralisedDecision/ballotvoter.py new file mode 100644 index 0000000..fd24914 --- /dev/null +++ b/DecisionSystem/CentralisedDecision/ballotvoter.py @@ -0,0 +1,21 @@ +import paho.mqtt.client as mqtt + +class BallotVoter: + def __init__(self): + self.client = mqtt.Client() + self.client.connect('172.16.43.2') + + def on_connect(self, client, userdata, flags, rc): + print("Connected with result code " + str(rc)) + if rc == 0: + global connected + connected = True + + self.client.subscribe('swarm1/voters', qos=1) + + def on_message(self, client, userdata, message): + + + def submit_vote(self): + self.client.publish('swarm1/') + \ No newline at end of file diff --git a/DecisionSystem/CentralisedDecision/commander.py b/DecisionSystem/CentralisedDecision/commander.py new file mode 100644 index 0000000..ac3d0f0 --- /dev/null +++ b/DecisionSystem/CentralisedDecision/commander.py @@ -0,0 +1,53 @@ +import Messaging.mqttsession as ms +import time +import umsgpack + +class Commander: + currentVote = None + + def __init__(self, timeout = 60): + ''' + Initial/default waiting time is 1 minute for votes to come in. + ''' + self.timeout = timeout + self._votes = [] + ms.Client() + + def on_message(client, userdata, message): + self._votes.append(umsgpack.unpackb(message.payload)) + + ms.client.subscribe("FakeSwarm/FirstTest", on_message) + + ms.client.loop_start() + + def make_decision(self): + votes = self._votes + dif_votes = {} + + for vote in votes: + # Get the average/max, etc. + if str(vote) in dif_votes: + dif_votes[str(vote)] = dif_votes[str(vote)] + 1 + else: + dif_votes[str(vote)] = 1 + + max_vote = None + max_vote_num = 0 + for vote in dif_votes.keys(): + if dif_votes[vote] > max_vote_num: + max_vote = vote + max_vote_num = dif_votes[vote] + + return max_vote + + def get_votes(self, topic, message, qos=0): + # Publish a message that votes are needed. + ms.client.publish(topic, message, qos) + time.sleep(self.timeout) + self.make_decision() + + def add_subscription(self, topic, callback=None, qos=0): + ms.client.subscribe(topic) + + if callback is not None: + ms.client.message_callback_add(topic, callback) \ No newline at end of file