# python 3.11 import random import time from paho.mqtt import client as mqtt_client from paho.mqtt.client import CallbackAPIVersion broker = 'mqtt.meezenest.nl' port = 1883 topic = "python/mqtt" # Generate a Client ID with the publish prefix. client_id = f'publish-{random.randint(0, 1000)}' # username = 'emqx' # password = 'public' msg_count = 1 def connect_mqtt(): def on_connect(client, userdata, flags, rc, properties): if rc == 0: print("Connected to MQTT Broker!") else: print("Failed to connect, return code %d\n", rc) def on_disconnect(client, userdata, rc): print("Disconnected with result code: %s", rc) reconnect_count, reconnect_delay = 0, FIRST_RECONNECT_DELAY while reconnect_count < MAX_RECONNECT_COUNT: print("Reconnecting in %d seconds...", reconnect_delay) time.sleep(reconnect_delay) try: client.reconnect() print("Reconnected successfully!") return except Exception as err: logging.error("%s. Reconnect failed. Retrying...", err) reconnect_delay *= RECONNECT_RATE reconnect_delay = min(reconnect_delay, MAX_RECONNECT_DELAY) reconnect_count += 1 print("Reconnect failed after %s attempts. Exiting...", reconnect_count) global FLAG_EXIT FLAG_EXIT = True client = mqtt_client.Client(CallbackAPIVersion.VERSION2, client_id) # client.username_pw_set(username, password) client.on_connect = on_connect client.on_disconnect = on_disconnect client.connect(broker, port, 120) return client def publish(client): global msg_count #while True: time.sleep(1) 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 if msg_count > 5: #break msg_count=1 def run(): client = connect_mqtt() client.loop_start() while 1: if client.is_connected(): print(client.is_connected()) publish(client) #else: #client.loop_stop() client.loop_stop() if __name__ == '__main__': run()