MessageLink#
Introducción#
MessageLink permite que dos cerebros V5 se comuniquen enviando mensajes de cadena corta con datos pequeños opcionales. Está diseñado para la coordinación de robot a robot, como iniciar rutinas, compartir resultados de sensores o activar comportamientos en otro robot.
Cada uso de send agrega un mensaje a la cola del cerebro V5 vinculado, y la cola se lee primero en entrar, primero en salir (FIFO). Si se envían varios mensajes antes de que el otro cerebro V5 use receive, se almacenarán y devolverán uno a la vez en el orden en que se enviaron. Debido a que los mensajes pueden ponerse en cola, enviar repetidamente el mismo estado en cada bucle puede crear retraso; para la lógica de tiempo crítico, envíe solo cuando cambien los valores.
Importante: Ambos robots deben estar ejecutando proyectos que MessageLink MessageLink al mismo tiempo, o no se enviarán ni recibirán mensajes.
Esta página utiliza link como ejemplo MessageLink name. Reemplácelo con su propio nombre configurado según sea necesario.
A continuación se muestra una lista de los métodos disponibles:
Crear un enlace#
Cree un MessageLink en ambos cerebros V5 para establecer un canal de comunicación entre ellos, ya sea de forma inalámbrica con V5 Robot Radios o a través de un cable inteligente cableado, para que los robots puedan enviarse mensajes entre sí.
MessageLink(smartport, name, linktype, wired)
Parámetro |
Descripción |
|---|---|
|
El puerto inteligente utilizado para este enlace: el puerto al que está conectado el radio robot V5 (inalámbrico) o el cable inteligente está conectado (cableado). Escrito como |
|
El nombre único para dar este enlace como una cadena. |
|
El rol que este cerebro usará para este par de enlaces. Cada par debe incluir un Gerente y un Trabajador
|
|
Opcional. Si este enlace es por cable o inalámbrico:
|
Código para Robot 1
""" Create a wireless link in Port 1 name: VEXRoboticsLink123456789 linktype: Manager """ link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.MANAGER)Código para Robot 2
""" Create a wireless link in Port 1 name: VEXRoboticsLink123456789 linktype: Worker """ link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.WORKER)
Métodos disponibles#
Una vez que tu MessageLink esté configurado y los Brains estén vinculados, puedes usar los siguientes métodos para enviar, recibir y responder mensajes.
is_linked#
el método is_linked devuelve si los cerebros V5 en un MessageLink están emparejados entre sí.
True: los dos cerebros V5 están emparejados y se comunican en este enlace.False– Los dos cerebros V5 no están emparejados en este enlace.
Nota: Es una buena práctica verificar siempre que los cerebros V5 estén vinculados al comienzo de un proyecto antes de ejecutar cualquier código adicional.
Usage:
link.is_linked()
Parámetros |
Descripción |
|---|---|
Este método no tiene parámetros. |
Código para Robot 1
# Tell the other robot when the screen is being pressed # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.MANAGER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 1 - Manager") # Continuously send if the screen is being pressed while True: if brain.screen.pressing(): link.send("pressed") else: link.send("released") wait(50, MSEC)Código para Robot 2
# Display if the other robot's screen is being pressed # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.WORKER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) # Continuously check if Robot 1 has sent "pressed" while True: brain.screen.clear_screen() brain.screen.set_cursor(1, 1) brain.screen.print("Robot 2 - Worker") brain.screen.next_row() if link.receive() == "pressed": brain.screen.new_line() brain.screen.print("Manager is being pressed!") wait(50, MSEC)
send#
send envía una cadena y/o un número entero y/o flotante al otro cerebro V5 vinculado.
Usage:
send(string, integer, float)
Parámetros |
Descripción |
|---|---|
|
La cadena a enviar al otro cerebro V5 vinculado. |
|
Opcional. Un número entero para enviar al otro cerebro V5 vinculado. |
|
Opcional. Un flotador para enviar al otro cerebro V5 vinculado. Los flotantes se formatean con 4 decimales; si se proporcionan menos decimales, se agregan ceros al final hasta que se muestren 4. |
Si solo se envía la cadena string , el otro V5 Brain vinculado recibe esa cadena exacta.
Si se incluyen integer y/o float, el cerebro receptor obtiene una sola cadena codificada que combina todos los campos en este orden: .string_integer_float
Ejemplo: Usando link.send(“string”, 1, 2.55) se recibe como .string_1_2.5500.
Código para Robot 1
# Tell the other robot when the screen is being pressed # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.MANAGER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 1 - Manager") # Continuously send if the screen is being pressed while True: if brain.screen.pressing(): link.send("pressed") else: link.send("released") wait(50, MSEC)Código para Robot 2
# Display if the other robot's screen is being pressed # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.WORKER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) # Continuously check if Robot 1 has sent "pressed" while True: brain.screen.clear_screen() brain.screen.set_cursor(1, 1) brain.screen.print("Robot 2 - Worker") brain.screen.next_row() if link.receive() == "pressed": brain.screen.new_line() brain.screen.print("Manager is being pressed!") wait(50, MSEC)
Código para Robot 1
# Tell the other robot where the screen was pressed # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.MANAGER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 1 - Manager") brain.screen.next_row() brain.screen.print("Tap to send circles") # Send the coordinates whenever the screen is pressed while True: if brain.screen.pressing(): x = brain.screen.x_position() y = brain.screen.y_position() link.send("touch", x, y) wait(10, MSEC)Código para Robot 2
# Draw a circle where Robot 1's screen was pressed # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.WORKER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 2 - Worker") while True: # Get the full encoded string circle_coordinates = link.receive(200) if circle_coordinates: # Split the encoded string by _ parts = circle_coordinates.split("_") if len(parts) == 3: # Convert the coordinates back into numbers x = float(parts[1]) y = float(parts[2]) brain.screen.set_fill_color(Color.WHITE) brain.screen.draw_circle(x, y, 20) wait(10, MSEC)
receive#
receive devuelve el siguiente mensaje en cola del otro V5 Brain vinculado. Los mensajes se leen en orden FIFO (el más antiguo sin leer primero). Si la cola está vacía cuando se llama a receive , espera hasta el tiempo de espera receive para un nuevo mensaje. Si no llega ningún mensaje en ese intervalo, receive devuelve timeout, y cualquier mensaje enviado posteriormente permanece en la cola para ser leído la próxima vez que se utilice None.
Si el otro cerebro V5 vinculado envió solo una string, receive devuelve esa cadena exacta.
Si el otro cerebro V5 vinculado envió un número entero y/o flotante, receive devuelve una sola cadena codificada que combina todos los campos en este orden: .string_integer_float
Por ejemplo, si el otro cerebro V5 vinculado usa link.send(“string”, 1, 2.55), entonces link.receive() devuelve una cadena codificada como .string_1_2.5500. Puede dividir esta cadena codificada (consulte los ejemplos a continuación) para extraer el nombre del mensaje, el número entero y los valores flotantes.
Si prefiere evitar la división/análisis manual, use received para registrar un controlador para un nombre de mensaje específico; el controlador recibe los valores enviados como argumentos.
Usage:
receive(timeout)
Parámetros |
Descripción |
|---|---|
|
Opcional. Cuánto tiempo en milisegundos |
Código para Robot 1
# Tell the other robot when the screen is being pressed # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.MANAGER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 1 - Manager") # Continuously send if the screen is being pressed while True: if brain.screen.pressing(): link.send("pressed") else: link.send("released") wait(50, MSEC)Código para Robot 2
# Display if the other robot's screen is being pressed # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.WORKER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) # Continuously check if Robot 1 has sent "pressed" while True: brain.screen.clear_screen() brain.screen.set_cursor(1, 1) brain.screen.print("Robot 2 - Worker") brain.screen.next_row() if link.receive() == "pressed": brain.screen.new_line() brain.screen.print("Manager is being pressed!") wait(50, MSEC)
Código para Robot 1
# Send a math problem for the other Brain to solve # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.MANAGER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 1 - Manager") """ Change whether to "add" or "subtract", then what numbers to use in the operation. """ link.send("add", 7, 2.5)Código para Robot 2
# Solve the math problem that the other Brain sends # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.WORKER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 2 - Worker") brain.screen.next_row() math_problem = link.receive() if math_problem: # Split the encoded string by _ parts = math_problem.split("_") if len(parts) == 3: # Remove the . from the beginning of the string operator = "".join([c for c in parts[0] if c.isalpha()]) # Separate out the numbers for the operation a = int(parts[1]) b = float(parts[2]) # Use what operator was sent if operator == "add": result = a + b elif operator == "subtract": result = a - b # If neither add or subtract is sent, do nothing else: pass brain.screen.print("Result = ", result)
received#
received registra una función para ser llamada cada vez que el Cerebro V5 recibe un mensaje enviado.
Usage:
link.received(message, arg)
Parámetros |
Descripción |
|---|---|
|
The message name (string) to match. When a received message’s name matches this value, the |
|
Una función previamente definida que se ejecuta cuando el cerebro V5 * * recibe * * un mensaje que coincide con el |
received devolución de llamada se llaman con cuatro argumentos:
Firma de devolución de llamada:
callback(message, linkname, index, value)
Argumento |
Descripción |
|---|---|
|
El nombre del mensaje que se recibió (por ejemplo, |
|
El nombre del enlace del que se recibió el mensaje. |
|
El valor entero enviado con el mensaje (si se proporciona). |
|
El valor flotante enviado con el mensaje (si se proporciona). |
Código para Robot 1
# Send a math problem for the other Brain to solve # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.MANAGER) # Do not run code UNTIL the Brains are linked while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 1 - Manager") """ Change whether to "add" or "subtract", then what numbers to use in the operation. """ link.send("add", 7, 2.5)Código para Robot 2
# Solve the math problem that the other Brain sends # Create the link link = MessageLink(Ports.PORT1, "VEXRoboticsLink123456789", VexlinkType.WORKER) while not link.is_linked(): wait(0.1, SECONDS) brain.screen.print("Robot 2 - Worker") brain.screen.next_row() # add if "add" is received def add_cmd(message, linkname, a, b): result = a + b brain.screen.print("Result = ", result) # subtract if ""subtract" is received def subtract_cmd(message, linkname, a, b): result = a - b brain.screen.print("Result = ", result) # Create event handlers for "add" and "subtract" link.received("add", add_cmd) link.received("subtract", subtract_cmd)