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)