def main(): client = MQTTClient( project_id=config.project_id, cloud_region=config.cloud_region, registry_id=config.registry_id, device_id=config.device_id, private_key_file=config.private_key_file, algorithm=config.jwt_algorithm, ca_certs=config.ssl_ca_certs, mqtt_bridge_hostname=config.mqtt_bridge_hostname, mqtt_bridge_port=config.mqtt_bridge_port ) client.loop() loop = asyncio.get_event_loop() while True: loop.run_until_complete(run(client))
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()
from mqtt_client import MQTTClient import ssl import json import paho.mqtt.client as mqtt with open("config/config.json", "r") as load_f: parameter = json.load(load_f) cli = MQTTClient(parameter["host"], parameter["port"]) cli.tls_set(parameter["ca_cert"], parameter["certfile"], parameter["keyfile"]) cli.on_log cli.connect(parameter["username"], parameter["password"]) cli.on_connect cli.subscribe(parameter["topic0"]) cli._on_message cli.loop()