FreeDATA/freedata-gui/src/js/event_sock.js

57 lines
1.5 KiB
JavaScript
Raw Normal View History

2023-11-13 06:21:13 +00:00
import {
eventDispatcher,
stateDispatcher,
connectionFailed,
} from "../js/eventHandler.js";
2023-11-09 16:14:22 +00:00
import { addDataToWaterfall } from "../js/waterfallHandler.js";
2023-11-09 14:48:10 +00:00
2023-11-13 19:22:11 +00:00
// ----------------- init pinia stores -------------
import { setActivePinia } from "pinia";
import pinia from "../store/index";
setActivePinia(pinia);
2023-11-18 15:53:54 +00:00
import { settingsStore as settings } from "../store/settingsStore.js";
2023-11-13 19:22:11 +00:00
2023-11-09 16:14:22 +00:00
function connect(endpoint, dispatcher) {
let socket = new WebSocket(
2023-11-18 15:53:54 +00:00
"ws://" + settings.local.host + ":" + settings.local.port + "/" + endpoint,
);
2023-11-09 12:52:47 +00:00
// handle opening
socket.addEventListener("open", function (event) {
2024-02-08 12:39:18 +00:00
//console.log("Connected to the WebSocket server: " + endpoint);
2023-11-09 12:52:47 +00:00
});
// handle data
socket.addEventListener("message", function (event) {
2023-11-09 16:15:12 +00:00
dispatcher(event.data);
2024-01-04 19:59:10 +00:00
return;
2023-11-09 12:52:47 +00:00
});
// handle errors
socket.addEventListener("error", function (event) {
2024-02-08 12:39:18 +00:00
//console.error("WebSocket error:", event);
2023-11-13 06:21:13 +00:00
connectionFailed(endpoint, event);
2023-11-09 12:52:47 +00:00
});
// handle closing and reconnect
socket.addEventListener("close", function (event) {
2024-02-08 12:39:18 +00:00
//console.log("WebSocket connection closed:", event.code);
2023-11-09 12:52:47 +00:00
// Reconnect handler
2023-11-09 14:48:10 +00:00
if (!event.wasClean) {
2023-11-09 12:52:47 +00:00
setTimeout(() => {
2024-02-08 12:39:18 +00:00
//console.log("Reconnecting to websocket");
2023-11-09 16:14:22 +00:00
connect(endpoint, dispatcher);
2023-11-09 12:52:47 +00:00
}, 1000);
}
});
2023-11-09 09:37:45 +00:00
}
2023-11-09 16:14:22 +00:00
// Initial connection attempts to endpoints
2023-11-20 13:24:45 +00:00
export function initConnections() {
connect("states", stateDispatcher);
connect("events", eventDispatcher);
connect("fft", addDataToWaterfall);
}