Mensaje#

Introducción#

Se pueden vincular dos robots de codificación VEX AIM para que se comuniquen durante un proyecto. Mediante mensajes, los robots pueden enviar y recibir información para coordinar sus acciones.

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 los métodos disponibles:

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 as a tuple.

  • 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.

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

message

The string to send to the other linked robot.

arg1

Opcional. Un valor flotante o entero para enviar al otro robot vinculado.

arg2

Opcional. Un segundo flotante o entero para enviar al otro robot vinculado.

arg3

Opcional. Un tercer flotante o entero para enviar al otro robot vinculado.

Code for 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")


Code for 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)


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)


Code for 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)


Code for 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)


Code for 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

timeout

Opcional. El tiempo máximo (en milisegundos) que la función esperará un mensaje antes de continuar sin él. El valor predeterminado es 1000.

Code for 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!")


Code for 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

timeout

Opcional. El tiempo máximo (en milisegundos) que la función esperará un mensaje antes de continuar sin él. El valor predeterminado es 1000.

Code for 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)


Code for 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(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 yet in the current project.

  • 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.

Code for 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!")


Code for 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)

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

callback

Una función previamente definida que se llama cuando el mensaje recibido coincide con la cadena especificada.

message

The string to check incoming messages against. If it matches, the callback runs.

Code for 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")


Code for 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

callback

Una función previamente definida que se llama cuando el robot está vinculado a otro robot.

args

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

callback

Una función previamente definida que se llama cuando el robot no está vinculado a otro robot.

args

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)