/modules/timer/timer.c
C | 101 lines | 71 code | 23 blank | 7 comment | 4 complexity | d52a7a1bf8a3478ccc66228fb6888ade MD5 | raw file
Possible License(s): GPL-3.0, GPL-2.0
1/*
2 * For more information, visit https://cesbo.com
3 * Copyright (C) 2012, Andrey Dyldin <and@cesbo.com>
4 */
5
6#include <astra.h>
7
8#define LOG_MSG(_msg) "[timer] " _msg
9
10struct module_data_s
11{
12 MODULE_BASE();
13
14 struct
15 {
16 int interval;
17 } config;
18
19 int idx_cb;
20 int idx_self;
21
22 void *timer;
23};
24
25/* callbacks */
26
27static void timer_callback(void *arg)
28{
29 module_data_t *mod = arg;
30 lua_State *L = LUA_STATE(mod);
31 lua_rawgeti(L, LUA_REGISTRYINDEX, mod->idx_cb);
32 lua_rawgeti(L, LUA_REGISTRYINDEX, mod->idx_self);
33 lua_call(L, 1, 0);
34}
35
36/* methods */
37
38static int method_close(module_data_t *mod)
39{
40 lua_State *L = LUA_STATE(mod);
41
42 if(mod->timer)
43 {
44 timer_detach(mod->timer);
45 mod->timer = NULL;
46 }
47
48 luaL_unref(L, LUA_REGISTRYINDEX, mod->idx_self);
49 mod->idx_self = 0;
50 luaL_unref(L, LUA_REGISTRYINDEX, mod->idx_cb);
51 mod->idx_cb = 0;
52
53 return 0;
54}
55
56/* required */
57
58static void module_configure(module_data_t *mod)
59{
60 module_set_number(mod, "interval", 1, 0, &mod->config.interval);
61 if(mod->config.interval <= 0)
62 {
63 log_error(LOG_MSG("option \"interval\" must be greater than 0"));
64 abort();
65 }
66
67 lua_State *L = LUA_STATE(mod);
68 lua_getfield(L, 2, "callback");
69 if(lua_type(L, -1) != LUA_TFUNCTION)
70 {
71 log_error(LOG_MSG("option \"callback\" must be a function"));
72 abort();
73 }
74 luaL_checktype(L, -1, LUA_TFUNCTION);
75 mod->idx_cb = luaL_ref(L, LUA_REGISTRYINDEX);
76
77}
78static void module_initialize(module_data_t *mod)
79{
80 module_configure(mod);
81
82 lua_State *L = LUA_STATE(mod);
83
84 lua_pushvalue(L, -1);
85 mod->idx_self = luaL_ref(L, LUA_REGISTRYINDEX);
86
87 mod->timer = timer_attach(mod->config.interval * 1000
88 , timer_callback, mod);
89}
90
91static void module_destroy(module_data_t *mod)
92{
93 method_close(mod);
94}
95
96MODULE_METHODS()
97{
98 METHOD(close)
99};
100
101MODULE(timer)