summaryrefslogtreecommitdiffstats
path: root/example/event_ops.c
blob: 2d1f586409aa0aa7b52f1b50a3f51be615ca9db3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#include <stdlib.h>
#include <sys/types.h>
#include <sys/time.h>
#include <signal.h>
#include <event.h>

#include <libdect.h>
#include "common.h"

struct dect_handle *dh;

static void event_callback(int fd, short mask, void *data)
{
	struct dect_fd *dfd = data;
	uint32_t events;

	events = 0;
	if (mask & EV_READ)
		events |= DECT_FD_READ;
	if (mask & EV_WRITE)
		events |= DECT_FD_WRITE;

	dfd->callback(dh, dfd, events);
}

static int register_fd(const struct dect_handle *dh, struct dect_fd *dfd,
		       uint32_t events)
{
	struct event *ev = (struct event *)dfd->priv;
	unsigned short mask;

	mask = EV_PERSIST;
	if (events & DECT_FD_READ)
		mask |= EV_READ;
	if (events & DECT_FD_WRITE)
		mask |= EV_WRITE;

	event_set(ev, dfd->fd, mask, event_callback, dfd);
	event_add(ev, NULL);
	return 0;
}

static void unregister_fd(const struct dect_handle *dh, struct dect_fd *dfd)
{
	struct event *ev = (struct event *)dfd->priv;

	event_del(ev);
}

static void timer_expire(int fd, short mask, void *data)
{
	struct dect_timer *timer = data;

	timer->callback(dh, timer);
}

static void start_timer(const struct dect_handle *dh,
			struct dect_timer *timer,
			const struct timeval *tv)
{
	struct event *ev = (struct event *)timer->priv;

	evtimer_set(ev, timer_expire, timer);
	evtimer_add(ev, (struct timeval *)tv);
}

static void stop_timer(const struct dect_handle *dh, struct dect_timer *timer)
{
	struct event *ev = (struct event *)timer->priv;

	evtimer_del(ev);
}

static const struct dect_event_ops dect_event_ops = {
	.fd_priv_size		= sizeof(struct event),
	.register_fd		= register_fd,
	.unregister_fd		= unregister_fd,
	.timer_priv_size	= sizeof(struct event),
	.start_timer		= start_timer,
	.stop_timer		= stop_timer
};

static struct event_base *ev_base;
static struct event sig_event;
static bool sigint;

static void sig_callback(int fd, short event, void *data)
{
	sigint = true;
}

int dect_event_ops_init(struct dect_ops *ops)
{

	ev_base = event_init();
	if (ev_base == NULL)
		return -1;
	ops->event_ops = &dect_event_ops;

	signal_set(&sig_event, SIGINT, sig_callback, NULL);
	signal_add(&sig_event, NULL);
	return 0;
}

void dect_event_loop(void)
{
	while (!sigint)
		event_loop(EVLOOP_ONCE);
	signal_del(&sig_event);
}

void dect_event_ops_cleanup(void)
{
	event_base_free(ev_base);
}