Refactor http server

This commit is contained in:
offtkp 2023-07-24 10:37:02 +03:00
parent 4a24a331da
commit 3a21661f45
5 changed files with 212 additions and 152 deletions

View file

@ -3,34 +3,75 @@
#include <array>
#include <atomic>
#include <condition_variable>
#include <map>
#include <memory>
#include <mutex>
#include <queue>
#include <thread>
#include "helpers.hpp"
enum class HttpAction { None, Screenshot, PressKey, ReleaseKey };
enum class HttpActionType { None, Screenshot, Key };
class Emulator;
namespace httplib {
class Server;
class Response;
} // namespace httplib
// Wrapper for httplib::Response that allows the HTTP server to wait for the response to be ready
struct DeferredResponseWrapper {
DeferredResponseWrapper(httplib::Response& response) : inner_response(response) {}
httplib::Response& inner_response;
std::mutex mutex;
std::condition_variable cv;
bool ready = false;
};
// Actions derive from this class and are used to communicate with the HTTP server
class HttpAction {
public:
HttpAction(HttpActionType type) : type(type) {}
virtual ~HttpAction() = default;
HttpActionType getType() const { return type; }
static std::unique_ptr<HttpAction> createScreenshotAction(DeferredResponseWrapper& response);
static std::unique_ptr<HttpAction> createKeyAction(uint32_t key, bool state);
private:
HttpActionType type;
};
struct HttpServer {
HttpServer(Emulator* emulator);
~HttpServer();
void processActions();
private:
static constexpr const char* httpServerScreenshotPath = "screenshot.png";
std::atomic_bool pendingAction = false;
HttpAction action = HttpAction::None;
std::mutex actionMutex = {};
u32 pendingKey = 0;
Emulator* emulator;
HttpServer();
std::unique_ptr<httplib::Server> server;
void startHttpServer();
std::string status();
std::thread httpServerThread;
std::queue<std::unique_ptr<HttpAction>> actionQueue;
std::mutex actionQueueMutex;
private:
std::map<std::string, std::pair<u32, bool>> keyMap;
std::array<bool, 12> pressedKeys = {};
std::map<std::string, u32> keyMap;
bool paused = false;
void startHttpServer();
void pushAction(std::unique_ptr<HttpAction> action);
std::string status();
u32 stringToKey(const std::string& key_name);
bool getKeyState(const std::string& key_name);
void setKeyState(const std::string& key_name, bool state);
HttpServer(const HttpServer&) = delete;
HttpServer& operator=(const HttpServer&) = delete;
};
#endif // PANDA3DS_ENABLE_HTTP_SERVER