Files
picar/DecisionSystem/CentralisedDecision/ballotvoter.py
2019-01-18 16:35:52 +10:30

64 lines
2.4 KiB
Python

import paho.mqtt.client as mqtt
import json
from DecisionSystem.messages import ConnectSwarm, SubmitVote, Message, deserialise, RequestVote
class BallotVoter:
def __init__(self, on_vote):
# Load config file
cfg = None
with open('../config.json') as json_config:
cfg = json.load(json_config)
self._cfg = cfg
self.client = mqtt.Client()
self.client.on_connect = self.on_connect
self.client.on_message = self.on_message
# id is generated automatically.
self.client.connect(cfg["mqtt"]["host"], cfg["mqtt"]["port"], cfg["mqtt"]["timeout"])
self.client.loop_start()
self.on_vote = on_vote
def on_connect(self, client, userdata, flags, rc):
print("Connected with result code " + str(rc))
self.client.subscribe('swarm1/voters', qos=1)
# Need to set a will as well to broadcast on unexpected disconnection, so commander
# knows it is no longer part of the set of voters.
# Leaving this until core centralised system is working.
#will_message = {"type": "UDisconnect"}
# Tell commander we are now connected.
# self.send_connect()
def on_message(self, client, userdata, message):
print("Message Received!")
messageD = deserialise(message.payload)
print("Message Type: " + messageD.type)
# Ok message.
if messageD.type == RequestVote().type:
print('Received vote message')
self.submit_vote()
elif messageD.type == "listening":
self.send_connect()
elif messageD.type == "disconnectedcommander":
# Elect new leader...
# Might just use raft's method for electing a leader,
# by doing a random timeout then choosing itself as the candidate,
# and collects who is part of the swarm. This may need to be another class...
pass
def submit_vote(self):
v = self.on_vote()
print("Got Vote")
vote = SubmitVote(v, self.client._client_id)
print('created vote')
self.client.publish('swarm1/commander', vote.serialise())
print('published vote')
def send_connect(self):
# Send a connected message to let any commanders know that
# it is available.
self.client.publish("swarm1/commander", ConnectSwarm(self.client._client_id).serialise())