Add centralised folder and initial implementations for decision system.
This commit is contained in:
21
DecisionSystem/CentralisedDecision/ballotvoter.py
Normal file
21
DecisionSystem/CentralisedDecision/ballotvoter.py
Normal file
@@ -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/')
|
||||||
|
|
||||||
53
DecisionSystem/CentralisedDecision/commander.py
Normal file
53
DecisionSystem/CentralisedDecision/commander.py
Normal file
@@ -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)
|
||||||
Reference in New Issue
Block a user