Change to use external messaging module

This commit is contained in:
Michael Pivato
2019-01-24 10:59:26 +10:30
parent 6de217a02f
commit 57db02a402
3 changed files with 174 additions and 38 deletions

View File

@@ -1,4 +1,3 @@
import paho.mqtt.client as mqtt
import time
from DecisionSystem.messages import Message, CommanderWill, RequestVote, GetSwarmParticipants, deserialise
import json
@@ -14,24 +13,17 @@ class Commander:
_votes = {}
_taking_votes = False
def __init__(self, timeout = 60):
def __init__(self, messenger, timeout = 60):
'''
Initial/default waiting time is 1 minute for votes to come in.
'''
self.timeout = timeout
# Default configuration file for testing.
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
self.client.on_disconnect = self.on_disconnect
self.client.connect(cfg["mqtt"]["host"], int(cfg["mqtt"]["port"]), int(cfg["mqtt"]["timeout"]))
# Don't forget to start the event loop!!!
self.client.loop_start()
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
@@ -65,13 +57,13 @@ class Commander:
self._taking_votes = True
# Publish a message that votes are needed.
print("Sending request message")
self.client.publish("swarm1/voters", RequestVote(self.client._client_id).serialise())
self._messenger.broadcast_message(self._messenger.swarm, RequestVote(self._messenger.id).serialise())
print("published message")
time.sleep(self.timeout)
self._taking_votes = False
return self.make_decision()
def on_message(self, client, userdata, message):
def on_message(self, message):
print("Message Received")
messageD = None
try:
@@ -101,16 +93,18 @@ class Commander:
print("Voter disconnected :(")
self._connectedVoters.remove(messageD.sender)
def on_connect(self, client, userdata, flags, rc):
self.client.subscribe("swarm1/commander")
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.client.publish("swarm1/voters", GetSwarmParticipants().serialise())
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, client, userdata, rc):
def on_disconnect(self, rc):
pass