54 lines
1.9 KiB
TypeScript
54 lines
1.9 KiB
TypeScript
import { withSuperAdmin } from "../db";
|
|
import { gpsStorage } from "./storage";
|
|
import { notifyOffline } from "./geozone.service";
|
|
import { eventBus } from "../routes/shared";
|
|
|
|
/**
|
|
* Воркер офлайн-детекта GPS-объектов.
|
|
* Раз в минуту ищет активные онлайн-объекты, от которых не было точек
|
|
* более 15 минут, переводит их в offline и уведомляет подписчиков (on_offline).
|
|
* Обратный переход в online происходит в processPosition при новой точке.
|
|
* Работает независимо от Traccar (PWA-трекинг тоже покрывается).
|
|
*/
|
|
|
|
const TICK_MS = 60_000;
|
|
const OFFLINE_THRESHOLD_MS = 15 * 60_000;
|
|
|
|
let isRunning = false;
|
|
|
|
async function tick(): Promise<void> {
|
|
const cutoff = new Date(Date.now() - OFFLINE_THRESHOLD_MS);
|
|
const staleAssets = await withSuperAdmin(() => gpsStorage.getStaleOnlineAssets(cutoff));
|
|
|
|
for (const asset of staleAssets) {
|
|
try {
|
|
await withSuperAdmin(async () => {
|
|
await gpsStorage.setAssetOnline(asset.id, false);
|
|
await notifyOffline(asset);
|
|
});
|
|
|
|
// SSE — чтобы открытые карты сразу «погасили» маркер
|
|
eventBus.publishEvent({
|
|
type: "gps_asset_offline",
|
|
data: { assetId: asset.id },
|
|
organizationId: asset.organizationId,
|
|
});
|
|
|
|
console.log(`[GPS Worker] Объект ${asset.id} ('${asset.name}', org ${asset.organizationId}) переведён в offline`);
|
|
} catch (err) {
|
|
console.error(`[GPS Worker] Ошибка обработки объекта ${asset.id}:`, err);
|
|
}
|
|
}
|
|
}
|
|
|
|
export function startGpsWorker(): void {
|
|
if (isRunning) return;
|
|
isRunning = true;
|
|
|
|
setInterval(() => {
|
|
tick().catch((err) => console.error("[GPS Worker] Tick error:", err));
|
|
}, TICK_MS);
|
|
|
|
console.log("[GPS Worker] started");
|
|
}
|