class Server(object): def __init__(self, channel, host, port, username=None, password=None): self.channel = channel self.host = host self.port = port self.client = MQTTClient( userdata={ "server": self, "channel": self.channel, "host": self.host, "port": self.port, }, callbacks={ 'on_connect': on_connect, 'on_disconnect': on_disconnect, 'on_message': on_message, } ).connect() def stop_server(self, signum, frame): logger.info("Received signal {}, terminating".format(signum)) self.stop = True def set_signal_handlers(self): signal.signal(signal.SIGTERM, self.stop_server) signal.signal(signal.SIGINT, self.stop_server) def run(self): self.stop = False self.set_signal_handlers() logger.info("Starting loop") while not self.stop: logger.debug("Restarting loop") self.client.loop() self.client.disconnect()