ledstrip_sandbox/main/main.cpp

366 lines
12 KiB
C++
Raw Normal View History

2021-09-19 04:13:10 +02:00
#include <atomic>
2021-08-28 03:13:01 +02:00
#include <chrono>
#include <csignal>
2021-09-19 04:13:10 +02:00
#include <cstdio>
#include <cstdlib>
#include <cstring>
2021-09-16 14:27:35 +02:00
#include <optional>
2021-09-19 04:13:10 +02:00
#include <thread>
#include <unordered_map>
2021-08-28 03:13:01 +02:00
#include "interpreter_config.h"
2021-09-16 14:27:35 +02:00
#include "json.hpp"
2021-09-19 04:13:10 +02:00
#include "log.h"
#include "lua.hpp"
#include "ws2811.h"
2021-08-28 03:13:01 +02:00
#include "httplib.h"
2021-09-16 14:27:35 +02:00
using json = nlohmann::json;
2021-09-16 18:16:30 +02:00
using std::chrono::duration_cast;
using std::chrono::milliseconds;
using std::chrono::system_clock;
2021-09-16 14:27:35 +02:00
2021-09-19 04:13:10 +02:00
#define TARGET_FREQ WS2811_TARGET_FREQ
#define GPIO_PIN 18
#define DMA 10
#define STRIP_TYPE WS2812_STRIP // WS2812/SK6812RGB integrated chip+leds
#define LED_COUNT 30 * 5
2021-08-28 03:13:01 +02:00
2021-09-19 04:13:10 +02:00
#define FPS 15
2021-08-28 03:13:01 +02:00
int frametime = 1000 / FPS;
2021-09-16 14:27:35 +02:00
struct LedSegment {
std::optional<std::thread> lua_thread;
2021-09-19 04:13:10 +02:00
InterpreterConfig *interpreter_config;
2021-09-16 14:27:35 +02:00
std::string owner;
std::string lua_code;
};
2021-09-19 04:13:10 +02:00
std::vector<LedSegment *> ledsegments;
2021-09-16 14:27:35 +02:00
// this map is used to be able to see allowed leds from lua
2021-09-19 04:13:10 +02:00
std::unordered_map<lua_State *, InterpreterConfig *> statemap;
2021-09-15 20:14:12 +02:00
std::atomic<std::uint64_t> framecounter = {0};
2021-09-19 04:13:10 +02:00
ws2811_t ledstring = {
2021-08-28 03:13:01 +02:00
.freq = TARGET_FREQ,
.dmanum = DMA,
.channel =
2021-09-19 04:13:10 +02:00
{
[0] =
{
.gpionum = GPIO_PIN,
.invert = 0,
.count = LED_COUNT,
.strip_type = STRIP_TYPE,
.brightness = 10,
},
[1] =
{
.gpionum = 0,
.invert = 0,
.count = 0,
.brightness = 0,
},
2021-08-28 03:13:01 +02:00
},
};
2021-09-19 04:13:10 +02:00
void hook(lua_State *L, lua_Debug *ar);
2021-09-16 18:16:30 +02:00
inline bool kill_thread_if_desired(lua_State *L) {
2021-09-19 04:13:10 +02:00
if (!statemap[L]->enabled) {
cout << "putting errors on the stack" << endl;
lua_sethook(L, hook, LUA_MASKLINE, 0);
luaL_error(L, "killed by manager");
return true;
2021-09-16 18:16:30 +02:00
}
return false;
}
// TODO also call this hook about once every second
2021-09-19 04:13:10 +02:00
void hook(lua_State *L, lua_Debug *ar) { kill_thread_if_desired(L); }
extern "C" {
static int c_override_print(lua_State *L) {
2021-09-16 18:16:30 +02:00
kill_thread_if_desired(L);
2021-09-19 04:13:10 +02:00
int n = lua_gettop(L); /* number of arguments */
int i;
for (i = 1; i <= n; i++) { /* for each argument */
size_t l;
const char *s = luaL_tolstring(L, i, &l); /* convert it to string */
if (i > 1) /* not the first element? */
statemap[L]->logger << '\t'; /* add a tab before it */
statemap[L]->logger << s; /* print it */
lua_pop(L, 1); /* pop result */
}
statemap[L]->logger << '\n';
return 0;
2021-09-16 18:16:30 +02:00
}
2021-08-28 03:13:01 +02:00
2021-09-19 04:13:10 +02:00
static int c_led(lua_State *L) {
kill_thread_if_desired(L);
int virtual_location = luaL_checkinteger(L, 1);
int red = luaL_checkinteger(L, 2);
int green = luaL_checkinteger(L, 3);
int blue = luaL_checkinteger(L, 4);
InterpreterConfig *config = statemap[L];
// Lua is one-based, let's keep it consistent and also make our API one-based
if (virtual_location <= 0 || virtual_location > (int)config->length) {
std::ostringstream errstream;
errstream << "setting led " << virtual_location << " of strip with lenght "
<< config->length << "";
luaL_argerror(L, 1, errstream.str().c_str());
return 0;
} else if (red < 0 || red > 0xff) {
std::ostringstream errstream;
errstream << "setting red channel to " << red
<< " but should be between 0 and 255";
luaL_argerror(L, 2, errstream.str().c_str());
return 0;
} else if (green < 0 || green > 0xff) {
std::ostringstream errstream;
errstream << "setting green channel to " << green
<< " but should be between 0 and 255";
luaL_argerror(L, 3, errstream.str().c_str());
return 0;
} else if (blue < 0 || blue > 0xff) {
std::ostringstream errstream;
errstream << "setting blue channel to " << blue
<< " but should be between 0 and 255";
luaL_argerror(L, 4, errstream.str().c_str());
2021-08-28 03:13:01 +02:00
return 0;
}
2021-09-19 04:13:10 +02:00
unsigned int real_location = config->begin + virtual_location - 1;
// TODO remove this debugging line
ledstring.channel[0].leds[real_location] = (red << 16) | (green << 8) | blue;
return 0;
}
2021-08-28 03:13:01 +02:00
2021-09-19 04:13:10 +02:00
static int c_ledamount(lua_State *L) {
kill_thread_if_desired(L);
lua_pushinteger(L, statemap[L]->length);
return 1;
}
2021-08-28 03:13:01 +02:00
2021-09-19 04:13:10 +02:00
static int c_delay(lua_State *L) {
if (kill_thread_if_desired(L)) {
return 0;
2021-08-28 03:13:01 +02:00
}
2021-09-19 04:13:10 +02:00
uint64_t millis = luaL_checkinteger(L, 1);
uint64_t begin =
duration_cast<milliseconds>(system_clock::now().time_since_epoch())
.count();
while (duration_cast<milliseconds>(system_clock::now().time_since_epoch())
.count() -
begin <
millis - 100) {
std::this_thread::sleep_for(std::chrono::milliseconds(100 - 5));
if (kill_thread_if_desired(L)) {
return 0;
2021-09-16 18:16:30 +02:00
}
2021-08-28 03:13:01 +02:00
}
2021-09-19 04:13:10 +02:00
uint64_t passed =
(duration_cast<milliseconds>(system_clock::now().time_since_epoch())
.count() -
begin);
std::this_thread::sleep_for(std::chrono::milliseconds(millis - passed));
return 0;
}
2021-08-28 03:13:01 +02:00
2021-09-19 04:13:10 +02:00
static int c_waitframes(lua_State *L) {
kill_thread_if_desired(L);
// TODO this is incorrect, fix this
int amount = luaL_checkinteger(L, 1);
uint64_t destination = amount + framecounter;
if (amount >= 2 * FPS) {
std::this_thread::sleep_for(
std::chrono::milliseconds(1000 * ((amount / FPS) - 1)));
2021-08-28 03:13:01 +02:00
}
2021-09-19 04:13:10 +02:00
while (framecounter <= destination) {
std::this_thread::sleep_for(std::chrono::milliseconds(frametime / 2));
}
return 0;
}
2021-08-28 03:13:01 +02:00
}
// Thanks to https://www.stefanmisik.com/post/sandboxing-lua-from-c.html
2021-09-19 04:13:10 +02:00
static void LuaLoadAndUndefine(lua_State *L, lua_CFunction openFunction,
const char *moduleName,
const char *functions[]) {
/* Load the module, the module table gets placed on the top of the stack */
luaL_requiref(L, moduleName, openFunction, 1);
/* Undefine the unwanted functions */
for (int i = 0; functions[i] != NULL; i++) {
lua_pushnil(L);
lua_setfield(L, -2, functions[i]);
}
2021-08-28 03:13:01 +02:00
2021-09-19 04:13:10 +02:00
/* Pop the module table */
lua_pop(L, 1);
2021-08-28 03:13:01 +02:00
}
2021-09-19 04:13:10 +02:00
lua_State *setup_lua_sandbox(const char *luacode) {
lua_State *L = luaL_newstate();
2021-08-28 03:13:01 +02:00
L = luaL_newstate();
if (!L) {
return nullptr;
}
2021-09-19 04:13:10 +02:00
static const char *remove_base[] = {"assert", "collectgarbage",
"dofile", "getmetatable",
"loadfile", "load",
"loadstring", "rawequal",
"rawlen", "rawget",
"rawset", "setmetatable",
"print", NULL};
2021-08-28 03:13:01 +02:00
LuaLoadAndUndefine(L, luaopen_base, "_G", remove_base);
2021-09-19 04:13:10 +02:00
static const char *remove_str[] = {"dump", NULL};
2021-08-28 03:13:01 +02:00
LuaLoadAndUndefine(L, luaopen_string, LUA_STRLIBNAME, remove_str);
2021-09-19 04:13:10 +02:00
static const char *all_allowed[] = {NULL};
2021-08-28 03:13:01 +02:00
LuaLoadAndUndefine(L, luaopen_table, LUA_TABLIBNAME, all_allowed);
LuaLoadAndUndefine(L, luaopen_math, LUA_MATHLIBNAME, all_allowed);
2021-09-19 04:13:10 +02:00
lua_pushcfunction(L, c_led);
2021-08-28 03:13:01 +02:00
lua_setglobal(L, "led");
lua_pushcfunction(L, c_ledamount);
lua_setglobal(L, "ledamount");
lua_pushcfunction(L, c_delay);
lua_setglobal(L, "delay");
lua_pushcfunction(L, c_waitframes);
lua_setglobal(L, "waitframes");
lua_pushcfunction(L, c_override_print);
lua_setglobal(L, "print");
luaL_loadbuffer(L, luacode, strlen(luacode), "script");
2021-09-16 18:16:30 +02:00
lua_sethook(L, hook, LUA_MASKCOUNT, 1000);
2021-08-28 03:13:01 +02:00
return L;
}
2021-09-19 04:13:10 +02:00
int execute_lua_sandbox(lua_State *L) {
2021-08-28 03:13:01 +02:00
int ret = lua_pcall(L, 0, 0, 0);
if (ret != 0) {
2021-09-19 04:05:24 +02:00
// TODO get full stacktrace
luaL_traceback(L, L, lua_tostring(L, -1), 1);
2021-08-28 03:13:01 +02:00
statemap[L]->logger << "CRASH: " << lua_tostring(L, -1) << '\n';
lua_close(L);
return 1;
}
lua_close(L);
return 0;
}
2021-09-19 04:13:10 +02:00
std::thread spawn_lua_tread(const char *luacode, InterpreterConfig *config) {
lua_State *L = setup_lua_sandbox(luacode);
2021-08-28 03:13:01 +02:00
statemap[L] = config;
std::thread t(execute_lua_sandbox, L);
return t;
}
void signal_callback_handler(int signum) {
2021-09-19 04:13:10 +02:00
(void)signum;
2021-08-28 03:13:01 +02:00
ws2811_fini(&ledstring);
exit(1);
}
2021-09-15 22:27:30 +02:00
httplib::Server svr;
2021-09-19 04:13:10 +02:00
void starthttpserver() { svr.listen("0.0.0.0", 8080); }
2021-08-28 03:13:01 +02:00
2021-09-19 04:13:10 +02:00
int main(int argc, char **argv) {
2021-09-16 14:27:35 +02:00
unsigned int amount = 10;
unsigned int leds_per_segment = LED_COUNT / amount;
for (unsigned int i = 0; i < amount; i++) {
2021-09-19 04:13:10 +02:00
InterpreterConfig *config =
new InterpreterConfig{.begin = leds_per_segment * i,
.length = leds_per_segment,
.enabled = true};
2021-09-16 14:27:35 +02:00
cout << config->begin << endl;
2021-09-19 04:13:10 +02:00
LedSegment *segment = new LedSegment{.lua_thread = std::nullopt,
.interpreter_config = config,
.owner = "",
.lua_code = ""};
2021-09-16 14:27:35 +02:00
ledsegments.push_back(segment);
}
2021-09-15 22:27:30 +02:00
2021-09-19 04:13:10 +02:00
svr.Get("/api/segments.json",
[](const httplib::Request &, httplib::Response &res) {
res.set_header("Access-Control-Allow-Origin", "*");
res.set_header("Access-Control-Allow-Methods", "GET");
json j;
int i = 0;
for (LedSegment *ledsegment : ledsegments) {
json o;
o["begin"] = ledsegment->interpreter_config->begin;
o["length"] = ledsegment->interpreter_config->length;
o["owner"] = ledsegment->owner;
o["code"] = ledsegment->lua_code;
o["id"] = i;
i++;
j.push_back(o);
}
res.set_content(j.dump(), "text/json");
});
svr.Put("/api/code.json", [](const httplib::Request &req,
httplib::Response &res,
const httplib::ContentReader &content_reader) {
2021-09-19 03:50:03 +02:00
res.set_header("Access-Control-Allow-Origin", "*");
res.set_header("Access-Control-Allow-Methods", "PUT");
2021-09-16 14:27:35 +02:00
if (req.is_multipart_form_data()) {
res.set_content("No multipart forms allowed", "text/plain");
return true;
} else {
content_reader([&](const char *raw_data, size_t data_length) {
std::string data(raw_data, data_length);
auto j = json::parse(data);
2021-09-19 04:13:10 +02:00
LedSegment *selected = ledsegments.at(j["id"].get<unsigned int>());
2021-09-16 14:27:35 +02:00
if (selected->lua_thread.has_value()) {
2021-09-16 18:16:30 +02:00
selected->interpreter_config->enabled = false;
selected->lua_thread.value().join();
2021-09-16 14:27:35 +02:00
}
selected->owner = j["owner"].get<std::string>();
selected->lua_code = j["code"].get<std::string>();
2021-09-16 18:16:30 +02:00
selected->interpreter_config->enabled = true;
2021-09-19 04:13:10 +02:00
selected->lua_thread = spawn_lua_tread(selected->lua_code.c_str(),
selected->interpreter_config);
cout << "Uploaded new code from " << selected->owner << " to segment "
<< j["id"].get<unsigned int>() << endl;
2021-09-16 14:27:35 +02:00
return true;
});
}
return true;
2021-08-28 03:13:01 +02:00
});
2021-09-19 04:13:10 +02:00
svr.Options("/api/code.json",
[](const httplib::Request &req, httplib::Response &res) {
res.set_header("Access-Control-Allow-Origin", "*");
res.set_header("Access-Control-Allow-Methods", "PUT");
return true;
});
2021-09-19 03:50:03 +02:00
2021-09-15 22:27:30 +02:00
std::thread httpserverthread(starthttpserver);
2021-08-28 03:13:01 +02:00
ws2811_return_t ret;
2021-09-19 04:13:10 +02:00
if ((ret = ws2811_init(&ledstring)) != WS2811_SUCCESS) {
fprintf(stderr, "ws2811_init failed: %s\n", ws2811_get_return_t_str(ret));
return ret;
2021-08-28 03:13:01 +02:00
}
signal(SIGINT, signal_callback_handler);
signal(SIGHUP, signal_callback_handler);
signal(SIGTERM, signal_callback_handler);
2021-09-15 23:02:16 +02:00
ledstring.channel[0].leds[10] = 0x00200000;
ledstring.channel[0].leds[11] = 0x00002000;
ledstring.channel[0].leds[12] = 0x00000020;
2021-08-28 03:13:01 +02:00
while (true) {
ws2811_render(&ledstring);
std::this_thread::sleep_for(std::chrono::milliseconds(frametime));
}
2021-09-19 03:50:03 +02:00
}