11// clang-format off
22#define CROW_MAIN
33#define CROW_LOG_LEVEL 0
4+ #define CROW_ENFORCE_WS_SPEC
45#include " crow_all.h"
56
67// clang-format on
78
89#include < windows.h>
910
10- #include < iomanip>
1111#include < iostream>
1212#include < string>
13+ #include < unordered_set>
1314
1415#include " json.hpp"
1516#include " openvr.h"
@@ -231,6 +232,22 @@ std::string GetOpenVRErrorAsString(vr::EVRInitError err) {
231232 }
232233}
233234
235+ crow::SimpleApp app;
236+ std::mutex connectionMutex;
237+ std::unordered_set<crow::websocket::connection*> connections;
238+
239+ std::atomic<bool > isRunning = true ;
240+
241+ void close () {
242+ for (auto u : connections) u->send_text (" shutdown" );
243+
244+ app.stop ();
245+
246+ vr::VR_Shutdown ();
247+
248+ isRunning = false ;
249+ }
250+
234251int main () {
235252 vr::EVRInitError initErr = InitOpenVR ();
236253 if (initErr != vr::EVRInitError::VRInitError_None) {
@@ -240,8 +257,6 @@ int main() {
240257
241258 std::cout << " initialised" << std::endl;
242259
243- crow::SimpleApp app;
244-
245260 CROW_ROUTE (app, " /settings/get" ).methods (crow::HTTPMethod::Post)([](const crow::request& req) {
246261 auto json = nlohmann::json::parse (req.body , nullptr , true , true );
247262
@@ -268,5 +283,41 @@ int main() {
268283
269284 CROW_ROUTE (app, " /" )([]() { return " Pong" ; });
270285
271- app.port (18080 ).multithreaded ().run ();
286+ CROW_ROUTE (app, " /ws" )
287+ .websocket ()
288+ .onaccept ([&](const crow::request&) { return true ; })
289+ .onopen ([&](crow::websocket::connection& conn) {
290+ std::cout << " user connected" << std::endl;
291+ std::lock_guard<std::mutex> _ (connectionMutex);
292+ connections.insert (&conn);
293+ })
294+ .onclose ([&](crow::websocket::connection& conn, const std::string& reason) {
295+ CROW_LOG_INFO << " websocket connection closed: " << reason;
296+ std::lock_guard<std::mutex> _ (connectionMutex);
297+ connections.erase (&conn);
298+ })
299+ .onmessage ([&](crow::websocket::connection& /* conn*/ , const std::string& data, bool is_binary) {
300+ std::lock_guard<std::mutex> _ (connectionMutex);
301+ if (data == " shutdown" ) close ();
302+ });
303+
304+ std::thread serverThread = std::thread ([&]() { app.port (18080 ).multithreaded ().run (); });
305+
306+ while (isRunning) {
307+ vr::VREvent_t event;
308+ while (vr::VRSystem ()->PollNextEvent (&event, sizeof event)) {
309+ switch (event.eventType ) {
310+ case vr::VREvent_Quit:
311+ vr::VRSystem ()->AcknowledgeQuit_Exiting ();
312+ std::cout << " shutdown" << std::endl;
313+ close ();
314+ break ;
315+ }
316+ }
317+
318+ Sleep (100 );
319+ }
320+
321+ std::cout << " closing program" << std::endl;
322+ return 0 ;
272323}
0 commit comments