repos/TB067

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