Files
Sheep-Service/web/lib/components/cloud.js
Rozenrod 3f08f3f6c9 Додана сторінка "Стенд"
Додане повідомлення про оновлення застосунку
Оновлен Service Worker
Перероблен WebSocket APІ
2025-10-19 00:55:30 +03:00

95 lines
3.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const Cloud = {
status: null,
socket: null,
reconnectTimeout: null,
reconnectAttempts: 0,
reconnecting: false,
start() {
Cloud.status = 'sync';
const uuid = localStorage.getItem("uuid");
if (Cloud.socket && Cloud.socket.readyState <= 1) return;
const ws = new WebSocket(CONFIG.wss, uuid);
Cloud.socket = ws;
ws.onopen = () => {
console.log("[WebSocket] З'єднання встановлено");
Cloud.status = 'ok';
ws.send(JSON.stringify({
event: 'connection',
user: {
name: USER.name,
id: USER.id
}
}));
if(Cloud.reconnecting == true) {
Router.navigate(location.pathname);
}
Cloud.reconnecting = true;
Cloud.reconnectAttempts = 0;
clearTimeout(Cloud.reconnectTimeout);
};
ws.onmessage = (e) => {
const data = JSON.parse(e.data);
if (data.event === 'user_connected' && data.user.id !== USER.id) {
console.log(`Новий користувач: ${data.user.name}`);
}
if (data.event === 'message') {
switch (data.type) {
case "apartment":
Territory_card.cloud.update(data);
break;
case "building":
Territory_card.cloud.update(data);
break;
case "stand_locking":
case "stand_unlocking":
case "stand_update":
Stand_card.cloud.update(data);
break;
default:
break;
}
}
};
ws.onclose = () => {
console.warn("[WebSocket] З'єднання розірвано");
Cloud.status = 'err';
if (!Cloud.reconnecting) return; // защита от дублирования
if (Cloud.reconnectAttempts < 5) {
Cloud.reconnectAttempts++;
console.log(`[WebSocket] Спроба перепідключення ${Cloud.reconnectAttempts}/5`);
Cloud.reconnectTimeout = setTimeout(() => {
Cloud.start();
}, 1000);
} else {
Cloud.reconnecting = false;
if (confirm("З'єднання розірвано! Перепідключитись?")) {
Cloud.reconnecting = true;
Cloud.reconnectAttempts = 0;
Cloud.start();
} else {
console.warn("[WebSocket] Перепідключення відмінено користувачем");
}
}
};
ws.onerror = (err) => {
console.error("[WebSocket] Помилка", err);
Cloud.status = 'err';
};
},
}