Enlace del mensaje#
Introducción#
La clase message_link permite que dos V5 Brains se comuniquen enviando mensajes cortos de cadena 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.
Cada uso de send agrega un mensaje a la cola del V5 Brain vinculado, y la cola se lee según el principio FIFO (primero en entrar, primero en salir). Si se envían varios mensajes antes de que el otro V5 Brain use receive, se almacenarán y se devolverán uno a uno en el orden en que se enviaron. Debido a que los mensajes pueden ponerse en cola, enviar repetidamente el mismo estado en cada ciclo puede crear retrasos; para lógica crítica en tiempo real, envíe solo cuando los valores cambien.
Importante: Ambos robots deben estar ejecutando proyectos que utilicen message_link al mismo tiempo, o no se enviarán ni recibirán mensajes.
Constructores de clases#
message_link(
int32_t index,
const char *name,
linkType type,
bool isWired = false );
Instructor de clase#
Destruye el objeto message_link y libera los recursos asociados.
virtual ~message_link();
Parámetros#
Parámetro |
Tipo |
Descripción |
|---|---|---|
|
|
El puerto inteligente al que está conectado el V5 Radio o el Smart Cable, escrito como |
|
|
El nombre del enlace del mensaje. |
|
|
El tipo de enlace, ya sea
|
|
|
Indica si el objeto message_link está conectado por cable.
|
Ejemplo#
Código para el Robot 1
// Create a wireless link in Port 1 message_link link = message_link( PORT1, // index "VEXRoboticsLink123456789", // name linkType::manager, // type true); // isWiredCódigo para el Robot 2
// Create a wireless link in Port 1 message_link link = message_link( PORT1, // index "VEXRoboticsLink123456789", // name linkType::worker, // type true); // isWired
Funciones de los miembros#
La clase message_link incluye las siguientes funciones miembro:
isLinked— Devuelve si este Cerebro está conectado activamente a su Cerebro emparejado.send— Envía un mensaje al Cerebro emparejado.receive— Espera y devuelve el siguiente mensaje entrante.received— Registra una función que se llamará cada vez que se reciba un nuevo mensaje.
Before calling any message_link member functions, a message_link instance must be created, as shown below:
Código para el Robot 1
// Create a wireless link in Port 1 message_link link = message_link( PORT1, // index "VEXRoboticsLink123456789", // name linkType::manager, // type true); // isWiredCódigo para el Robot 2
// Create a wireless link in Port 1 message_link link = message_link( PORT1, // index "VEXRoboticsLink123456789", // name linkType::worker, // type true); // isWired
isLinked#
El método isLinked devuelve si los V5 Brains en un MessageLink están emparejados entre sí.
bool isLinked();
Esta función no tiene ningún parámetro.
Return ValuesEsta función devuelve un valor booleano.
true– Los dos cerebros V5 están emparejados y comunicándose a través de este enlace.false– Los dos cerebros V5 no están emparejados en este enlace.
Es recomendable comprobar siempre que los V5 Brains estén conectados al inicio de un proyecto, antes de ejecutar cualquier otro código.
ExamplesCódigo para el Robot 1
// Tell the other robot when the screen is being pressed // Create the link message_link link = message_link(PORT1, "VEXRoboticsLink123456789", linkType::manager, true); // Do not run code UNTIL the Brains are linked while (!link.isLinked()){ 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(0.05, seconds); }Código para el Robot 2
// Display if the other robot's screen is being pressed // Create the link message_link link = message_link(PORT1, "VEXRoboticsLink123456789", linkType::worker, true); // Do not run code UNTIL the Brains are linked while (!link.isLinked()){ wait(0.1, seconds); } // Continuously check if Robot 1 has sent "pressed" while (true){ Brain.Screen.clearScreen(); Brain.Screen.setCursor(1, 1); Brain.Screen.print("Robot 2 - Worker"); Brain.Screen.newLine(); char msg[32] = {0}; // buffer for incoming message int32_t n = link.receive(msg, sizeof(msg), 100); // wait up to 100ms if (n > 0 && strcmp(msg, "pressed") == 0) { Brain.Screen.newLine(); Brain.Screen.print("Manager is being pressed!"); } wait(0.05, seconds); }
send#
Envía un mensaje a través de la conexión de enlace.
Available FunctionsParameters1 — Envía una cadena de mensaje.
int32_t send( const char *message );2 — Envía una cadena de mensaje con un doble
double.int32_t send( const char *message, double value );3 — Envía una cadena de mensaje con un
int32_ty undouble.int32_t send( const char *message, int32_t index, double value );
Parámetro |
Tipo |
Descripción |
|---|---|---|
|
|
El mensaje que se enviará al otro cerebro V5 vinculado. |
|
|
Un número entero para enviar al otro cerebro V5 vinculado. |
|
|
Un número doble para enviar al otro V5 Brain vinculado. Los números dobles se formatean con 4 decimales; si se proporcionan menos decimales, se agregan ceros al final hasta que se muestren 4. |
Esta función no devuelve ningún valor.
NotesSi solo se envía el mensaje message , el otro cerebro V5 vinculado recibe ese mismo mensaje.
Si se incluyen el valor value (y el índice index si se proporcionan), el Cerebro receptor recibe un único mensaje codificado que combina todos los campos en este orden: .message_index_value
Usando link.send(“string”, 1, 2.55) se recibe como .string_1_2.5500.
Código para el Robot 1
// Tell the other robot when the screen is being pressed // Create the link message_link link = message_link(PORT1, "VEXRoboticsLink123456789", linkType::manager, true); // Do not run code UNTIL the Brains are linked while (!link.isLinked()){ 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(0.05, seconds); }Código para el Robot 2
// Display if the other robot's screen is being pressed // Create the link message_link link = message_link(PORT1, "VEXRoboticsLink123456789", linkType::worker, true); // Do not run code UNTIL the Brains are linked while (!link.isLinked()){ wait(0.1, seconds); } // Continuously check if Robot 1 has sent "pressed" while (true){ Brain.Screen.clearScreen(); Brain.Screen.setCursor(1, 1); Brain.Screen.print("Robot 2 - Worker"); Brain.Screen.newLine(); char msg[32] = {0}; // buffer for incoming message int32_t n = link.receive(msg, sizeof(msg), 100); // wait up to 100ms if (n > 0 && strcmp(msg, "pressed") == 0) { Brain.Screen.newLine(); Brain.Screen.print("Manager is being pressed!"); } wait(0.05, seconds); }
receive#
Recibe un mensaje de la conexión de enlace.
Available Functionsint32_t receive(
char *buffer,
int32_t length,
int32_t timeoutMs = 500 );
Parámetro |
Tipo |
Descripción |
|---|---|---|
|
|
El búfer para almacenar el mensaje recibido. |
|
|
La longitud del búfer. |
|
|
¿Cuánto tiempo en milisegundos tarda un mensaje en recibir |
Esta función devuelve el número de bytes recibidos.
Notesreceivedevuelve 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 areceive, espera hasta el tiempo de esperareceivepara un nuevo mensaje. Si no llega ningún mensaje en ese intervalo,receivedevuelve0, y cualquier mensaje enviado posteriormente permanece en la cola para ser leído la próxima vez que se utilicetimeout.Si el otro V5 Brain vinculado envió solo una cadena
string,receivedevuelve esa cadena exacta.Si el otro V5 Brain vinculado envió un entero y/o un número decimal,
receivedevuelve una única cadena codificada que combina todos los campos en este orden:.string_integer_floatPor ejemplo, si el otro V5 Brain vinculado usa
link.send(“string”, 1, 2.55), entonces al usarlink.receive()se devuelve una cadena codificada como.string_1_2.5500. Puedes dividir esta cadena codificada (consulta los ejemplos a continuación) para extraer el nombre del mensaje, los valores enteros y los valores flotantes.Si prefiere evitar la división/análisis manual, utilice
receivedpara registrar un controlador para un nombre de mensaje específico; el controlador recibe los valores enviados como argumentos.
Usando link.send(“string”, 1, 2.55) se recibe como .string_1_2.5500.
Código para el Robot 1
// Tell the other robot when the screen is being pressed // Create the link message_link link = message_link(PORT1, "VEXRoboticsLink123456789", linkType::manager, true); // Do not run code UNTIL the Brains are linked while (!link.isLinked()){ 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(0.05, seconds); }Código para el Robot 2
// Display if the other robot's screen is being pressed // Create the link message_link link = message_link(PORT1, "VEXRoboticsLink123456789", linkType::worker, true); // Do not run code UNTIL the Brains are linked while (!link.isLinked()){ wait(0.1, seconds); } // Continuously check if Robot 1 has sent "pressed" while (true){ Brain.Screen.clearScreen(); Brain.Screen.setCursor(1, 1); Brain.Screen.print("Robot 2 - Worker"); Brain.Screen.newLine(); char msg[32] = {0}; // buffer for incoming message int32_t n = link.receive(msg, sizeof(msg), 100); // wait up to 100ms if (n > 0 && strcmp(msg, "pressed") == 0) { Brain.Screen.newLine(); Brain.Screen.print("Manager is being pressed!"); } wait(0.05, seconds); }
received#
Registra una función que se llamará cada vez que el V5 Brain reciba un mensaje.
Available FunctionsParameters1 Registra una función de devolución de llamada para todos los mensajes recibidos (mensaje + valor).
void received( void (* callback)(const char *, const char *, double) );2 Registra una función de devolución de llamada para todos los mensajes recibidos (mensaje + índice + valor).
void received( void (* callback)(const char *, const char *, int32_t, double) );3 Registra una función de devolución de llamada para un mensaje específico (mensaje + valor).
void received( const char *message, void (* callback)(const char *, const char *, double) );4 Registra una función de devolución de llamada para un mensaje específico (mensaje + índice + valor).
void received( const char *message, void (* callback)(const char *, const char *, int32_t, double) );
Parámetro |
Tipo |
Descripción |
|---|---|---|
|
|
El nombre del mensaje que se desea escuchar. Si se omite, la función de devolución de llamada se ejecuta para todos los mensajes recibidos. |
|
|
Una función que se ejecuta cuando se recibe un mensaje. |
Esta función no devuelve ningún valor.
Callback Signature1 Recibe el nombre del remitente, el nombre del mensaje y el valor.
void callback(const char *, const char *, double)2 Recibe el nombre del remitente, el nombre del mensaje, el índice y el valor.
void callback(const char *, const char *, int32_t, double)
Tipo |
Descripción |
|---|---|
1st |
El nombre del enlace del remitente. |
2nd |
El nombre del mensaje recibido. |
|
El índice asociado al mensaje. |
|
El valor asociado al mensaje. |
Código para el Robot 1
// Create the link. message_link link(PORT1, "LeftRightLink", linkType::manager, true); // Send whether screen is pressed on left or right. void screen_pressed() { if (Brain.Screen.xPosition() < 240) { link.send("left"); } else { link.send("right"); } } int main() { /* vexcodeInit() is only required when using VEXcode. Remove vexcodeInit() if compiling in VS Code. */ vexcodeInit(); // Do not run code UNTIL the Brains are linked. while (!link.isLinked()) { wait(0.1, seconds); } Brain.Screen.print("Robot 1 - Manager"); Brain.Screen.pressed(screen_pressed); while (true) { wait(10, msec); } }Código para el Robot 2
// Create variable to track where screen is pressed. int lastPress = 0; // Update the variable whenever a new message is received. void message_received(const char* message, const char* linkname, double timestamp) { if (strcmp(message, "left") == 0) lastPress = 1; if (strcmp(message, "right") == 0) lastPress = 2; } int main() { /* vexcodeInit() is only required when using VEXcode. Remove vexcodeInit() if compiling in VS Code. */ vexcodeInit(); // Create the link. message_link link(PORT1, "VEXRoboticsLink123456789", linkType::worker, true); // Do not run code UNTIL the Brains are linked. while (!link.isLinked()) { wait(0.1, seconds); } link.received(message_received); // Display if Robot 1's screen was pressed on the left or right while (true) { Brain.Screen.clearScreen(); Brain.Screen.setCursor(1, 1); Brain.Screen.print("Robot 2 - Worker"); Brain.Screen.newLine(); if (lastPress == 1) { Brain.Screen.print("Manager pressed LEFT"); } else if (lastPress == 2) { Brain.Screen.print("Manager pressed RIGHT"); } else { Brain.Screen.print("Waiting..."); } wait(0.1, seconds); } }