tps/2C2024/1/scripts/subscriber.py (1632B)
1 import paho.mqtt.client as mqtt 2 3 # Configuración 4 broker = "broker.hivemq.com" 5 #broker = "mqtt-dashboard.com" 6 7 topic = "tp1/klockner" 8 output_file = 'output.txt' 9 received_fragments = {} 10 last_fragment = False 11 12 def on_subscribe(self, mqttc, obj, mid, granted_qos): 13 print("Subscribed: "+str(mid)+" "+str(granted_qos)) 14 15 def on_message(client, userdata, msg): 16 global last_fragment 17 18 # Decodificar mensaje: número de fragmento, tamaño, bandera de último fragmento, y contenido 19 payload = msg.payload.decode('utf-8') 20 fragment_info, fragment = payload.rsplit('|', 1) 21 fragment_number, fragment_size, is_last = map(int, fragment_info.split('|')[:3]) 22 23 received_fragments[fragment_number] = (fragment_size, fragment) 24 print(f"Fragmento recibido {fragment_number} (size: {fragment_size})") 25 if is_last == 1: 26 last_fragment = True 27 28 # Reensamblar si es el último fragmento 29 if last_fragment: 30 reassemble_file(output_file) 31 # quit() 32 last_fragment = False 33 34 def reassemble_file(filename): 35 with open(filename, 'w') as file: 36 for fragment_number in sorted(received_fragments): 37 fragment_size, fragment = received_fragments[fragment_number] 38 file.write(fragment[:fragment_size]) # Reescribimos usando el largo correcto 39 print(f"File reassembled as {filename}") 40 41 # Configuración del cliente MQTT 42 client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2) 43 client.on_message = on_message 44 client.on_subscribe = on_subscribe 45 46 client.connect(broker, 1883, 60) 47 client.subscribe(topic, qos=2) 48 49 # Mantener el cliente en funcionamiento 50 client.loop_forever()