Mensaje#
Introducción#
Dos robots VEX AIM Coding pueden conectarse para comunicarse durante un proyecto. La función Message permite que dos robots se comuniquen enviando mensajes cortos con datos opcionales. Está diseñada para la coordinación entre robots, como iniciar rutinas, compartir resultados de sensores o activar comportamientos en otro robot.
Every usage of send_message adds a message to the linked robot’s queue, and the queue is read first-in, first-out (FIFO). If multiple messages are sent before the other robot uses get_message or get_message_and_data, they will be stored and returned one at a time in the order they were sent. Because messages can queue, repeatedly sending the same status every loop may create backlog; for time-critical logic, send only when values change.
Los mensajes se almacenan en una cola de tipo primero en entrar, primero en salir (FIFO). El primer mensaje recibido se procesa primero, incluso si hay mensajes más recientes disponibles.
Nota: Para que se envíen y reciban mensajes, ambos robots deben estar ejecutando proyectos que manejen mensajes al mismo tiempo.
A continuación se muestra una lista de todos los métodos:
Acciones – Enviar mensajes entre robots.
send_message– Sends a string and up to three numbers to the other linked robot.
Getters: verifica los mensajes recibidos y el estado de la conexión.
get_message– Retrieve the most recent string received.get_message_and_data– Retrieve the most recent string and numbers received.is_connected– Returns a Boolean indicating whether the robot is linked with another robot.is_message_available– Returns a Boolean indicating whether the other linked robot has ever sent a message.get_name– Returns the name of the linked robot.
Devoluciones de llamadas: ejecutan funciones cuando ocurren eventos.
handle_message– Register a function to be called when a specific message is received.connected– Register a function to be called when the robot is connected with another robot.disconnected– Register a function to be called when the robot is disconnected with another robot.
Comportamiento#
send_message#
send_message sends a string and up to three numbers to the other linked robot.
Usage:
robot.link.send_message(message, arg1, arg2, arg3)
Parámetro |
Descripción |
|---|---|
|
La cadena que se enviará al otro robot vinculado. |
|
Opcional. Un valor flotante o entero para enviar al otro robot vinculado. |
|
Opcional. Un segundo flotante o entero para enviar al otro robot vinculado. |
|
Opcional. Un tercer flotante o entero para enviar al otro robot vinculado. |
Código para Robot 1
# Press the screen to tell Robot 2 which way to turn robot.screen.print("Robot 1") while not robot.screen.pressing(): wait(5, MSEC) # "right" turns right, "left" turns left robot.link.send_message("right")
Código para Robot 2
# Turn in the direction that Robot 1 sends robot.screen.print("Robot 2") while not robot.link.is_message_available(): wait(5, MSEC) direction = robot.link.get_message() if direction == "left": robot.turn_for(LEFT, 90) elif direction == "right": robot.turn_for(RIGHT, 90)
Código para Robot 1
# Continuously send the current heading to Robot 2 robot.screen.print("Robot 1") while True: robot.link.send_message("Turn to heading", robot.inertial.get_heading()) wait(5, MSEC)
Código para Robot 2
# Turn to match Robot 1's heading robot.screen.print("Robot 2") while True: if robot.link.is_message_available(): message, heading = robot.link.get_message_and_data() robot.turn_to(heading) wait(5, MSEC)
Código para Robot 1
robot.screen.show_aivision() while True: # Only return a max of 3 AprilTag IDs for message limit detections = robot.vision.get_data(ALL_TAGS, 3) # Identify the IDs collected ids = [det.id for det in detections] # Send IDs as separate arguments robot.link.send_message("Vision Data", *ids) # Tuple organized like: ("Vision Data", ID 1, ID 2, ID 3) wait(50, MSEC)
Código para Robot 2
while True: if robot.link.is_message_available(): # Receive the message from Robot 1 data = robot.link.get_message_and_data() # Separate out the received message message = data[0] arg1 = data[1] if len(data) > 1 else None arg2 = data[2] if len(data) > 2 else None arg3 = data[3] if len(data) > 3 else None # Reset the screen robot.screen.clear_screen() robot.screen.set_cursor(1, 1) robot.screen.print("Detected IDs:") robot.screen.next_row() # Display any IDs that exist from the data if message == "Vision Data": for tag_id in (arg1, arg2, arg3): if tag_id is not None: robot.screen.print(tag_id) robot.screen.next_row() wait(50, MSEC)
Captadores#
get_message#
get_message returns the most recent string received from the other linked robot.
Usage:
robot.link.get_message(timeout)
Parámetros |
Descripción |
|---|---|
|
Opcional. El tiempo máximo (en milisegundos) que la función esperará un mensaje antes de continuar sin él. El valor predeterminado es 1000. |
Código para Robot 1
# Press the screen to send a message to Robot 2 robot.screen.print("Robot 1") while not robot.screen.pressing(): wait(5, MSEC) # Change the string to display a different message robot.link.send_message("Hello, Robot 2!")
Código para Robot 2
# Display what message Robot 1 sends robot.screen.print("Robot 2") robot.screen.next_row() while not robot.link.is_message_available(): wait(5, MSEC) message = robot.link.get_message() robot.screen.print(message)
get_message_and_data#
get_message_and_data returns the most recent string and numbers received from the other linked robot and returns it as a tuple.
Usage:
robot.link.get_message_and_data(timeout)
Parámetros |
Descripción |
|---|---|
|
Opcional. El tiempo máximo (en milisegundos) que la función esperará un mensaje antes de continuar sin él. El valor predeterminado es 1000. |
Código para Robot 1
# Code for Robot 1 # Continuously send the current heading to Robot 2 robot.screen.print("Robot 1") while True: robot.link.send_message("Turn to heading", robot.inertial.get_heading()) wait(5, MSEC)
Código para Robot 2
# Turn to match Robot 1's heading robot.screen.print("Robot 2") while True: if robot.link.is_message_available(): message, heading = robot.link.get_message_and_data() robot.turn_to(heading) wait(5, MSEC)
is_connected#
is_connected returns a Boolean indicating whether the robot is currently linked with another robot.
True– The robot is linked with another robot.False– The robot is not linked with another robot.
Usage:
robot.link.is_connected()
Parámetros |
Descripción |
|---|---|
Este método no tiene parámetros. |
# Turn off one of the linked robots to see the message change
while True:
robot.screen.clear_screen()
robot.screen.set_cursor(1, 1)
robot.screen.print(robot.link.is_connected())
wait(5, MSEC)
is_message_available#
is_message_available returns a Boolean indicating whether the other linked robot has ever used send_message.
True– send_message has been used by the other linked robot in the current project.False– send_message has never been used by the other linked robot in the current project.
Usage:
robot.link.is_message_available()
Parámetros |
Descripción |
|---|---|
Este método no tiene parámetros. |
Código para Robot 1
# Press the screen to send a message to Robot 2 robot.screen.print("Robot 1") while not robot.screen.pressing(): wait(5, MSEC) # Change the string to display a different message robot.link.send_message("Hello, Robot 2!")
Código para Robot 2
# Display what message Robot 1 sends robot.screen.print("Robot 2") robot.screen.next_row() while not robot.link.is_message_available(): wait(5, MSEC) message = robot.link.get_message() robot.screen.print(message)
get_name#
get_name returns a string with the name of the linked robot. If no robot is linked, this will return “None”.
Usage:
robot.link.get_name()
Parámetros |
Descripción |
|---|---|
Este método no tiene parámetros. |
# Display the name of the robot that's linked
robot.screen.print(robot.link.get_name())
Devoluciones de llamadas#
handle_message#
handle_message registers a method that runs when the robot receives a specific message string.
Usage:robot.link.handle_message(callback, message)
Parámetros |
Descripción |
|---|---|
|
Una función previamente definida que se llama cuando el mensaje recibido coincide con la cadena especificada. |
|
The string to check incoming messages against. If it matches, the |
Código para Robot 1
# Press the screen to send a message to Robot 2 robot.screen.print("Robot 1") while not robot.screen.pressing(): wait(5, MSEC) robot.link.send_message("smile")
Código para Robot 2
# Show a smiling emoji def robot_smile(): robot.screen.show_emoji(HAPPY) # If Robot 1 sends "smile", show a smiling emoji robot.screen.print("Robot 2") while not robot.link.is_message_available(): wait(5, MSEC) robot.link.handle_message(robot_smile, "smile")
connected#
connected registers a function to be called when the robot is linked to another robot.
Usage:robot.link.connected(callback, args)
Parámetros |
Descripción |
|---|---|
|
Una función previamente definida que se llama cuando el robot está vinculado a otro robot. |
|
Opcional. Una tupla que contiene los argumentos que se pasarán a la función de devolución de llamada. Consulte Uso de funciones con parámetros para obtener más información. |
# Show a happy face when connected
def robot_smile():
robot.screen.show_emoji(HAPPY)
# Show a sad face when disconnected
def robot_sad():
robot.screen.show_emoji(SAD)
# Register both callbacks
# Turn off a robot to change the emoji
robot.link.connected(robot_smile)
robot.link.disconnected(robot_sad)
disconnected#
disconnected registers a function to be called when the robot is not linked to another robot.
Usage:robot.link.disconnected(callback, args)
Parámetros |
Descripción |
|---|---|
|
Una función previamente definida que se llama cuando el robot no está vinculado a otro robot. |
|
Opcional. Una tupla que contiene los argumentos que se pasarán a la función de devolución de llamada. Consulte Uso de funciones con parámetros para obtener más información. |
# Show a happy face when connected
def robot_smile():
robot.screen.show_emoji(HAPPY)
# Show a sad face when disconnected
def robot_sad():
robot.screen.show_emoji(SAD)
# Register both callbacks
# Turn off a robot to change the emoji
robot.link.connected(robot_smile)
robot.link.disconnected(robot_sad)