All files / src/lib opc-ws.js

0% Statements 0/75
0% Branches 0/1
0% Functions 0/1
0% Lines 0/75

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90                                                                                                                                                                                   
/**
 * OPC WebSocket Client - Real-time updates
 */
 
import { getToken } from "./api.js";
 
let ws = null;
let reconnectTimer = null;
let listeners = new Set();
 
export function connect() {
  if (ws && ws.readyState === WebSocket.OPEN) {
    return;
  }
 
  const protocol = window.location.protocol === "https:" ? "wss:" : "ws:";
  const token = getToken();
  const tokenParam = token ? `?token=${encodeURIComponent(token)}` : "";
  const wsUrl = `${protocol}//${window.location.host}/ws/opc${tokenParam}`;
 
  ws = new WebSocket(wsUrl);
 
  ws.onopen = () => {
    console.log("OPC WebSocket connected");
    if (reconnectTimer) {
      clearTimeout(reconnectTimer);
      reconnectTimer = null;
    }
 
    // Send ping every 30 seconds to keep connection alive
    const pingInterval = setInterval(() => {
      if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send("ping");
      } else {
        clearInterval(pingInterval);
      }
    }, 30000);
  };
 
  ws.onmessage = (event) => {
    try {
      const message = JSON.parse(event.data);
      notifyListeners(message);
    } catch (e) {
      console.error("Failed to parse WebSocket message:", e);
    }
  };
 
  ws.onerror = (error) => {
    console.error("WebSocket error:", error);
  };
 
  ws.onclose = () => {
    console.log("OPC WebSocket disconnected");
    ws = null;
 
    // Reconnect after 5 seconds
    reconnectTimer = setTimeout(() => {
      console.log("Reconnecting WebSocket...");
      connect();
    }, 5000);
  };
}
 
export function disconnect() {
  if (ws) {
    ws.close();
    ws = null;
  }
  if (reconnectTimer) {
    clearTimeout(reconnectTimer);
    reconnectTimer = null;
  }
}
 
export function subscribe(callback) {
  listeners.add(callback);
  return () => listeners.delete(callback);
}
 
function notifyListeners(message) {
  listeners.forEach((callback) => {
    try {
      callback(message);
    } catch (e) {
      console.error("Listener error:", e);
    }
  });
}