1 | #include "owl.h" |
---|
2 | |
---|
3 | #define OWL_TIMER_DIRECTION_COUNTUP 1 |
---|
4 | #define OWL_TIMER_DIRECTION_COUNTDOWN 2 |
---|
5 | |
---|
6 | |
---|
7 | /* Create a "counting up" timer. The counter starts running as soon |
---|
8 | * as this is called. Use owl_timer_reset() to reset it. |
---|
9 | */ |
---|
10 | void owl_timer_create_countup(owl_timer *t) |
---|
11 | { |
---|
12 | t->direction=OWL_TIMER_DIRECTION_COUNTUP; |
---|
13 | t->starttime=time(NULL); |
---|
14 | } |
---|
15 | |
---|
16 | /* create a "counting down" timer, which counts down from 'start' |
---|
17 | * seconds. The counter starts running as soon as this is called. |
---|
18 | * Use owl_timer_reset to reset it. |
---|
19 | */ |
---|
20 | void owl_timer_create_countdown(owl_timer *t, int start) |
---|
21 | { |
---|
22 | t->direction=OWL_TIMER_DIRECTION_COUNTDOWN; |
---|
23 | t->start=start; |
---|
24 | t->starttime=time(NULL); |
---|
25 | } |
---|
26 | |
---|
27 | /* Reset the timer. For a "counting up" timer, it is reset to 0. For |
---|
28 | * a "counting down" timer it is set to the value initially set with |
---|
29 | * owl_timer_create_countdown() or the last value set with |
---|
30 | * owl_timer_reset_newstart() */ |
---|
31 | void owl_timer_reset(owl_timer *t) |
---|
32 | { |
---|
33 | t->starttime=time(NULL); |
---|
34 | } |
---|
35 | |
---|
36 | /* Only for a countdown timer. Rest the timer, but this time (and on |
---|
37 | * future resets) start with 'start' seconds. |
---|
38 | */ |
---|
39 | void owl_timer_reset_newstart(owl_timer *t, int start) |
---|
40 | { |
---|
41 | t->start=start; |
---|
42 | t->starttime=time(NULL); |
---|
43 | } |
---|
44 | |
---|
45 | /* Return the number of seconds elapsed or remaining. If using a |
---|
46 | * countdown timer, a negative value is never reported. Once the |
---|
47 | * timer gets to 0 it stays at 0 */ |
---|
48 | int owl_timer_get_time(owl_timer *t) |
---|
49 | { |
---|
50 | time_t now; |
---|
51 | int rem; |
---|
52 | |
---|
53 | now=time(NULL); |
---|
54 | |
---|
55 | if (t->direction==OWL_TIMER_DIRECTION_COUNTUP) { |
---|
56 | return(now-t->starttime); |
---|
57 | } else if (t->direction==OWL_TIMER_DIRECTION_COUNTDOWN) { |
---|
58 | rem=t->start-(now-t->starttime); |
---|
59 | if (rem<0) return(0); |
---|
60 | return(rem); |
---|
61 | } |
---|
62 | |
---|
63 | /* never reached */ |
---|
64 | return(0); |
---|
65 | } |
---|
66 | |
---|
67 | /* Only for countdown timer. Return true if time has run out (the |
---|
68 | * timer is at 0 seconds or less |
---|
69 | */ |
---|
70 | int owl_timer_is_expired(owl_timer *t) |
---|
71 | { |
---|
72 | if (owl_timer_get_time(t)==0) return(1); |
---|
73 | return(0); |
---|
74 | } |
---|