tps/2C2024/1/scripts/publisher.py (1869B)
1 import paho.mqtt.client as mqtt 2 import random 3 import time 4 # Configuración 5 broker_address = "broker.hivemq.com" 6 #broker_address = "mqtt-dashboard.com" 7 8 topic = "tp1/klockner" 9 min_size = 50 # Tamaño mínimo del fragmento 10 max_size = 70 # Tamaño máximo del fragmento 11 file_to_publish = 'input.txt' 12 13 def on_connect(client, userdata, flags, rc): 14 # Al conectarse, configuramos la opción TCP_NODELAY 15 client_socket = client._socket().socket # Accede al socket subyacente 16 client_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # Desactiva Nagle 17 18 def on_subscribe(self, mqttc, obj, mid, granted_qos): 19 print("Subscribed: "+str(mid)+" "+str(granted_qos)) 20 21 def publish_file(client, filename, min_size, max_size): 22 with open(filename, 'r') as file: 23 content = file.read() 24 25 index = 0 26 fragment_number = 0 27 while index < len(content): 28 fragment_size = random.randint(min_size, max_size) 29 fragment = content[index:index+fragment_size] 30 31 # Metadatos: número de fragmento, tamaño, y bandera de último fragmento 32 is_last = 1 if index + fragment_size >= len(content) else 0 33 payload = f'{fragment_number}|{fragment_size}|{is_last}|{fragment}' 34 client.publish(topic, payload, qos=2, retain=False) 35 print(f"Fragmento publicado {fragment_number} (size: {fragment_size})") 36 index += fragment_size 37 fragment_number += 1 38 time.sleep(1) 39 40 # Configuración del cliente MQTT 41 client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2) 42 client.on_connect = on_connect # Añade el manejador de eventos para cuando se conecte 43 client.on_subscribe = on_subscribe # Añade el manejador de suscripción 44 client.connect(broker_address, 1883, 60) 45 46 # Publicar el archivo fragmentado 47 publish_file(client, file_to_publish, min_size, max_size) 48 49 client.disconnect()