Skip to content

Commit

Permalink
websocket for steamvr shutdown
Browse files Browse the repository at this point in the history
  • Loading branch information
danwillm committed Feb 27, 2022
1 parent c663926 commit 504c1ab
Show file tree
Hide file tree
Showing 5 changed files with 115 additions and 14 deletions.
59 changes: 55 additions & 4 deletions sidecar/main.cpp
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
//clang-format off
#define CROW_MAIN
#define CROW_LOG_LEVEL 0
#define CROW_ENFORCE_WS_SPEC
#include "crow_all.h"

//clang-format on

#include <windows.h>

#include <iomanip>
#include <iostream>
#include <string>
#include <unordered_set>

#include "json.hpp"
#include "openvr.h"
Expand Down Expand Up @@ -231,6 +232,22 @@ std::string GetOpenVRErrorAsString(vr::EVRInitError err) {
}
}

crow::SimpleApp app;
std::mutex connectionMutex;
std::unordered_set<crow::websocket::connection*> connections;

std::atomic<bool> isRunning = true;

void close() {
for (auto u : connections) u->send_text("shutdown");

app.stop();

vr::VR_Shutdown();

isRunning = false;
}

int main() {
vr::EVRInitError initErr = InitOpenVR();
if (initErr != vr::EVRInitError::VRInitError_None) {
Expand All @@ -240,8 +257,6 @@ int main() {

std::cout << "initialised" << std::endl;

crow::SimpleApp app;

CROW_ROUTE(app, "/settings/get").methods(crow::HTTPMethod::Post)([](const crow::request& req) {
auto json = nlohmann::json::parse(req.body, nullptr, true, true);

Expand All @@ -268,5 +283,41 @@ int main() {

CROW_ROUTE(app, "/")([]() { return "Pong"; });

app.port(18080).multithreaded().run();
CROW_ROUTE(app, "/ws")
.websocket()
.onaccept([&](const crow::request&) { return true; })
.onopen([&](crow::websocket::connection& conn) {
std::cout << "user connected" << std::endl;
std::lock_guard<std::mutex> _(connectionMutex);
connections.insert(&conn);
})
.onclose([&](crow::websocket::connection& conn, const std::string& reason) {
CROW_LOG_INFO << "websocket connection closed: " << reason;
std::lock_guard<std::mutex> _(connectionMutex);
connections.erase(&conn);
})
.onmessage([&](crow::websocket::connection& /*conn*/, const std::string& data, bool is_binary) {
std::lock_guard<std::mutex> _(connectionMutex);
if (data == "shutdown") close();
});

std::thread serverThread = std::thread([&]() { app.port(18080).multithreaded().run(); });

while (isRunning) {
vr::VREvent_t event;
while (vr::VRSystem()->PollNextEvent(&event, sizeof event)) {
switch (event.eventType) {
case vr::VREvent_Quit:
vr::VRSystem()->AcknowledgeQuit_Exiting();
std::cout << "shutdown" << std::endl;
close();
break;
}
}

Sleep(100);
}

std::cout << "closing program" << std::endl;
return 0;
}
2 changes: 1 addition & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ tauri-build = { version = "1.0.0-beta.3" }
[dependencies]
serde_json = "1.0"
serde = { version = "1.0", features = [ "derive" ] }
tauri = { version = "1.0.0-beta.8", features = ["fs-read-dir", "fs-read-text-file", "fs-write-file", "http-all", "shell-execute", "shell-open"] }
tauri = { version = "1.0.0-beta.8", features = ["fs-read-dir", "fs-read-text-file", "fs-write-file", "http-all", "shell-execute", "shell-open", "window-all"] }

[features]
default = [ "custom-protocol" ]
Expand Down
3 changes: 3 additions & 0 deletions src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@
"http": {
"all": true,
"request": true
},
"window": {
"all": true
}
},
"windows": [
Expand Down
34 changes: 32 additions & 2 deletions src/pages/_layout.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@
import {onMount} from "svelte";
import Suspense from "../components/Suspense.svelte";
import OrangeButton from "../components/Input/Button/OrangeButton.svelte";
import {SidecarWebsocket} from "../utils/http";
import {process} from "@tauri-apps/api";
import {appWindow} from '@tauri-apps/api/window';
const _urls = [
["./index", "Configuration"],
Expand Down Expand Up @@ -73,18 +77,44 @@
active: !!$isActive(path),
}));
let isClosing = false;
const closeApp = () => {
if (isClosing) return;
isClosing = true;
ToastStore.addToast(ToastStore.severity.WARNING, "SteamVR closed! Closing app...");
setTimeout(() => {
appWindow.close();
process.exit();
}, 1000);
}
const init = async () => {
try {
$state.sidecar.loading = true;
if ($state.sidecar.process) $state.sidecar.process.kill();
await awaitSidecarInit((child) => $state.sidecar.process = child);
$state.sidecar.success = true;
const sidecarWebsocket = new SidecarWebsocket(() => {
$state.sidecar.success = true;
$state.sidecar.loading = false;
}, (event) => {
console.log(event.data);
if (event.data === 'shutdown') closeApp();
}, (event) => {
closeApp();
});
await appWindow.listen('tauri://close-requested', ({event, payload}) => {
sidecarWebsocket.send('shutdown');
})
} catch (e) {
console.error(e);
$state.sidecar.success = false;
ToastStore.addToast(ToastStore.severity.ERROR, e);
} finally {
$state.sidecar.loading = false;
}
}
Expand Down
31 changes: 24 additions & 7 deletions src/utils/http.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import {http} from "@tauri-apps/api";
import {awaitSidecarInit} from "./sidecar";
import {process} from "@tauri-apps/api";
import ToastStore from "../stores/toast";

const basePath = "http://localhost:18080/";
const port = 18080;

export const makeHTTPRequest = async (url, method = "POST", body, retry = true) => {
try {
const response = await http.fetch(basePath + url, {
const response = await http.fetch("http://localhost:" + port + "/" + url, {
method: 'POST',
body: {
type: 'Json',
Expand All @@ -17,15 +18,31 @@ export const makeHTTPRequest = async (url, method = "POST", body, retry = true)

console.error(response);

throw new Error(response.data ?? 'An unknown error occurred');
throw new Error(response.data ? response.data : "An unknown error occurred");
} catch (e) {
//The server has closed, retry connection
//The server has closed
if (typeof e === 'string' && e.includes('(os error 10061)') && retry) {
await awaitSidecarInit();
ToastStore.addToast(ToastStore.severity.WARNING, "Server has closed - closing app.");

return makeHTTPRequest(url, method, body, false);
setTimeout(() => process.exit(), 500);
}
throw e;
}
}

export function SidecarWebsocket(onOpen = () => {
}, onMessage = () => {
}, onClose = () => {
}) {
const socket = new WebSocket('ws://localhost:' + port + "/ws");

socket.addEventListener('open', onOpen);

socket.addEventListener('message', onMessage);

socket.addEventListener('close', onClose);

return {
send: async (data) => socket.send(data)
};
}

0 comments on commit 504c1ab

Please sign in to comment.