Statistics
| Branch: | Revision:

napa-baselibs / common / common.c @ 507372bb

History | View | Annotate | Download (1.95 KB)

1
/*
2
 * Common functions (mostly init stuff) for NAPA
3
 */
4

    
5
#include        <stdio.h>
6
#include        <stdlib.h>
7
#include        <math.h>
8

    
9
#include        <event2/event.h>
10

    
11

    
12
#include        "napa.h"
13
#include        "napa_log.h"
14

    
15
struct event_base *eventbase = NULL;
16

    
17
#if 0
18
        /* Won't need this for normal operation */
19
void never_callback(evutil_socket_t fd, short what, void *arg) {
20
        fatal("It's the end of the world!");
21
}
22
#endif
23

    
24
/** Initialize the software. This should be called FIRST */
25
void napaInit(void *event2_base) {
26
        eventbase = event2_base;
27
#if 0
28
        /* Won't need this for normal operation */
29
        struct timeval t = { 1000*1000*1000, 0 };
30
        event_base_once(eventbase, -1, EV_TIMEOUT, never_callback, NULL, &t);
31
#endif
32
}
33

    
34
void napaYield() {
35
        event_base_loop(eventbase, EVLOOP_ONCE);
36
}
37

    
38
struct periodic {
39
        void(*cb)(HANDLE handle, void *arg);
40
        void *cbarg;
41
        double frequency;
42
};
43

    
44
void schedule_periodic_callback(evutil_socket_t fd, short what, void *arg) {
45
        struct periodic *p = arg;
46
        /* This indicates STOP */
47
        if (p == NULL || p->frequency == 0.0) {
48
                if (arg) free(arg);
49
                return;
50
        }
51
        
52
        double next = 1.0 / p->frequency;
53
        struct timeval t = { floor(next), fmod(next,1.0) * 1000000.0 };
54
        event_base_once(eventbase, -1, EV_TIMEOUT, schedule_periodic_callback, arg, &t);
55
        if (p->cb) p->cb(arg, p->cbarg);
56
}
57

    
58

    
59
HANDLE napaSchedulePeriodic(const struct timeval *start, double frequency, void(*cb)(HANDLE handle, void *arg), void *cbarg) {
60
        struct timeval t = { 0,0 };
61
        if (start) t = *start;
62
        struct periodic *h = malloc(sizeof(struct periodic));
63
        if (!h) return NULL;
64

    
65
        h->cb = cb;
66
        h->cbarg = cbarg;
67
        h->frequency = frequency;
68

    
69
        event_base_once(eventbase, -1, EV_TIMEOUT, schedule_periodic_callback, h, &t);
70
        return h;
71
}
72

    
73
void napaStopPeriodic(HANDLE h) {
74
        struct periodic *p = h;
75
        p->frequency = 0.0;
76
}
77

    
78

    
79
const char *timeval2str(const struct timeval *ts) {
80
        if (ts->tv_sec == 0 && ts->tv_usec == 0) return "0";
81
 
82
        static char buf[100];
83
        sprintf(buf, "%ld%03ld", ts->tv_sec, ts->tv_usec/1000);
84
 
85
        return buf;
86
}
87

    
88