Eventos#

Introducción#

Los eventos permiten iniciar una función de forma asíncrona. Cuando se emite un evento, la función de devolución de llamada del evento se inicia en su propia tarea (hilo), de modo que el código principal puede seguir ejecutándose simultáneamente.

Important: An event object stores one callback. If you register another function with the same event object, it replaces the previous callback.

Si quieres que ocurran varias cosas a partir de un mismo desencadenante, puedes:

  • Llamar a varias funciones auxiliares desde una única función de devolución de llamada, o

  • Utilice varios objetos de evento y transmita cada uno de ellos.

  • Utilice hilos separados para ejecutar tareas de forma independiente.

Para crear y luego usar un evento, siga estos pasos en orden:

  1. Create the event with event.

  2. Set the event’s callback using the event name (ex: myEvent(myCallback);).

  3. Broadcast an event:

    • broadcast — Triggers all registered functions in an event object to run in parallel.

    • broadcastAndWait — Triggers all registered functions in an event object and waits for them to finish before continuing.

Constructores de clases#

1 Creates an event object without a callback function.

event();

2 Creates an event object with a callback function.

event( void (* callback)(void) );

3 Creates an event object from another event with a callback function.

event( 
  event v, 
  void (* callback)(void) );

4 Creates an event object with a callback function that accepts an argument.

event( void (* callback)(void *), void *arg );

5 Creates an event object from another event with a callback function that accepts an argument.

event( event v, void (* callback)(void *), void *arg );

Instructor de clase#

Destroys the event object and releases associated resources.

~event();

Parámetros#

Parámetro

Tipo

Descripción

callback

void (*)(void)

Una función que se define previamente para ejecutarse cuando se transmite el evento.

v

event

Un objeto de evento existente del que copiar.

callback

void (*)(void *)

Una función que acepta un argumento de puntero vacío y se ejecuta cuando se transmite el evento.

arg

void *

Un puntero a los datos que se pasarán a la función de devolución de llamada.

Notas#

  • An event object stores one callback. If you register another function with the same event object, it replaces the previous callback.

  • Si quieres que ocurran varias cosas a partir de un mismo desencadenante, puedes:

    • Llamar a varias funciones auxiliares desde una única función de devolución de llamada, o

    • Utilice varios objetos de evento y transmita cada uno de ellos.

    • Utilice hilos separados para ejecutar las tareas de forma independiente.

Ejemplo#

Define the callback function (outside of int main())

// Create a callback function
void onMyEvent() {
  Brain.Screen.print("Callback function executed!");
}

Register the callback inside int main()

int main() {
  /* vexcodeInit() is only required when using VEXcode.
  Remove vexcodeInit() if compiling in VS Code. */
  vexcodeInit();

  // Create an event called myEvent
  // Set onMyEvent as the callback function
  event myEvent(onMyEvent);
}

Funciones de los miembros#

The event class includes the following member functions:

  • operator — Sets a callback function for the event.

  • broadcast — Triggers the event’s callback function to run in parallel.

  • broadcastAndWait — Triggers the event’s callback function and waits for completion.

Before calling any event member functions, an event instance must be created, as shown below:

/* This constructor is required when using VS Code.
Event configuration can be created with or without
a callback function as shown in the examples above. */

// Create an event without a callback
event myEvent;

// Or create an event with a callback
event myEvent(onMyEvent);

operator#

Establece una función de devolución de llamada para el evento utilizando el operador de llamada a función.

Available Functions
void operator()( void (* callback)() );

Parameters

Parámetro

Tipo

Descripción

callback

void (*)(void)

Una función de devolución de llamada definida previamente que se ejecuta automáticamente cuando se transmite el evento. La función debe coincidir con la firma de devolución de llamada requerida. Consulte Funciones de devolución de llamada para obtener más información.

Return Values

Esta función no devuelve ningún valor.

Notes
  • Al volver a configurar una función de devolución de llamada, se reemplaza la función de devolución de llamada anterior.

  • La función de devolución de llamada no debe tener parámetros y debe devolver void.

Examples

Define the callback functions (outside of int main())

// Create a callback function
void drawSquare() {
  Brain.Screen.clearScreen();
  Brain.Screen.drawRectangle(40, 40, 120, 120);
}

void drawCircle() {
  Brain.Screen.clearScreen();
  Brain.Screen.drawCircle(100, 100, 60);
}

Register the callback inside int main()

int main() {
  /* vexcodeInit() is only required when using VEXcode.
  Remove vexcodeInit() if compiling in VS Code. */
  vexcodeInit();

  // Create the event drawEvent
  event drawEvent;

  Brain.Screen.print("Drawing a square...");

  // Set the event to drawSquare
  drawEvent(drawSquare);

  wait(1, seconds);

  // Trigger the event
  drawEvent.broadcast();

  wait(1, seconds);

  Brain.Screen.clearScreen();
  Brain.Screen.setCursor(1, 1);
  Brain.Screen.print("Drawing a circle...");

  // Replace drawSquare with drawCircle
  drawEvent(drawCircle);

  wait(1, seconds);

  // Trigger the event a second time
  drawEvent.broadcast();
}

broadcast#

broadcast starts the event’s callback and continues immediately.

Member Functions
void broadcast();

Parameters

Esta función no requiere ningún parámetro.

Return Values

Esta función no devuelve ningún valor.

Examples

Define the callback function (outside of int main())

// Create a callback function
void onMyEvent() {
  Brain.Screen.clearScreen();
  Brain.Screen.setCursor(1, 1);
  Brain.Screen.print("Event fired!");
}

Register the callback inside int main()

int main() {
  /* vexcodeInit() is only required when using VEXcode.
  Remove vexcodeInit() if compiling in VS Code. */
  vexcodeInit();

  Brain.Screen.print("Broadcasting in 2 seconds...");

  // Create an event called myEvent
  // Set onMyEvent as the callback function
  event myEvent(onMyEvent);

  wait(2, seconds);

  // Trigger the event
  myEvent.broadcast();
}

broadcastAndWait#

Inicia la función de devolución de llamada y espera hasta que finalice (o se agote el tiempo de espera).

Available Functions
void broadcastAndWait( int32_t timeout = 60000 );

Parameters

Parámetro

Tipo

Descripción

timeout

int32_t

Cantidad de milisegundos que se deben esperar antes de que el código vuelva a ejecutarse (el valor predeterminado es 60000).

Return Values

Esta función no devuelve ningún valor.

Notes
  • Utilice esto únicamente con funciones de devolución de llamada que finalicen (sin bucles infinitos).

  • Se trata de una función de espera que bloquea la ejecución hasta que la función de devolución de llamada finaliza o se agota el tiempo de espera.

Examples

Define the callback function (outside of int main())

// Create a callback function
void startDriving() {
  Drivetrain.drive(forward);
  wait(2, seconds);
}

Register the callback inside int main()

int main() {
  /* vexcodeInit() is only required when using VEXcode.
  Remove vexcodeInit() if compiling in VS Code. */
  vexcodeInit();

  Brain.Screen.print("Starting drive...");

  event driveEvent(startDriving);
  // Give the event time to be set
  wait(0.25, seconds);

  // Run the event and wait until it finishes
  driveEvent.broadcastAndWait();

  // Stop driving after 2 seconds
  Drivetrain.stop();
  Brain.Screen.clearScreen();
  Brain.Screen.print("Drive complete!");
}