Run clang-format on source

This commit is contained in:
redfast00 2021-09-19 04:13:10 +02:00
parent e070010401
commit eb14a20f89
No known key found for this signature in database
GPG key ID: 5946E0E34FD0553C
3 changed files with 253 additions and 241 deletions

View file

@ -1,12 +1,13 @@
#include <string>
#include "log.h" #include "log.h"
#include <string>
using namespace std; using namespace std;
struct InterpreterConfig { struct InterpreterConfig {
unsigned int begin; unsigned int begin;
unsigned int length; unsigned int length;
bool enabled; bool enabled;
std::string scriptkey; // To change the script in this part of the interpreter and get logger output std::string scriptkey; // To change the script in this part of the interpreter
// and get logger output
std::string persistkey; // To persist the current running script to disk std::string persistkey; // To persist the current running script to disk
Log logger; Log logger;
}; };

View file

@ -1,6 +1,6 @@
#include <iostream> #include <iostream>
#include <vector>
#include <sstream> #include <sstream>
#include <vector>
#ifndef _LOG_ #ifndef _LOG_
#define _LOG_ #define _LOG_
@ -9,10 +9,8 @@ class Log {
public: public:
Log() {} Log() {}
Log(unsigned int s) { size = s; } Log(unsigned int s) { size = s; }
~Log() { ~Log() {}
} template <typename T> Log &operator<<(const T &msg) {
template<typename T>
Log& operator<<(const T &msg) {
std::stringstream current_string; std::stringstream current_string;
current_string << msg; current_string << msg;
os << msg; os << msg;

View file

@ -1,18 +1,18 @@
#include <cstdio>
#include <thread>
#include <chrono>
#include <cstring>
#include <cstdlib>
#include <csignal>
#include <unordered_map>
#include <atomic> #include <atomic>
#include <chrono>
#include <csignal>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <optional> #include <optional>
#include <thread>
#include <unordered_map>
#include "interpreter_config.h"
#include "json.hpp"
#include "log.h"
#include "lua.hpp" #include "lua.hpp"
#include "ws2811.h" #include "ws2811.h"
#include "interpreter_config.h"
#include "log.h"
#include "json.hpp"
#include "httplib.h" #include "httplib.h"
@ -21,7 +21,6 @@ using std::chrono::duration_cast;
using std::chrono::milliseconds; using std::chrono::milliseconds;
using std::chrono::system_clock; using std::chrono::system_clock;
#define TARGET_FREQ WS2811_TARGET_FREQ #define TARGET_FREQ WS2811_TARGET_FREQ
#define GPIO_PIN 18 #define GPIO_PIN 18
#define DMA 10 #define DMA 10
@ -44,20 +43,21 @@ std::vector<LedSegment*> ledsegments;
// this map is used to be able to see allowed leds from lua // this map is used to be able to see allowed leds from lua
std::unordered_map<lua_State *, InterpreterConfig *> statemap; std::unordered_map<lua_State *, InterpreterConfig *> statemap;
std::atomic<std::uint64_t> framecounter = {0}; std::atomic<std::uint64_t> framecounter = {0};
ws2811_t ledstring = ws2811_t ledstring = {
{
.freq = TARGET_FREQ, .freq = TARGET_FREQ,
.dmanum = DMA, .dmanum = DMA,
.channel = .channel =
{ {
[0] = { [0] =
{
.gpionum = GPIO_PIN, .gpionum = GPIO_PIN,
.invert = 0, .invert = 0,
.count = LED_COUNT, .count = LED_COUNT,
.strip_type = STRIP_TYPE, .strip_type = STRIP_TYPE,
.brightness = 10, .brightness = 10,
}, },
[1] = { [1] =
{
.gpionum = 0, .gpionum = 0,
.invert = 0, .invert = 0,
.count = 0, .count = 0,
@ -68,8 +68,7 @@ ws2811_t ledstring =
void hook(lua_State *L, lua_Debug *ar); void hook(lua_State *L, lua_Debug *ar);
inline bool kill_thread_if_desired(lua_State *L) { inline bool kill_thread_if_desired(lua_State *L) {
if (!statemap[L]->enabled) if (!statemap[L]->enabled) {
{
cout << "putting errors on the stack" << endl; cout << "putting errors on the stack" << endl;
lua_sethook(L, hook, LUA_MASKLINE, 0); lua_sethook(L, hook, LUA_MASKLINE, 0);
luaL_error(L, "killed by manager"); luaL_error(L, "killed by manager");
@ -79,10 +78,7 @@ inline bool kill_thread_if_desired(lua_State *L) {
} }
// TODO also call this hook about once every second // TODO also call this hook about once every second
void hook(lua_State* L, lua_Debug *ar) void hook(lua_State *L, lua_Debug *ar) { kill_thread_if_desired(L); }
{
kill_thread_if_desired(L);
}
extern "C" { extern "C" {
static int c_override_print(lua_State *L) { static int c_override_print(lua_State *L) {
@ -112,22 +108,26 @@ extern "C" {
// Lua is one-based, let's keep it consistent and also make our API one-based // 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) { if (virtual_location <= 0 || virtual_location > (int)config->length) {
std::ostringstream errstream; std::ostringstream errstream;
errstream << "setting led " << virtual_location << " of strip with lenght " << config->length << ""; errstream << "setting led " << virtual_location << " of strip with lenght "
<< config->length << "";
luaL_argerror(L, 1, errstream.str().c_str()); luaL_argerror(L, 1, errstream.str().c_str());
return 0; return 0;
} else if (red < 0 || red > 0xff) { } else if (red < 0 || red > 0xff) {
std::ostringstream errstream; std::ostringstream errstream;
errstream << "setting red channel to " << red << " but should be between 0 and 255"; errstream << "setting red channel to " << red
<< " but should be between 0 and 255";
luaL_argerror(L, 2, errstream.str().c_str()); luaL_argerror(L, 2, errstream.str().c_str());
return 0; return 0;
} else if (green < 0 || green > 0xff) { } else if (green < 0 || green > 0xff) {
std::ostringstream errstream; std::ostringstream errstream;
errstream << "setting green channel to " << green << " but should be between 0 and 255"; errstream << "setting green channel to " << green
<< " but should be between 0 and 255";
luaL_argerror(L, 3, errstream.str().c_str()); luaL_argerror(L, 3, errstream.str().c_str());
return 0; return 0;
} else if (blue < 0 || blue > 0xff) { } else if (blue < 0 || blue > 0xff) {
std::ostringstream errstream; std::ostringstream errstream;
errstream << "setting blue channel to " << blue << " but should be between 0 and 255"; errstream << "setting blue channel to " << blue
<< " but should be between 0 and 255";
luaL_argerror(L, 4, errstream.str().c_str()); luaL_argerror(L, 4, errstream.str().c_str());
return 0; return 0;
} }
@ -144,15 +144,27 @@ extern "C" {
} }
static int c_delay(lua_State *L) { static int c_delay(lua_State *L) {
if (kill_thread_if_desired(L)) {return 0;} if (kill_thread_if_desired(L)) {
uint64_t millis = luaL_checkinteger (L, 1); return 0;
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;}
} }
uint64_t passed = (duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count() - begin); 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;
}
}
uint64_t passed =
(duration_cast<milliseconds>(system_clock::now().time_since_epoch())
.count() -
begin);
std::this_thread::sleep_for(std::chrono::milliseconds(millis - passed)); std::this_thread::sleep_for(std::chrono::milliseconds(millis - passed));
return 0; return 0;
} }
@ -163,7 +175,8 @@ extern "C" {
int amount = luaL_checkinteger(L, 1); int amount = luaL_checkinteger(L, 1);
uint64_t destination = amount + framecounter; uint64_t destination = amount + framecounter;
if (amount >= 2 * FPS) { if (amount >= 2 * FPS) {
std::this_thread::sleep_for(std::chrono::milliseconds(1000 * ((amount / FPS) - 1))); std::this_thread::sleep_for(
std::chrono::milliseconds(1000 * ((amount / FPS) - 1)));
} }
while (framecounter <= destination) { while (framecounter <= destination) {
std::this_thread::sleep_for(std::chrono::milliseconds(frametime / 2)); std::this_thread::sleep_for(std::chrono::milliseconds(frametime / 2));
@ -173,14 +186,14 @@ extern "C" {
} }
// Thanks to https://www.stefanmisik.com/post/sandboxing-lua-from-c.html // Thanks to https://www.stefanmisik.com/post/sandboxing-lua-from-c.html
static void LuaLoadAndUndefine(lua_State* L, lua_CFunction openFunction, const char* moduleName, const char* functions[]) 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 */ /* Load the module, the module table gets placed on the top of the stack */
luaL_requiref(L, moduleName, openFunction, 1); luaL_requiref(L, moduleName, openFunction, 1);
/* Undefine the unwanted functions */ /* Undefine the unwanted functions */
for (int i = 0; functions[i] != NULL; i++) for (int i = 0; functions[i] != NULL; i++) {
{
lua_pushnil(L); lua_pushnil(L);
lua_setfield(L, -2, functions[i]); lua_setfield(L, -2, functions[i]);
} }
@ -196,10 +209,13 @@ lua_State* setup_lua_sandbox(const char* luacode) {
return nullptr; return nullptr;
} }
static const char* remove_base[] = {"assert", static const char *remove_base[] = {"assert", "collectgarbage",
"collectgarbage", "dofile", "getmetatable", "loadfile", "load", "dofile", "getmetatable",
"loadstring", "rawequal", "rawlen", "rawget", "rawset", "loadfile", "load",
"setmetatable", "print", NULL}; "loadstring", "rawequal",
"rawlen", "rawget",
"rawset", "setmetatable",
"print", NULL};
LuaLoadAndUndefine(L, luaopen_base, "_G", remove_base); LuaLoadAndUndefine(L, luaopen_base, "_G", remove_base);
static const char *remove_str[] = {"dump", NULL}; static const char *remove_str[] = {"dump", NULL};
LuaLoadAndUndefine(L, luaopen_string, LUA_STRLIBNAME, remove_str); LuaLoadAndUndefine(L, luaopen_string, LUA_STRLIBNAME, remove_str);
@ -253,33 +269,26 @@ void signal_callback_handler(int signum) {
httplib::Server svr; httplib::Server svr;
void starthttpserver() { void starthttpserver() { svr.listen("0.0.0.0", 8080); }
svr.listen("0.0.0.0", 8080);
}
int main(int argc, char **argv) {
int main(int argc, char** argv)
{
unsigned int amount = 10; unsigned int amount = 10;
unsigned int leds_per_segment = LED_COUNT / amount; unsigned int leds_per_segment = LED_COUNT / amount;
for (unsigned int i = 0; i < amount; i++) { for (unsigned int i = 0; i < amount; i++) {
InterpreterConfig* config = new InterpreterConfig { InterpreterConfig *config =
.begin = leds_per_segment*i, new InterpreterConfig{.begin = leds_per_segment * i,
.length = leds_per_segment, .length = leds_per_segment,
.enabled = true .enabled = true};
};
cout << config->begin << endl; cout << config->begin << endl;
LedSegment* segment = new LedSegment { LedSegment *segment = new LedSegment{.lua_thread = std::nullopt,
.lua_thread = std::nullopt,
.interpreter_config = config, .interpreter_config = config,
.owner = "", .owner = "",
.lua_code = "" .lua_code = ""};
};
ledsegments.push_back(segment); ledsegments.push_back(segment);
} }
svr.Get("/api/segments.json", [](const httplib::Request &, httplib::Response &res) { svr.Get("/api/segments.json",
[](const httplib::Request &, httplib::Response &res) {
res.set_header("Access-Control-Allow-Origin", "*"); res.set_header("Access-Control-Allow-Origin", "*");
res.set_header("Access-Control-Allow-Methods", "GET"); res.set_header("Access-Control-Allow-Methods", "GET");
json j; json j;
@ -297,7 +306,9 @@ int main(int argc, char** argv)
res.set_content(j.dump(), "text/json"); res.set_content(j.dump(), "text/json");
}); });
svr.Put("/api/code.json", [](const httplib::Request &req, httplib::Response &res, const httplib::ContentReader &content_reader) { svr.Put("/api/code.json", [](const httplib::Request &req,
httplib::Response &res,
const httplib::ContentReader &content_reader) {
res.set_header("Access-Control-Allow-Origin", "*"); res.set_header("Access-Control-Allow-Origin", "*");
res.set_header("Access-Control-Allow-Methods", "PUT"); res.set_header("Access-Control-Allow-Methods", "PUT");
if (req.is_multipart_form_data()) { if (req.is_multipart_form_data()) {
@ -315,15 +326,18 @@ int main(int argc, char** argv)
selected->owner = j["owner"].get<std::string>(); selected->owner = j["owner"].get<std::string>();
selected->lua_code = j["code"].get<std::string>(); selected->lua_code = j["code"].get<std::string>();
selected->interpreter_config->enabled = true; selected->interpreter_config->enabled = true;
selected->lua_thread = spawn_lua_tread(selected->lua_code.c_str(), selected->interpreter_config); selected->lua_thread = spawn_lua_tread(selected->lua_code.c_str(),
cout << "Uploaded new code from " << selected->owner << " to segment " << j["id"].get<unsigned int>() << endl; selected->interpreter_config);
cout << "Uploaded new code from " << selected->owner << " to segment "
<< j["id"].get<unsigned int>() << endl;
return true; return true;
}); });
} }
return true; return true;
}); });
svr.Options("/api/code.json", [](const httplib::Request &req, httplib::Response &res) { 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-Origin", "*");
res.set_header("Access-Control-Allow-Methods", "PUT"); res.set_header("Access-Control-Allow-Methods", "PUT");
return true; return true;
@ -332,8 +346,7 @@ int main(int argc, char** argv)
std::thread httpserverthread(starthttpserver); std::thread httpserverthread(starthttpserver);
ws2811_return_t ret; ws2811_return_t ret;
if ((ret = ws2811_init(&ledstring)) != WS2811_SUCCESS) if ((ret = ws2811_init(&ledstring)) != WS2811_SUCCESS) {
{
fprintf(stderr, "ws2811_init failed: %s\n", ws2811_get_return_t_str(ret)); fprintf(stderr, "ws2811_init failed: %s\n", ws2811_get_return_t_str(ret));
return ret; return ret;
} }