Implementing an Event Loop for Effective Communication with the Base System

Using an event loop is a practical way to communicate efficiently with the base system in ACU6 applications. As an application grows, the event loop and its supporting functions often become more complex. To keep the code clear and maintainable, it is good practice to separate the event loop from the rest of the application. This chapter walks through how to build that structure.

Inspecting the API for LED Control in the ACU6 System

Understanding the API for controlling LEDs is part of building the led-example application. The API provides the interfaces and protocols used to interact with the LED system through IPC. The LED API is documented in the System Service API.

Key Points of the LED API

System service
  • Location in the System Service API: The LED service is part of the

    System Service API and uses the IPC ID A_SERVICE_ID_SYSTEM.

  • IPC Call Process: To manipulate the LED state, the process involves an

    IPC call:

    • A request is sent with the message led_set_req.

    • This request triggers a response from the base system of the type led_set_rsp.

Creating a New File ipc.h for Event Handling

Create a new file named ipc.h in the /package/led-example/files/ directory. This file declares the IPC helpers used by the main loop in led_example.c. It keeps IPC setup, message sending, and event dispatch separate from the top-level application control flow while keeping the small amount of IPC-specific runtime state inside ipc.c.

Key Components of ipc.h

Header Guards and Includes: The file starts with include guards and the headers needed for the implementation.

#ifndef IPC_H_
#define IPC_H_

#include <actia/actia.h>
#include <stdbool.h>
#include <stdint.h>
#include <sys/epoll.h>

#include "led_example.h"

#define IPC_OUTBOX_SIZE 1
#define IPC_INBOX_SIZE 1

#define LED_ON 1
#define LED_OFF 0

int ipc_initialize_actia_ipc(int ipc_id, int epfd);

A_IPC_RESULT ipc_send_open_session_req(int to);

bool ipc_handle_actia_ipc_event(struct epoll_event *event);

A_IPC_RESULT ipc_set_led(a_ipc_enum_led_pin_type led, uint8_t state);

void ipc_destroy_actia_ipc(void);

#endif  // IPC_H_

LED State Constants: Constants for LED states are defined for ease of code readability.

Function Declarations: The header declares helpers for IPC initialization, session startup, epoll event handling, LED requests, and IPC teardown.

Closing Header Guard: This ends the conditional preprocessor directive to close the header file.

Source: ipc.h

Implementing the IPC Helper in ipc.c

For effective event handling in the ACU6 system, create the ipc.c file in /package/led-example/files/, which includes definitions corresponding to the declarations in ipc.h. This file handles the IPC-specific work, including the small bit of runtime state needed to track whether the LED is currently on, while led_example.c owns the top-level event loop.

Key Elements of ipc.c

Includes and Initialization: The file starts with necessary includes, similar to the header file, but adds epoll for event handling.

#include <actia/actia.h>
#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <unistd.h>

#include "ipc.h"

#define IPC_MSG_BUF_SIZE 256
#define IPC_OUTBOX_SIZE  512
#define IPC_INBOX_SIZE   512

A_IPC_STATIC_BUFFERS_BYTES(ipc_buffers, IPC_INBOX_SIZE, IPC_OUTBOX_SIZE);
A_IPC_STATIC_MSG(msg, IPC_MSG_BUF_SIZE);

typedef struct {
    bool session_open;
} ipc_state_t;

static a_ipc_handle *a_ipc;
static ipc_state_t ipc_state = {
    .session_open = false,
};
static uint8_t pending_led_state = LED_OFF;

static void ipc_handle_open_session_rsp(a_ipc_msg_ipc_open_session_rsp *msg_rsp)
{
    if (msg_rsp->result != A_IPC_ENUM_IPC_OPEN_SESSION_RESULT_OK) {
        fprintf(stderr, "Error opening session: %d\n", msg_rsp->result);
        set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
        return;
    }

    ipc_state.session_open = true;

    A_IPC_RESULT rc = ipc_set_led(A_IPC_ENUM_LED_PIN_TYPE_GREEN, LED_ON);
    if (rc != A_IPC_RET_OK) {
        fprintf(stderr, "Couldn't send message\n");
        set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
        return;
    }
}

static void ipc_handle_led_set_rsp(a_ipc_msg_led_set_rsp *msg_rsp)
{
    if (msg_rsp->result != A_IPC_ENUM_LED_RESULT_OK) {
        fprintf(stderr, "Error lighting LED: %d\n", msg_rsp->result);
        set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
    } else if (pending_led_state == LED_ON) {
        sleep(1);

        A_IPC_RESULT rc = ipc_set_led(A_IPC_ENUM_LED_PIN_TYPE_GREEN, LED_OFF);
        if (rc != A_IPC_RET_OK) {
            fprintf(stderr, "Couldn't send message\n");
            set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
            return;
        }

    } else {
        set_event_loop_state(EVENT_LOOP_EXIT_OK);
    }
}

int ipc_initialize_actia_ipc(int ipc_id, int epfd)
{
    a_ipc = a_ipc_init(ipc_id, &ipc_buffers);

    if (a_ipc == NULL) {
        return -ENOMEM;
    }

    struct epoll_event ipc_events = {
        .events = EPOLLIN,
        .data.fd = a_ipc_get_fd(a_ipc),
    };

    if (epoll_ctl(epfd, EPOLL_CTL_ADD, a_ipc_get_fd(a_ipc), &ipc_events) == -1) {
        fprintf(stderr, "Error epoll_ctl ipc_fd, EPOLL_CTL_ADD: %d\n", errno);
        int saved_errno = errno;
        a_ipc_destroy(a_ipc);
        return -saved_errno;
    }

    return a_ipc_get_fd(a_ipc);
}

A_IPC_RESULT ipc_send_open_session_req(int to)
{
    A_IPC_RESULT rc = a_ipc_init_ipc_open_session_req(msg);
    if (rc != A_IPC_RET_OK) {
        fprintf(stderr, "Failed to create open session request: %s\n", a_ipc_result_str(rc));
        return rc;
    }

    rc = a_ipc_send(a_ipc, to, msg);
    if (rc != A_IPC_RET_OK) {
        fprintf(stderr, "Failed to send open session request: %s\n", a_ipc_result_str(rc));
        return rc;
    }
}

bool ipc_handle_actia_ipc_event(struct epoll_event *event)
{
    if (!(event->events & EPOLLIN) || event->data.fd != a_ipc_get_fd(a_ipc)) {
        return false;
    }

    int from = -1;
    A_IPC_RESULT rc = a_ipc_recv(a_ipc, &from, msg);

    if (rc != A_IPC_RET_OK) {
        fprintf(stderr, "Failed to fetch message\n");
        set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
        return true;
    }

    (void)from;

    switch (msg->info.type) {
    case A_IPC_MSG_IPC_OPEN_SESSION_RSP:
        ipc_handle_open_session_rsp(&msg->ipc_open_session_rsp);
        break;
    case A_IPC_MSG_LED_SET_RSP:
        ipc_handle_led_set_rsp(&msg->led_set_rsp);
        break;
    default:
        fprintf(stderr, "Unrecognized response received\n");
        set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
        break;
    }

    return true;
}

A_IPC_RESULT ipc_set_led(a_ipc_enum_led_pin_type led, uint8_t state)
{
    A_IPC_RESULT rc = a_ipc_init_led_set_req(msg);
    if (rc != A_IPC_RET_OK) {
        fprintf(stderr, "Could not init A_IPC_LED_SET_REQ message %d\n", rc);
        return rc;
    }

    msg->led_set_req.pin = led;
    msg->led_set_req.value = state;

    pending_led_state = state;

    return a_ipc_send(a_ipc, A_SERVICE_ID_SYSTEM, msg);
}

void ipc_destroy_actia_ipc(void)
{
    if (a_ipc != NULL) {
        a_ipc_destroy(a_ipc);
        a_ipc = NULL;
    }
    ipc_state.session_open = false;

Defining Static Variables: ipc_buffers initializes the message queues. a_ipc stores the IPC instance, msg is the reusable message buffer used for send and receive operations, and ipc_state keeps the IPC-specific runtime state internal to the helper.

The main helpers in ipc.c initialize the IPC instance, add the IPC file descriptor to epoll, send the session request, and dispatch incoming messages to the correct response handlers.

IPC Initialization: ipc_initialize_actia_ipc() ties together the IPC ID, the message buffers, and the epoll file descriptor owned by the main loop.

Opening Session Request: ipc_send_open_session_req() builds and sends the open-session request to the system service.

Response Dispatch: ipc_handle_actia_ipc_event() receives incoming messages and forwards them to the appropriate response helpers.

LED Requests: ipc_set_led() wraps message creation and sending for LED state changes.

Source: ipc.c

Implementing the Initial LED Example

Implement the main event loop in led_example.c. Update led_example.c with the following content:

#include <actia/actia.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <unistd.h>

#include "ipc.h"
#include "led_example.h"

#define IPC_ID (A_IPC_GUEST_MIN_ID + 9)

static event_loop_state_t event_loop_state = EVENT_LOOP_RUN;

void set_event_loop_state(event_loop_state_t state)
{
    event_loop_state = state;
}

static int event_loop(void)
{
    int rc = EXIT_SUCCESS;
    int epfd = epoll_create1(0);

    if (epfd < 0) {
        rc = EXIT_FAILURE;
        goto err_return;
    }

    int ipc_fd = ipc_initialize_actia_ipc(IPC_ID, epfd);

    if (ipc_fd < 0) {
        rc = EXIT_FAILURE;
        goto err_close_epfd;
    }

    A_IPC_RESULT ipc_rc = ipc_send_open_session_req(A_SERVICE_ID_SYSTEM);

    if (ipc_rc != A_IPC_RET_OK) {
        fprintf(stderr, "Failed to send open session request: %s\n", a_ipc_result_str(ipc_rc));
        rc = EXIT_FAILURE;
        goto err_close_actia_ipc;
    }

    while (event_loop_state == EVENT_LOOP_RUN) {
        struct epoll_event events[3];
        int event_count = 0;

        do {
            event_count = epoll_wait(epfd, events, a_membersof(events), -1);
        } while (event_count < 0 && errno == EINTR);

        if (event_count > 0) {
            for (int e = 0; e < event_count; ++e) {
                if (ipc_handle_actia_ipc_event(&events[e])) {
                    /* Intentionally empty */
                } else {
                    fprintf(stderr, "Unexpected epoll_wait result\n");
                    set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
                }

                if (event_loop_state != EVENT_LOOP_RUN) {
                    break;
                }
            }
        } else if (event_count < 0) {
            fprintf(stderr, "Error while waiting for event: %d\n", errno);
            set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
        }
    }

    if (event_loop_state != EVENT_LOOP_EXIT_OK) {
        rc = EXIT_FAILURE;
    }

err_close_actia_ipc:
    ipc_destroy_actia_ipc();
err_close_epfd:
    close(epfd);
err_return:
    return rc;
}

int main(void)
{
    printf("LEDs are fun\n");

    return event_loop();
}

Event-loop state: led_example.c stores the loop state, while the IPC helper keeps its own runtime state internally.

Epoll-based main loop: event_loop() owns epoll setup and delegates IPC-specific events to ipc_handle_actia_ipc_event().

Session startup: The main loop explicitly opens the session before entering steady-state event processing.

Main function: main() focuses on startup and then transfers control to the event loop.

Source: led_example.c

Adjust Makefile and Verify

Update the Makefile to integrate the new components into the build process:

Add led_example.c and ipc.c to the compilation sources, ensuring they are compiled with the rest of the project.

TARGET_BIN  = led-example

CFLAGS  += -MMD -MP -Wall -Wextra -pedantic -Werror -Wno-error=deprecated-declarations

LIBS    += -lactia

C_SRCS   = led_example.c
C_SRCS   += ipc.c

OBJS     += $(patsubst %.c, $(BUILD_DIR)/%.o, $(C_SRCS))
OBJS     += $(patsubst %.S, $(BUILD_DIR)/%.o, $(ASM_SRCS))

DEPS = $(OBJS:%.o=%.d)

BUILD_DIR = build

.PHONY: all

all: $(BUILD_DIR)/$(TARGET_BIN)

$(BUILD_DIR)/$(TARGET_BIN): $(OBJS)
	@echo LINK $@ $(LDFLAGS)
	@$(CC) $(CFLAGS) $(LDFLAGS) $(OBJS) $(LIBS) -o $@

$(BUILD_DIR)/%.o: %.c
	@echo CC $<
	@mkdir -p $(@D)
	@$(CC) -c $(CFLAGS) $< -o $@

install: all
	@install -m 755 $(BUILD_DIR)/$(TARGET_BIN) $(DESTDIR)/$(PREFIX)/bin

clean:
	@-rm -rf $(BUILD_DIR)/

-include $(DEPS)

Verification Steps:

  1. Clean the build directory: make buildroot-led-example-dirclean

  2. Compile the project: make

  3. Flash the compiled program onto the target device: make flash

  4. Connect to the device: ssh acu6pro

  5. Run the program on the device: led-example

After running the program, verify that it exits cleanly. When the program starts, the message LEDs are fun should be printed, and the middle green LED should light for a couple of seconds.

Source: Makefile