Add a Timer to the Event Loop
One useful feature of epoll is that it can monitor different kinds of file descriptors, including timers. This makes it possible to extend the event loop with timed behavior.
Expanding Interface
To use the timer effectively, the IPC helper
interface must support arming and disarming the timer while keeping the
top-level event loop in led_example.c focused on orchestration.
The periodic sequence timer is added on top of the retry timeout handling from
the previous chapter, but the timer helpers remain internal to ipc.c.
The public interface only changes because the event handler now receives the
CLI options that control the bounded demo run:
#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,
const led_example_options_t *params);
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_
The timer helpers such as sequence_timer_arm(), retry_timer_arm(), and
retry_timer_disarm() remain internal details of ipc.c.
Adding Timer to Epoll
Start by modifying ipc.c to keep the retry timer from the previous chapter
and add a separate timer file descriptor for the rolling LED sequence.
Initial Setup
#include <actia/actia.h>
#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <sys/timerfd.h>
#include <time.h>
#include <unistd.h>
#include "ipc.h"
#define IPC_MSG_BUF_SIZE 256
#define IPC_OUTBOX_SIZE 512
#define IPC_INBOX_SIZE 512
#define NUM_LEDS 3
A_IPC_STATIC_BUFFERS_BYTES(ipc_buffers, IPC_INBOX_SIZE, IPC_OUTBOX_SIZE);
A_IPC_STATIC_MSG(msg, IPC_MSG_BUF_SIZE);
typedef enum {
IPC_PENDING_REQUEST_NONE = 0,
IPC_PENDING_REQUEST_OPEN_SESSION,
IPC_PENDING_REQUEST_LED_SET,
} ipc_pending_request_t;
typedef struct {
bool session_open;
int ticks;
} ipc_state_t;
static a_ipc_handle *a_ipc;
static int sequence_timer_fd = -1;
static int retry_timer_fd = -1;
static ipc_state_t ipc_state = {
.session_open = false,
.ticks = 0,
};
static ipc_pending_request_t pending_request = IPC_PENDING_REQUEST_NONE;
static a_ipc_enum_led_pin_type pending_led = A_IPC_ENUM_LED_PIN_TYPE_RED;
static uint8_t pending_led_state = LED_OFF;
static bool sequence_timer_started = false;
static bool sequence_advance_pending = false;
static size_t current_led_index = 0;
static a_ipc_enum_led_pin_type leds[NUM_LEDS] = {
A_IPC_ENUM_LED_PIN_TYPE_RED,
A_IPC_ENUM_LED_PIN_TYPE_GREEN,
A_IPC_ENUM_LED_PIN_TYPE_BLUE,
};
Include the sys/timerfd.h header, keep the retry timeout state, and define
the additional sequence timer state used by the rolling LED behavior.
Configuring the Timers
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;
}
retry_timer_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
if (retry_timer_fd < 0) {
fprintf(stderr, "Couldn't create retry timer\n");
int saved_errno = errno;
a_ipc_destroy(a_ipc);
return -saved_errno;
}
struct epoll_event retry_timer_event = {
.events = EPOLLIN,
.data.fd = retry_timer_fd,
};
if (epoll_ctl(epfd, EPOLL_CTL_ADD, retry_timer_fd, &retry_timer_event) == -1) {
fprintf(stderr, "Error epoll_ctl retry_timer_fd, EPOLL_CTL_ADD: %d\n", errno);
int saved_errno = errno;
close(retry_timer_fd);
retry_timer_fd = -1;
a_ipc_destroy(a_ipc);
return -saved_errno;
}
sequence_timer_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
if (sequence_timer_fd < 0) {
fprintf(stderr, "Couldn't create timer\n");
int saved_errno = errno;
close(retry_timer_fd);
retry_timer_fd = -1;
a_ipc_destroy(a_ipc);
return -saved_errno;
}
struct epoll_event timer_event = {
.events = EPOLLIN,
.data.fd = sequence_timer_fd,
};
if (epoll_ctl(epfd, EPOLL_CTL_ADD, sequence_timer_fd, &timer_event) == -1) {
fprintf(stderr, "Error epoll_ctl sequence_timer_fd, EPOLL_CTL_ADD: %d\n", errno);
int saved_errno = errno;
close(sequence_timer_fd);
sequence_timer_fd = -1;
close(retry_timer_fd);
retry_timer_fd = -1;
a_ipc_destroy(a_ipc);
return -saved_errno;
}
return a_ipc_get_fd(a_ipc);
This code creates both the one-shot retry timer and the periodic sequence timer, then adds both file descriptors to the epoll set managed by the main loop.
Modifying the Event Loop
bool ipc_handle_actia_ipc_event(struct epoll_event *event,
const led_example_options_t *params)
{
if ((event->events & EPOLLIN) && event->data.fd == retry_timer_fd) {
uint64_t timers = 0;
ssize_t read_size = read(retry_timer_fd, &timers, sizeof(timers));
if (read_size != (ssize_t)sizeof(timers)) {
fprintf(stderr, "Failed to read retry timer\n");
set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
return true;
}
ipc_handle_retry_timer_event();
return true;
}
if ((event->events & EPOLLIN) && event->data.fd == sequence_timer_fd) {
uint64_t timers = 0;
ssize_t read_size = read(sequence_timer_fd, &timers, sizeof(timers));
if (read_size != (ssize_t)sizeof(timers)) {
fprintf(stderr, "Failed to read sequence timer\n");
set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
return true;
}
ipc_handle_sequence_timer_event();
return true;
}
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);
ipc_handle_actia_ipc_event() now checks for retry-timer events, sequence-
timer events, and IPC messages. This keeps retry handling and periodic LED
sequencing in the same event loop without mixing up their responsibilities.
Arming the Sequence Timer
static int sequence_timer_arm(uint32_t start_time, uint32_t interval)
{
struct itimerspec ts = {0};
ts.it_value.tv_sec = (time_t)start_time;
ts.it_interval.tv_sec = (time_t)interval;
return timerfd_settime(sequence_timer_fd, 0, &ts, NULL);
}
The sequence_timer_arm function is used for setting the start time and
interval for the sequence timer. retry_timer_arm and
retry_timer_disarm are used internally whenever there is an outstanding
request waiting for a response.
Adding Logic to the Main Program
The goal is to create a program that sequences the lighting of LEDs in a
rolling pattern. led_example.c keeps the iteration state, while ipc.c
contains the timer-driven LED sequencing logic.
Defining LED Order and Iteration Variables
static event_loop_state_t event_loop_state = EVENT_LOOP_RUN;
static led_example_options_t params = {
.max_ticks = 0,
};
The params structure stores the CLI-configured max_ticks value.
Runtime values such as session_open and ticks now live inside
ipc.c so the IPC helper owns the timer-driven sequencing state without
burdening the top-level event loop.
Implementing the Timer Callback
static void ipc_handle_open_session_rsp(a_ipc_msg_ipc_open_session_rsp *msg_rsp)
{
if (pending_request != IPC_PENDING_REQUEST_OPEN_SESSION) {
return;
}
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;
}
if (ipc_clear_pending_request() < 0) {
return;
}
ipc_state.session_open = true;
current_led_index = 0;
sequence_advance_pending = false;
A_IPC_RESULT rc = ipc_set_led(leds[0], LED_ON);
if (rc != A_IPC_RET_OK) {
fprintf(stderr, "Couldn't send message\n");
set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
return;
}
ipc_state.ticks = 0;
}
static void ipc_handle_led_set_rsp(a_ipc_msg_led_set_rsp *msg_rsp,
const led_example_options_t *params)
{
a_ipc_enum_led_pin_type completed_led = pending_led;
uint8_t completed_led_state = pending_led_state;
if (pending_request != IPC_PENDING_REQUEST_LED_SET) {
return;
}
if (!ipc_state.session_open) {
return;
}
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);
return;
}
if (ipc_clear_pending_request() < 0) {
return;
}
if (!sequence_timer_started &&
completed_led == leds[current_led_index] &&
completed_led_state == LED_ON) {
if (sequence_timer_arm(1, 1) < 0) {
fprintf(stderr, "Couldn't arm timer\n");
set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
return;
}
sequence_timer_started = true;
return;
}
if (!sequence_advance_pending ||
completed_led != leds[current_led_index] ||
completed_led_state != LED_OFF) {
return;
}
sequence_advance_pending = false;
++ipc_state.ticks;
if ((ipc_state.ticks >= params->max_ticks) && (params->max_ticks != 0)) {
set_event_loop_state(EVENT_LOOP_EXIT_OK);
return;
}
current_led_index = (current_led_index + 1) % NUM_LEDS;
A_IPC_RESULT rc = ipc_set_led(leds[current_led_index], LED_ON);
if (rc != A_IPC_RET_OK) {
fprintf(stderr, "Couldn't send message\n");
set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
}
}
static void ipc_handle_sequence_timer_event(void)
{
if (!ipc_state.session_open) {
return;
}
if (pending_request != IPC_PENDING_REQUEST_NONE) {
return;
}
A_IPC_RESULT rc = ipc_set_led(leds[current_led_index], LED_OFF);
if (rc != A_IPC_RET_OK) {
fprintf(stderr, "Couldn't send message\n");
set_event_loop_state(EVENT_LOOP_EXIT_ERROR);
return;
}
sequence_advance_pending = true;
}
This logic starts the rolling sequence after the session opens, waits for each LED response before advancing, and keeps the retry state aligned with the single request that is currently outstanding.
Updating the IPC Handler
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], ¶ms)) {
/* 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(int argc, char **argv)
{
if (argc < 2) {
params.max_ticks = 0;
} else if (argc == 2) {
params.max_ticks = atoi(argv[1]);
} else {
printf("Usage: led-example <max_ticks>, leave blank to run indefinitely");
return 0;
}
printf("LEDs are fun\n");
return event_loop();
}
The main function remains focused on parsing the optional iteration count and starting the event loop, while the helper manages the timer callbacks.
Argument Handling in Main Function
int main(int argc, char **argv)
{
if (argc < 2) {
params.max_ticks = 0;
} else if (argc == 2) {
params.max_ticks = atoi(argv[1]);
} else {
printf("Usage: led-example <max_ticks>, leave blank to run indefinitely");
return 0;
}
printf("LEDs are fun\n");
return event_loop();
}
This main function allows for an optional max_ticks argument. Each tick
represents one completed step in the rolling LED sequence. If no argument is
provided, the program keeps running until it is stopped manually.
Verification Process
To verify the proper functioning of the updated application, follow the standard rebuild and execution steps. Additionally, run the program with an argument to ensure it stops as expected.
Rebuilding the Application
Clean the build directory:
make buildroot-led-example-dircleanCompile the application:
makeFlash the compiled program onto the target device:
make flashConnect to the device:
ssh acu6proRun the program using the new argument:
led-example 3
Counting LED Pulses
After executing the program, observe the behavior of the LEDs.
The 3 argument limits the run to three sequence ticks, so the lightshow
stops automatically after a short demonstration. This bounded run is useful
for testing the timer-driven behavior without leaving the program running
indefinitely.