Files
thrawn/src/LuaEngine.h

90 lines
2.1 KiB
C++

#if !defined(LUA_ENGINE_H)
#define LUA_ENGINE_H
#include "Service.h"
#include "Cache.h"
#include <vector>
#include <functional>
#include <string>
#include "DBLogger.h"
#include "croncpp/croncpp.h"
#include <ctime>
#include <queue>
#include "spdlog/spdlog.h"
struct ScheduledService {
cron::cronexpr cron;
std::time_t next_run;
LuaService* service;
std::string callback;
void next();
bool operator<(const ScheduledService& rhs) const;
};
class LuaEngine {
private:
LuaEngine();
public:
std::function<void(const TopicState& state)> publish;
DBLogger db_logger;
std::priority_queue<ScheduledService> time_schedule;
static LuaEngine& get_instance() {
static LuaEngine instance;
return instance;
}
std::vector<LuaService> services;
Cache cache;
void load_services();
void start_services();
LuaService* create_service(std::string filename);
LuaService* service_by_lua_state(lua_State* lua);
LuaEngine(LuaEngine const&) = delete;
void operator=(LuaEngine const&) = delete;
};
template<typename Arg, typename... Args>
inline bool check_arguments(lua_State* lua, int stack_pos) {
return check_arguments<Args...>(lua, stack_pos+1) && check_arguments<Arg>(lua, stack_pos);
}
template<typename Arg, typename... Args>
inline bool check_arguments(lua_State* lua) {
int num_arg = sizeof...(Args) + 1;
return check_arguments<Arg, Args...>(lua, num_arg * -1);
}
template <>
inline bool check_arguments<std::string>(lua_State* lua, int stack_pos) {
return lua_isstring(lua, stack_pos);
}
template <>
inline bool check_arguments<int>(lua_State* lua, int stack_pos) {
return lua_isnumber(lua, stack_pos);
}
template <>
inline bool check_arguments<bool>(lua_State* lua, int stack_pos) {
return lua_isnumber(lua, stack_pos);
}
template<typename F>
void lua_func_call(LuaService& service, const std::string& lua_func, F push_params) {
lua_getglobal(service.lua, lua_func.c_str());
int num_arguments = push_params();
if (lua_pcall(service.lua, num_arguments, 0, 0) != 0) {
spdlog::error("[{}] Unable to call '{}'. [Lua: '{}']", lua_func, service.name);
return;
}
}
#endif // LUA_ENGINE_H