commit 568d6b4eeca33ad0ad58c8cf980ea871d3a65c33
parent 0bbfc3acbb4e80478724e0f15e147ce80e504778
Author: Martin Kloeckner <mjkloeckner@gmail.com>
Date: Fri, 18 Oct 2024 16:35:57 -0300
update `tps/2C2024/` files
Diffstat:
13 files changed, 404 insertions(+), 427 deletions(-)
diff --git a/tps/2C2024/1/capturas_wireshark/captura_aguilar_publisher.pcapng b/tps/2C2024/1/capturas_wireshark/captura_aguilar_publisher.pcapng
Binary files differ.
diff --git a/tps/2C2024/1/capturas_wireshark/captura_klockner_subscriber.pcapng b/tps/2C2024/1/capturas_wireshark/captura_klockner_subscriber.pcapng
Binary files differ.
diff --git a/tps/2C2024/1/informe.pdf b/tps/2C2024/1/informe.pdf
Binary files differ.
diff --git a/tps/2C2024/1/informe/informe.md b/tps/2C2024/1/informe/informe.md
@@ -1,84 +0,0 @@
-# Nivel de Transporte y de Red del Modelo TCP/IP
-
-Redes de Comunicaciones (TB067) - 2C2024 - FIUBA
-Martin Klöckner (123456) - [mklockner@fi.uba.ar](mailto:mklockner@fi.uba.ar)
-Matteo Aguilar Cafferata (123456) - [meaguilar@fi.uba.ar](meaguilar@fi.uba.ar)
-
-## El protocolo MQTT
-
-MQTT (Message Query Telemetry Transport) es un protocolo de red ligero y
-eficiente, implementado de extremo a extremo y con patron publisher-subscriber
-(editor-suscriptor).
-
-Este protocolo está diseñado principalmente para dispositivos en locaciones
-remotas con recursos y/o ancho de banda limitado, tal como sistemas embebidos.
-
-El protocolo MQTT se ubica en el nivel de aplicación del modelo TCP/IP por lo
-que requiere de un protocolo de transporte subyacente; en particular uno que sea
-ordenado, seguro y sin perdida de datos, tal como el protocolo TCP.
-
-### Seguridad
-
-Encriptacion
-
-### Aplicaciones Comerciales
-
-### Versiones
-
-Las versiones de MQTT son controladas por la organización sin fines de lucro
-OASIS (Organization for the Advancement of Structured Information Standards)
-
-#### MQTT 5
-#### MQTT 3.1.1
-#### MQTT 3.1
-#### MQTT-SN v1.2
-
-### Referencias
-
-[MQTT: The Standard for IoT Messaging](https://mqtt.org/)
-[¿Qué es MQTT?](https://aws.amazon.com/es/what-is/mqtt/)
-[A expandir](https://www.paessler.com/es/it-explained/mqtt).
-
-## Uso Práctico
-
-> Sobre la aplicación, ¿de qué modo consigue implementar la fragmentación?
-
-> En comparación con la fragmentación que implementa el protocolo TCP, ¿hay
-> funcionalidades o características de la fragmentación en estos scripts que
-> sean similares a la segmentación TCP? ¿Cuáles?
-
-> En comparación con la segmentación que implementa el protocolo TCP, ¿hay
-> funcionalidades o características de la segmentación TCP que en estos scripts
-> estén ausentes? ¿Cuáles?
-
-> Acerca de las sesiones del publicador y del suscriptor, ¿cuáles son los
-> extremos de las sesiones? ¿quién toma el rol de cliente y quién de servidor?
-
-> Sobre la extensión de las sesiones, ¿son persistentes, cómo se sostienen
-> cuando no hay tráfico? ¿no son persistentes? ¿cómo se cierran (en qué momento
-> y quién lo inicia)?
-
-> En detalle sobre las sesiones:
-> a. ¿Cuál es el número de secuencia del primer segmento TCP de
-> petición de conexión?
-> b. ¿Cuáles son las opciones implementadas, si las hay?
-> c. ¿Cuántos bytes tiene el buffer de recepción según se informa al inicio?
-> d. ¿A qué hora se envió el primer segmento (el que contiene datos de la
-> aplicación)? ¿A qué hora se recibió el ACK de este primer segmento
-> que contiene datos? ¿Cuál es su RTT?
-> e. ¿Cuál es la longitud (encabezado más carga útil) de cada uno de los
-> primeros cuatro segmentos TCP que transportan datos?
-
-> HTTP indica la cantidad de datos a transmitir mediante un encabezado. Esta
-> adecuación de MQTT para transmitir fragmentos no comunica la cantidad de datos
-> que va a transmitir. Si algún paquete se perdiera, el suscriptor no tendría
-> forma de detectar la falta. Modificar el código para simular la pérdida de un
-> paquete intermedio y verificar en el suscriptor que el texto quede truncado.
-> Luego modificar ambos scripts para que se comunique el largo de los datos a
-> transmitir y que el suscriptor pueda validar la cantidad de datos recibidos
-> versus los esperados.
-
-> De las funcionalidades o características vinculadas a segmentación, presentes
-> en TCP pero no cubiertas por estos scripts, implementar una versión mejorada,
-> que incorpore al menos una mejora o una funcionalidad. Se puede usar
-> inteligencia artificial y por qué no, inteligencia natural.
diff --git a/tps/2C2024/1/informe/style.tex b/tps/2C2024/1/informe/style.tex
@@ -1,235 +0,0 @@
-% \documentclass[14pt]{extarticle}
-
-% page setup
-\usepackage[a4paper,
- top=2.5cm,
- bottom=2.5cm,
- left=2.00cm,
- right=2.00cm,
- bmargin=2.0cm]{geometry}
-
-\usepackage{titlesec}
-\usepackage{fontspec}
-\usepackage{tabularx}
-
-% make pictures caption font bold and small
-\usepackage[font={footnotesize,bf}]{caption}
-
-% inline code (backticks in md)
-\linespread{1.05}
-% \definecolor{bgcolor}{HTML}{e0e0e0}
-\definecolor{bgcolor}{HTML}{f8f8f8}
-\let\oldtexttt\texttt
-
-\renewcommand{\texttt}[1]{
- % \colorbox{bgcolor}{\oldtexttt{#1}}
- \tcbox[ on line,
- boxsep=1pt,
- left=0pt,
- right=0pt,
- top=0pt,
- bottom=0pt,
- arc=1pt,
- outer arc=1pt,
- grow to left by=2.5pt,
- grow to right by=2.5pt,
- colframe=bgcolor,
- colback=bgcolor]{\oldtexttt{#1}}
-}
-
-% code blocks
-\usepackage{verbatimbox}
-\newenvironment{fullgrayverb}
-{\verbbox}
-% {\endverbbox\par\colorbox{gray!25}{\parbox{\textwidth}{\theverbbox}}\par}
-{\endverbbox\par\colorbox{bgcolor}{\parbox{\textwidth}{\theverbbox}}\par}
-
-% change boldfont bold to extrabold
-% \setmainfont[
-% BoldFont={Inter-ExtraBold}
-% ]{Inter}
-
-% change regular font to light font
-% \setmainfont{Inter light}
-
-\newfontfamily\titlefont{Inter}[
-UprightFont = *-Regular,
-BoldFont = *-ExtraBold,
-Scale = 1.00
-]
-
-\newfontfamily\sectionsfont{Inter}[
-UprightFont = *-Regular,
-BoldFont = *-Bold,
-]
-
-\setmathfont{Fira Math}
-
-\usepackage{xcolor}
-\definecolor{ugrey}{HTML}{333333}
-
-\titleformat{\section}
-{\color{ugrey}\titlefont\LARGE\bfseries}
-{\color{ugrey}}
-{0em}
-{}
-
-\titleformat{\subsection}
-{\color{ugrey}\sectionsfont\Large\bfseries}
-{\color{ugrey}}
-{0em}
-{}
-
-\titleformat{\subsubsection}
-{\color{ugrey}\sectionsfont\large\bfseries}
-{\color{ugrey}}
-{0em}
-{}
-
-\titleformat{\paragraph}
-{\color{ugrey}\sectionsfont\normalsize\bfseries}
-{\color{ugrey}\theparagraph}
-{0em}
-{}
-
-\titleformat{\subparagraph}
-{\color{ugrey}\normalfont\bfseries}
-{\color{ugrey}\theparagraph}
-{0em}
-{}
-
-% spacing: how to read {12pt plus 4pt minus 2pt}
-% 12pt is what we would like the spacing to be
-% plus 4pt means that TeX can stretch it by at most 4pt
-% minus 2pt means that TeX can shrink it by at most 2pt
-%
-% \titlespacing{command}{left spacing}{before spacing}{after spacing}[right]
-
-\titlespacing*{\section}
-{0pt}{2ex plus 1ex minus .2ex}{1.75ex plus .2ex}
-
-\titlespacing*{\subsection}
-{0pt}{1.75ex plus 1ex minus .2ex}{1.5ex plus .2ex}
-
-\titlespacing*{\subsubsection}
-{0pt}{1.5ex plus 1ex minus .2ex}{1.25ex plus .2ex}
-
-\titlespacing*{\paragraph}
-{0pt}{1.5ex plus 1ex minus .2ex}{1.0ex plus .2ex}
-
-\titlespacing*{\subparagraph}
-{0pt}{1.25ex plus 1ex minus .2ex}{1.0ex plus .2ex}
-
-% spacing between formulas and text
-\setlength{\abovedisplayskip}{5pt}
-\setlength{\belowdisplayskip}{2pt}
-
-\setlength{\abovedisplayshortskip}{9pt}
-\setlength{\belowdisplayshortskip}{2pt}
-
-\setlength{\belowdisplayshortskip}{\belowdisplayskip}
-
-\setlength{\baselineskip}{10pt}
-
-% \usepackage{setspace}
-% \setstretch{1.25}
-
-% \renewcommand{\figurename}{Fig.}
-
-\usepackage{caption}
-\captionsetup{labelformat=empty}
-
-% \renewcommand{\contentsname}{Índice}
-\renewcommand\contentsname{\vspace*{-45pt}}
-
-% TOC dots separation
-% \renewcommand{\cftdotsep}{10}
-
-% \setlength{\cftsecindent}{0pt}% Remove indent for \section
-% \setlength{\cftsubsecindent}{5pt}% Remove indent for \subsection
-% \setlength{\cftsubsubsecindent}{0pt}% Remove indent for \subsubsec
-
-\setcounter{tocdepth}{4}
-
-\usepackage{titling}
-\renewcommand{\maketitle}{
- \begin{flushleft}
- {\bfseries\Huge\thetitle}
- \vspace{1mm}
- \end{flushleft}
- \thispagestyle{empty}
-}
-
-% remove the page number from all the pages that the TOC occupies
-\addtocontents{toc}{\protect\thispagestyle{empty}}
-
-% add page break after TOC set it to page number 1
-\let\oldtableofcontents\tableofcontents % remember the definition
-\renewcommand\tableofcontents{
- \oldtableofcontents % use the standard toc
- \thispagestyle{empty}
- \pagebreak
- \setcounter{page}{1}
-}
-
-% Set text color for all document
-% \color{ugrey}
-
-\usepackage[titles]{tocloft}
-\renewcommand{\cftdotsep}{1.5}
-\renewcommand{\cftsetpnumwidth}{1.5}
-\renewcommand{\cftsetrmarg}{1.5}
-
-\usepackage{float}
-\makeatletter
-\def\fps@figure{H}
-\makeatother
-
-% nicer chemical figures
-\usepackage{chemfig}
-
-% change style of quote, see also https://tex.stackexchange.com/a/436253/114857
-\usepackage[most]{tcolorbox}
-
-\definecolor{linequote}{RGB}{224,215,188}
-\definecolor{bordercolor}{RGB}{221,221,221}
-% \definecolor{backquote}{RGB}{249,245,233}
-\definecolor{backquote}{RGB}{230,230,230}
-
-% change left border: https://tex.stackexchange.com/a/475716/114857
-% change left margin: https://tex.stackexchange.com/a/457936/114857
-\newtcolorbox{myquote}[1][]{%
- enhanced,
- breakable,
- size=minimal,
- left=12pt,
- top=12pt,
- bottom=12pt,
- right=12pt,
- boxrule=1pt,
- sharp corners=all,
- % colback=backquote,
- colback=bgcolor,
- colframe=black,
- #1}
-
-% redefine quote environment to use the myquote environment, see
-% https://tex.stackexchange.com/a/337587/114857
-\renewenvironment{quote}{\begin{myquote}}{\end{myquote}}
-
-% better fractions
-\usepackage{nicefrac,xfrac}
-
-% surround footnotes number with square brackets and always use numbers (even
-% inside quoted text)
-% https://www.overleaf.com/learn/latex/Footnotes
-\renewcommand*{\thefootnote}{\ [\arabic{footnote}]\ }
-\renewcommand*{\thempfootnote}{\ [\arabic{mpfootnote}]\ }
-
-% space between text and footer
-\setlength\footskip{25pt}
-\setlength{\skip\footins}{12pt}
-
-% align first letter of all the lines in the footnotes
-\usepackage[bottomfloats,belowfloats,hang]{footmisc}
-\setlength{\footnotemargin}{1em}
diff --git a/tps/2C2024/1/scripts/input.txt b/tps/2C2024/1/scripts/input.txt
@@ -1,9 +1 @@
-Nos los representantes del pueblo de la Nación Argentina, reunidos en Congreso
-General Constituyente por voluntad y elección de las provincias que la componen,
-en cumplimiento de pactos preexistentes, con el objeto de constituir la unión
-nacional, afianzar la justicia, consolidar la paz interior, proveer a la defensa
-común, promover el bienestar general, y asegurar los beneficios de la libertad,
-para nosotros, para nuestra posteridad, y para todos los hombres del mundo que
-quieran habitar en el suelo argentino: invocando la protección de Dios, fuente
-de toda razón y justicia: ordenamos, decretamos y establecemos esta
-Constitución, para la Nación Argentina
+"Nos los representantes del pueblo de la Nación Argentina, reunidos en Congreso General Constituyente por voluntad y elección de las provincias que la componen, en cumplimiento de pactos preexistentes, con el objeto de constituir la unión nacional, afianzar la justicia, consolidar la paz interior, proveer a la defensa común, promover el bienestar general y asegurar los beneficios de la libertad para nosotros, para nuestra posteridad, y para todos los hombres del mundo que quieran habitar en el suelo argentino: invocando la protección de Dios, fuente de toda razón y justicia: ordenamos, decretamos y establecemos esta Constitución para la Nación Argentina."
+\ No newline at end of file
diff --git a/tps/2C2024/1/scripts/publisher-data-lost.py b/tps/2C2024/1/scripts/publisher-data-lost.py
@@ -0,0 +1,62 @@
+import paho.mqtt.client as mqtt
+import random
+import time
+# Configuración
+broker_address = "broker.hivemq.com"
+#broker_address = "mqtt-dashboard.com"
+
+topic = "tp1/aguilar_klockner" # <<<<<<<<<<====== Completar con el nombre del grupo
+min_size = 50 # Tamaño mínimo del fragmento
+max_size = 70 # Tamaño máximo del fragmento
+file_to_publish = 'input.txt'
+
+
+def on_connect(client, userdata, flags, rc):
+ # Al conectarse, configuramos la opción TCP_NODELAY
+ client_socket = client._socket().socket # Accede al socket subyacente
+ client_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # Desactiva Nagle
+
+def on_subscribe(self, mqttc, obj, mid, granted_qos):
+ print("Subscribed: "+str(mid)+" "+str(granted_qos))
+
+def publish_file(client, filename, min_size, max_size):
+ with open(filename, 'r') as file:
+ content = file.read()
+
+
+ index = 0
+ fragment_number = 0
+
+ #Toma la medida total de la informacion y la envia como paquete 0
+ lenght = len(content)
+ payload = f'{fragment_number}|{4}|{0}|{lenght}'
+ client.publish(topic, payload, qos=2, retain=False)
+ print(f"Fragmento publicado {fragment_number} (size: {4})")
+ fragment_number += 1
+
+ while index < len(content):
+ fragment_size = random.randint(min_size, max_size)
+ fragment = content[index:index+fragment_size]
+
+ # Metadatos: número de fragmento, tamaño, y bandera de último fragmento
+ is_last = 1 if index + fragment_size >= len(content) else 0
+ payload = f'{fragment_number}|{fragment_size}|{is_last}|{fragment}'
+
+ if fragment_number != 6: #Pierde un paquete aproposito
+ client.publish(topic, payload, qos=2, retain=False)
+ print(f"Fragmento publicado {fragment_number} (size: {fragment_size})")
+
+ index += fragment_size
+ fragment_number += 1
+ time.sleep(1)
+
+# Configuración del cliente MQTT
+client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
+client.on_connect = on_connect # Añade el manejador de eventos para cuando se conecte
+client.on_subscribe = on_subscribe # Añade el manejador de suscripción
+client.connect(broker_address, 1883, 60)
+
+# Publicar el archivo fragmentado
+publish_file(client, file_to_publish, min_size, max_size)
+
+client.disconnect()
diff --git a/tps/2C2024/1/scripts/publisher-missing-package.py b/tps/2C2024/1/scripts/publisher-missing-package.py
@@ -0,0 +1,53 @@
+import paho.mqtt.client as mqtt
+import random
+import time
+
+# Configuración
+broker_address = "broker.hivemq.com"
+# broker_address = "mqtt-dashboard.com"
+
+topic = "tp1/aguilar_klockner"
+min_size = 50 # Tamaño mínimo del fragmento
+max_size = 70 # Tamaño máximo del fragmento
+file_to_publish = 'input.txt'
+
+def on_connect(client, userdata, flags, rc):
+ # Al conectarse, configuramos la opción TCP_NODELAY
+ client_socket = client._socket().socket # Accede al socket subyacente
+ client_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # Desactiva Nagle
+
+def on_subscribe(self, mqttc, obj, mid, granted_qos):
+ print("Subscribed: "+str(mid)+" "+str(granted_qos))
+
+def publish_file(client, filename, min_size, max_size):
+ with open(filename, 'r') as file:
+ content = file.read()
+
+ index = 0
+ fragment_number = 0
+ while index < len(content):
+ fragment_size = random.randint(min_size, max_size)
+ fragment = content[index:index+fragment_size]
+
+ # Metadatos: número de fragmento, tamaño, y bandera de último fragmento
+ is_last = 1 if index + fragment_size >= len(content) else 0
+ payload = f'{fragment_number}|{fragment_size}|{is_last}|{fragment}'
+
+ if fragment_number != 6:
+ client.publish(topic, payload, qos=2, retain=False)
+ print(f"Fragmento publicado {fragment_number} (size: {fragment_size})")
+
+ fragment_number += 1
+ index += fragment_size
+ time.sleep(1)
+
+# Configuración del cliente MQTT
+client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
+client.on_connect = on_connect # Añade el manejador de eventos para cuando se conecte
+client.on_subscribe = on_subscribe # Añade el manejador de suscripción
+client.connect(broker_address, 1883, 60)
+
+# Publicar el archivo fragmentado
+publish_file(client, file_to_publish, min_size, max_size)
+
+client.disconnect()
diff --git a/tps/2C2024/1/scripts/publisher-secure.py b/tps/2C2024/1/scripts/publisher-secure.py
@@ -0,0 +1,68 @@
+import paho.mqtt.client as mqtt
+import random
+import time
+# Configuración
+broker_address = "broker.hivemq.com"
+#broker_address = "mqtt-dashboard.com"
+
+topic = "tp1/aguilar_klockner" # <<<<<<<<<<====== Completar con el nombre del grupo
+min_size = 100 # Tamaño mínimo del fragmento
+max_size = 150 # Tamaño máximo del fragmento
+file_to_publish = 'input.txt'
+
+
+def on_connect(client, userdata, flags, rc):
+ # Al conectarse, configuramos la opción TCP_NODELAY
+ client_socket = client._socket().socket # Accede al socket subyacente
+ client_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # Desactiva Nagle
+
+def on_subscribe(self, mqttc, obj, mid, granted_qos):
+ print("Subscribed: "+str(mid)+" "+str(granted_qos))
+
+def publish_file(client, filename, min_size, max_size):
+ with open(filename, 'r') as file:
+ content = file.read()
+
+
+ index = 0
+ fragment_number = 0
+ total_size = len(content)
+ control_size = 0
+ while index < total_size:
+ fragment_size = random.randint(min_size, max_size)
+ fragment = content[index:index+fragment_size]
+
+ # Metadatos: número de fragmento, tamaño, y bandera de último fragmento
+ is_last = 0
+ if random.randint(1, 100) > 10: #Establezco un 10% de perder el fragmento
+ payload = f'{fragment_number}|{fragment_size}|{is_last}|{fragment}'
+ client.publish(topic, payload, qos=2, retain=False)
+ control_size += fragment_size
+ print(f"Fragmento publicado {fragment_number} (size: {fragment_size})")
+ index += fragment_size
+ fragment_number += 1
+ time.sleep(1)
+
+ if control_size < total_size: # Detecto si se perdio un fragmento y reinicio el envio en ese caso enviando un mensansaje de error
+ payload = f'{-1}|{4}|{is_last}|{1}'
+ client.publish(topic, payload, qos=2, retain=False)
+ print(f"Fragmento publicado {-1} (size: {4})")
+ print(f"Error de transmision. Reiniciando secuencia")
+ publish_file(client, filename, min_size, max_size)
+ else: #En caso de exito envio mensaje de exito y finalizo
+ is_last = 1
+ payload = f'{100}|{4}|{is_last}|{0}'
+ client.publish(topic, payload, qos=2, retain=False)
+ print(f"Fragmento publicado {-0} (size: {4})")
+ print(f"Transmision exitosa. Finalizando secuencia")
+
+# Configuración del cliente MQTT
+client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
+client.on_connect = on_connect # Añade el manejador de eventos para cuando se conecte
+client.on_subscribe = on_subscribe # Añade el manejador de suscripción
+client.connect(broker_address, 1883, 60)
+
+# Publicar el archivo fragmentado
+publish_file(client, file_to_publish, min_size, max_size)
+
+client.disconnect()
diff --git a/tps/2C2024/1/scripts/publisher.py b/tps/2C2024/1/scripts/publisher.py
@@ -1,49 +1,53 @@
-import paho.mqtt.client as mqtt
-import random
-import time
-# Configuración
-broker_address = "broker.hivemq.com"
-#broker_address = "mqtt-dashboard.com"
-
-topic = "tp1/klockner"
-min_size = 50 # Tamaño mínimo del fragmento
-max_size = 70 # Tamaño máximo del fragmento
-file_to_publish = 'input.txt'
-
-def on_connect(client, userdata, flags, rc):
- # Al conectarse, configuramos la opción TCP_NODELAY
- client_socket = client._socket().socket # Accede al socket subyacente
- client_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # Desactiva Nagle
-
-def on_subscribe(self, mqttc, obj, mid, granted_qos):
- print("Subscribed: "+str(mid)+" "+str(granted_qos))
-
-def publish_file(client, filename, min_size, max_size):
- with open(filename, 'r') as file:
- content = file.read()
-
- index = 0
- fragment_number = 0
- while index < len(content):
- fragment_size = random.randint(min_size, max_size)
- fragment = content[index:index+fragment_size]
-
- # Metadatos: número de fragmento, tamaño, y bandera de último fragmento
- is_last = 1 if index + fragment_size >= len(content) else 0
- payload = f'{fragment_number}|{fragment_size}|{is_last}|{fragment}'
- client.publish(topic, payload, qos=2, retain=False)
- print(f"Fragmento publicado {fragment_number} (size: {fragment_size})")
- index += fragment_size
- fragment_number += 1
- time.sleep(1)
-
-# Configuración del cliente MQTT
-client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
-client.on_connect = on_connect # Añade el manejador de eventos para cuando se conecte
-client.on_subscribe = on_subscribe # Añade el manejador de suscripción
-client.connect(broker_address, 1883, 60)
-
-# Publicar el archivo fragmentado
-publish_file(client, file_to_publish, min_size, max_size)
-
-client.disconnect()
+import paho.mqtt.client as mqtt
+import random
+import time
+
+# Configuración
+broker_address = "broker.hivemq.com"
+# broker_address = "mqtt-dashboard.com"
+
+topic = "tp1/aguilar_klockner"
+min_size = 50 # Tamaño mínimo del fragmento
+max_size = 70 # Tamaño máximo del fragmento
+file_to_publish = 'input.txt'
+
+def on_connect(client, userdata, flags, rc):
+ # Al conectarse, configuramos la opción TCP_NODELAY
+ client_socket = client._socket().socket # Accede al socket subyacente
+ client_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # Desactiva Nagle
+
+def on_subscribe(self, mqttc, obj, mid, granted_qos):
+ print("Subscribed: "+str(mid)+" "+str(granted_qos))
+
+def publish_file(client, filename, min_size, max_size):
+ with open(filename, 'r') as file:
+ content = file.read()
+
+ index = 0
+ fragment_number = 0
+ while index < len(content):
+ fragment_size = random.randint(min_size, max_size)
+ fragment = content[index:index+fragment_size]
+
+ # Metadatos: número de fragmento, tamaño, y bandera de último fragmento
+ is_last = 1 if index + fragment_size >= len(content) else 0
+ payload = f'{fragment_number}|{fragment_size}|{is_last}|{fragment}'
+
+ if fragment_number != 6:
+ client.publish(topic, payload, qos=2, retain=False)
+ print(f"Fragmento publicado {fragment_number} (size: {fragment_size})")
+
+ fragment_number += 1
+ index += fragment_size
+ time.sleep(1)
+
+# Configuración del cliente MQTT
+client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
+client.on_connect = on_connect # Añade el manejador de eventos para cuando se conecte
+client.on_subscribe = on_subscribe # Añade el manejador de suscripción
+client.connect(broker_address, 1883, 60)
+
+# Publicar el archivo fragmentado
+publish_file(client, file_to_publish, min_size, max_size)
+
+client.disconnect()
diff --git a/tps/2C2024/1/scripts/subscriber-data-lost.py b/tps/2C2024/1/scripts/subscriber-data-lost.py
@@ -0,0 +1,59 @@
+import paho.mqtt.client as mqtt
+
+# Configuración
+broker = "broker.hivemq.com"
+#broker = "mqtt-dashboard.com"
+topic = "tp1/aguilar_klockner" # <<<<<<<<<<====== Completar con el nombre del grupo
+output_file = 'output.txt'
+received_fragments = {}
+last_fragment = False
+
+def on_subscribe(self, mqttc, obj, mid, granted_qos):
+ print("Subscribed: "+str(mid)+" "+str(granted_qos))
+
+def on_message(client, userdata, msg):
+ global last_fragment
+
+
+ # Decodificar mensaje: número de fragmento, tamaño, bandera de último fragmento, y contenido
+ payload = msg.payload.decode('utf-8')
+ fragment_info, fragment = payload.rsplit('|', 1)
+ fragment_number, fragment_size, is_last = map(int, fragment_info.split('|')[:3])
+
+ received_fragments[fragment_number] = (fragment_size, fragment)
+ print(f"Fragmento recibido {fragment_number} (size: {fragment_size})")
+ if is_last == 1:
+ last_fragment = True
+
+ # Reensamblar si es el último fragmento
+ if last_fragment:
+ reassemble_file(output_file)
+ quit()
+
+def reassemble_file(filename):
+ total_size = 0 #Creo la variable que guarda el peso total
+ control_size = 0 #Creo la variable que guarda el peso recibido
+ with open(filename, 'w') as file:
+ for fragment_number in sorted(received_fragments):
+ fragment_size, fragment = received_fragments[fragment_number]
+ if fragment_number != 0: #Excluyo de la reconstruccion al peso del archivo
+ file.write(fragment[:fragment_size]) # Reescribimos usando el largo correcto
+ total_size += fragment_size
+ else: # Guardo cuanto pesa el archivo como numero
+ control_size = int(fragment)
+ print(f"File reassembled as {filename}")
+ if control_size > total_size: #Contrasto el peso recibido con el esperado para definir si hubo error
+ print(f"Error en la transmision: Perdida de datos detectada")
+ else:
+ print(f"Transmision recibida exitosamente")
+
+# Configuración del cliente MQTT
+client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
+client.on_message = on_message
+client.on_subscribe = on_subscribe
+
+client.connect(broker, 1883, 60)
+client.subscribe(topic, qos=2)
+
+# Mantener el cliente en funcionamiento
+client.loop_forever()
diff --git a/tps/2C2024/1/scripts/subscriber-secure.py b/tps/2C2024/1/scripts/subscriber-secure.py
@@ -0,0 +1,59 @@
+import paho.mqtt.client as mqtt
+
+# Configuración
+broker = "broker.hivemq.com"
+#broker = "mqtt-dashboard.com"
+topic = "tp1/aguilar_klockner" # <<<<<<<<<<====== Completar con el nombre del grupo
+output_file = 'output.txt'
+received_fragments = {}
+last_fragment = False
+
+def on_subscribe(self, mqttc, obj, mid, granted_qos):
+ print("Subscribed: "+str(mid)+" "+str(granted_qos))
+
+def on_message(client, userdata, msg):
+ global last_fragment
+
+
+ # Decodificar mensaje: número de fragmento, tamaño, bandera de último fragmento, y contenido
+ payload = msg.payload.decode('utf-8')
+ fragment_info, fragment = payload.rsplit('|', 1)
+ fragment_number, fragment_size, is_last = map(int, fragment_info.split('|')[:3])
+
+
+
+ if fragment_number == -1: #En caso de recibir error de transmision borra todo y continua recibiendo
+ print(f"Error en la recepcion. Reiniciando secuencia")
+ received_fragments.clear()
+
+ else:
+ if fragment_number != 100: #Guarda cada dato recibido menos el mensaje de exito
+ received_fragments[fragment_number] = (fragment_size, fragment)
+ print(f"Fragmento recibido {fragment_number} (size: {fragment_size})")
+
+ if is_last == 1:
+ last_fragment = True
+
+ # Reensamblar si es el último fragmento
+ if last_fragment:
+ print(f"Exito en la recepcion. Finalizando secuencia")
+ reassemble_file(output_file)
+ quit()
+
+def reassemble_file(filename):
+ with open(filename, 'w') as file:
+ for fragment_number in sorted(received_fragments):
+ fragment_size, fragment = received_fragments[fragment_number]
+ file.write(fragment[:fragment_size]) # Reescribimos usando el largo correcto
+ print(f"File reassembled as {filename}")
+
+# Configuración del cliente MQTT
+client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
+client.on_message = on_message
+client.on_subscribe = on_subscribe
+
+client.connect(broker, 1883, 60)
+client.subscribe(topic, qos=2)
+
+# Mantener el cliente en funcionamiento
+client.loop_forever()
diff --git a/tps/2C2024/1/scripts/subscriber.py b/tps/2C2024/1/scripts/subscriber.py
@@ -1,50 +1,48 @@
-import paho.mqtt.client as mqtt
-
-# Configuración
-broker = "broker.hivemq.com"
-#broker = "mqtt-dashboard.com"
-
-topic = "tp1/klockner"
-output_file = 'output.txt'
-received_fragments = {}
-last_fragment = False
-
-def on_subscribe(self, mqttc, obj, mid, granted_qos):
- print("Subscribed: "+str(mid)+" "+str(granted_qos))
-
-def on_message(client, userdata, msg):
- global last_fragment
-
- # Decodificar mensaje: número de fragmento, tamaño, bandera de último fragmento, y contenido
- payload = msg.payload.decode('utf-8')
- fragment_info, fragment = payload.rsplit('|', 1)
- fragment_number, fragment_size, is_last = map(int, fragment_info.split('|')[:3])
-
- received_fragments[fragment_number] = (fragment_size, fragment)
- print(f"Fragmento recibido {fragment_number} (size: {fragment_size})")
- if is_last == 1:
- last_fragment = True
-
- # Reensamblar si es el último fragmento
- if last_fragment:
- reassemble_file(output_file)
- # quit()
- last_fragment = False
-
-def reassemble_file(filename):
- with open(filename, 'w') as file:
- for fragment_number in sorted(received_fragments):
- fragment_size, fragment = received_fragments[fragment_number]
- file.write(fragment[:fragment_size]) # Reescribimos usando el largo correcto
- print(f"File reassembled as {filename}")
-
-# Configuración del cliente MQTT
-client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
-client.on_message = on_message
-client.on_subscribe = on_subscribe
-
-client.connect(broker, 1883, 60)
-client.subscribe(topic, qos=2)
-
-# Mantener el cliente en funcionamiento
-client.loop_forever()
+import paho.mqtt.client as mqtt
+
+# Configuración
+broker = "broker.hivemq.com"
+#broker = "mqtt-dashboard.com"
+topic = "tp1/aguilar_klockner"
+output_file = 'output.txt'
+received_fragments = {}
+last_fragment = False
+
+def on_subscribe(self, mqttc, obj, mid, granted_qos):
+ print("Subscribed: "+str(mid)+" "+str(granted_qos))
+
+def on_message(client, userdata, msg):
+ global last_fragment
+
+ # Decodificar mensaje: número de fragmento, tamaño, bandera de último fragmento, y contenido
+ payload = msg.payload.decode('utf-8')
+ fragment_info, fragment = payload.rsplit('|', 1)
+ fragment_number, fragment_size, is_last = map(int, fragment_info.split('|')[:3])
+
+ received_fragments[fragment_number] = (fragment_size, fragment)
+ print(f"Fragmento recibido {fragment_number} (size: {fragment_size})")
+ if is_last == 1:
+ last_fragment = True
+
+ # Reensamblar si es el último fragmento
+ if last_fragment:
+ reassemble_file(output_file)
+ quit()
+
+def reassemble_file(filename):
+ with open(filename, 'w') as file:
+ for fragment_number in sorted(received_fragments):
+ fragment_size, fragment = received_fragments[fragment_number]
+ file.write(fragment[:fragment_size]) # Reescribimos usando el largo correcto
+ print(f"File reassembled as {filename}")
+
+# Configuración del cliente MQTT
+client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
+client.on_message = on_message
+client.on_subscribe = on_subscribe
+
+client.connect(broker, 1883, 60)
+client.subscribe(topic, qos=2)
+
+# Mantener el cliente en funcionamiento
+client.loop_forever()