import time import ssl from paho.mqtt import client as mqtt_client broker = '100.10.1.100' port = 8883 topic = "python/mqtt" client_id = 'simple' username = 'simple' password = 'simple' def connect_mqtt(): def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to MQTT Broker!") else: print("Failed to connect, return code %d\n", rc) client = mqtt_client.Client(client_id) client.username_pw_set(username, password) context = ssl.create_default_context() context.check_hostname = False context.verify_mode = ssl.CERT_NONE client.tls_set_context(context) client.on_connect = on_connect client.connect(broker, port) return client def publish(client): msg_count = 0 while True: time.sleep(2) msg = f"messages: {msg_count}" result = client.publish(topic, msg) # result: [0, 1] status = result[0] if status == 0: print(f"Send `{msg}` to topic `{topic}`") else: print(f"Failed to send message to topic {topic}") msg_count += 1 def run(): client = connect_mqtt() client.loop_start() publish(client) if __name__ == '__main__': run()