from paho.mqtt import client as mqtt_client import random import time import json from prompt_toolkit import PromptSession, prompt from prompt_toolkit.patch_stdout import patch_stdout broker = '162.199.59.89' port = 1883 topic = "python/mqtt" client_id = f'python-mqtt-{random.randint(0, 1000)}' username = "nico" password = "nico" 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_id) client.username_pw_set(username, password) client.on_connect = on_connect client.connect(broker, port) return client def publish(client): msg_count = 1 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 def subscribe(client: mqtt_client.Client): def on_message(client, userdata, msg): try: payload = json.loads(msg.payload.decode()) sender_id = payload.get("sender_id") message = payload.get("message") #print(sender_id, client_id) if sender_id != username: print(f"{sender_id}: {message}") except json.JSONDecodeError: print(f"Received non-JSON message: {msg.payload.decode()}") client.subscribe(topic) client.on_message = on_message def console(client: mqtt_client.Client): session = PromptSession() with patch_stdout(): while True: try: msg = session.prompt(f"{username}: ", multiline=True) if msg.strip().lower() == 'exit': break payload = json.dumps({"sender_id": username, "message": msg}) result = client.publish(topic, payload) if result.rc != 0: print("Failed to publish message") except KeyboardInterrupt: break def run(): client = connect_mqtt() subscribe(client) client.loop_start() console(client) #client.loop_stop() #publish(client) #client.loop_forever() run()