Eventos#

Introducción#

Los eventos permiten iniciar una función de forma asíncrona. Cuando se transmite un evento, su función de devolución de llamada 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 desea que sucedan varias cosas a partir de un disparador, puede:

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

  • Utilice múltiples objetos de evento y transmita cada uno de ellos.

  • Utilice subprocesos separados para ejecutar tareas de forma independiente.

Para crear y luego utilizar 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.

Class Constructors#

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 v(* 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 );

Class Destructor#

Destroys the event object and releases associated resources.

~event();

Parameters#

Parámetro

Type

Descripción

callback

void (*)(void)

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

v

event

An existing event object to copy from.

callback

void (*)(void *)

A function that accepts a void pointer argument and executes when the event is broadcasted.

arg

void *

A pointer to data that will be passed to the callback function.

Notes#

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

  • Si desea que sucedan varias cosas a partir de un disparador, puede:

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

    • Utilice múltiples objetos de evento y transmita cada uno de ellos.

    • Use separate threads to run tasks independently.

Example#

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

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

Member Functions#

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#

Sets a callback function for the event using the function call operator.

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

Parameters

Parámetro

Type

Descripción

callback

void (*)(void)

Una función de devolución de llamada previamente definida que se llama automáticamente al transmitir 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

This function does not return a value.

Notes
  • Setting a callback again replaces the previous callback.

  • The callback function must have no parameters and return void.

Examples
void drawSquare() {
  Brain.Screen.clearScreen();
  Brain.Screen.drawRectangle(40, 40, 120, 120);
}

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

// 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

This function does not take any parameters.

Return Values

This function does not return a value.

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

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#

Starts the callback and waits until it finishes (or times out).

Available Functions
void broadcastAndWait( int32_t timeout = 60000 );

Parameters

Parámetro

Type

Descripción

timeout

int32_t

The amount of milliseconds to wait before the code starts executing again (defaults to 60000).

Return Values

This function does not return a value.

Notes
  • Use this only with callbacks that end (no infinite loops).

  • This is a waiting function that blocks execution until the callback completes or times out.

Examples
void startDriving() {
  Drivetrain.drive(forward);
  wait(2, seconds);
}


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!");