2025-08-14 12:16:32 +07:00
|
|
|
import { useEffect } from "react";
|
|
|
|
|
import { BASE_URL, API_ENDPOINTS } from "@/config/api";
|
|
|
|
|
interface DeviceEventData {
|
|
|
|
|
Message: string;
|
|
|
|
|
DeviceId: string;
|
|
|
|
|
Room: string;
|
|
|
|
|
Timestamp?: string;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
interface UseDeviceEventsOptions {
|
|
|
|
|
onRoomDeviceOnline?: (room: string, deviceId: string) => void;
|
|
|
|
|
onRoomDeviceOffline?: (room: string, deviceId: string) => void;
|
|
|
|
|
onDeviceOnlineInRoom?: (deviceId: string, room: string) => void;
|
|
|
|
|
onDeviceOfflineInRoom?: (deviceId: string, room: string) => void;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function useDeviceEvents(options: UseDeviceEventsOptions) {
|
|
|
|
|
useEffect(() => {
|
2025-08-25 09:40:11 +07:00
|
|
|
const onlineES = new EventSource(API_ENDPOINTS.SSE_EVENTS.DEVICE_ONLINE);
|
|
|
|
|
const offlineES = new EventSource(API_ENDPOINTS.SSE_EVENTS.DEVICE_OFFLINE);
|
2025-08-14 12:16:32 +07:00
|
|
|
|
|
|
|
|
onlineES.addEventListener("online", (event) => {
|
|
|
|
|
try {
|
|
|
|
|
const data: DeviceEventData = JSON.parse(event.data);
|
|
|
|
|
options.onRoomDeviceOnline?.(data.Room, data.DeviceId);
|
|
|
|
|
options.onDeviceOnlineInRoom?.(data.DeviceId, data.Room);
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.error("Error parsing online event:", err);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
offlineES.addEventListener("offline", (event) => {
|
|
|
|
|
try {
|
|
|
|
|
const data: DeviceEventData = JSON.parse(event.data);
|
|
|
|
|
options.onRoomDeviceOffline?.(data.Room, data.DeviceId);
|
|
|
|
|
options.onDeviceOfflineInRoom?.(data.DeviceId, data.Room);
|
|
|
|
|
} catch (err) {
|
|
|
|
|
console.error("Error parsing offline event:", err);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
onlineES.onerror = (err) => {
|
|
|
|
|
console.error("Online SSE connection error:", err);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
offlineES.onerror = (err) => {
|
|
|
|
|
console.error("Offline SSE connection error:", err);
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
|
onlineES.close();
|
|
|
|
|
offlineES.close();
|
|
|
|
|
};
|
|
|
|
|
}, [options]);
|
|
|
|
|
}
|