From 1e720a1d2edb8c6c2aaa86f846d536e09e0158a2 Mon Sep 17 00:00:00 2001 From: Georgy Shive Date: Sun, 11 May 2025 14:53:35 +0700 Subject: [PATCH] =?UTF-8?q?=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB=20?= =?UTF-8?q?=D0=BE=D0=B3=D1=80=D0=B0=D0=BD=D0=B8=D1=87=D0=B5=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=20=D0=BD=D0=B0=20=D0=B3=D0=B5=D0=BD=D0=B5=D1=80=D0=B0?= =?UTF-8?q?=D1=86=D0=B8=D1=8E=20=D0=BE=D1=88=D0=B8=D0=B1=D0=BE=D0=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- index.ts | 3 ++- src/periodicUpdates.ts | 26 +++++++++++++------------- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/index.ts b/index.ts index 10927c5..d288e88 100644 --- a/index.ts +++ b/index.ts @@ -40,4 +40,5 @@ const app = new Elysia() console.log(`Server running on http://localhost:3030`); // Импортируем periodicUpdates как побочный эффект: -import './src/syncSensors'; \ No newline at end of file +import './src/syncSensors'; +import './src/periodicUpdates' \ No newline at end of file diff --git a/src/periodicUpdates.ts b/src/periodicUpdates.ts index 6ce3301..1a165a4 100644 --- a/src/periodicUpdates.ts +++ b/src/periodicUpdates.ts @@ -1,11 +1,20 @@ import db from './db/database'; import type { SensorCount, SensorRow } from './interfaces/SensorRow'; - const updateInterval = 30000; // 30 секунд +const MAX_ERRORS = 160; // лимит аварий // Периодическое обновление аварийного состояния: -setInterval(() => { +const errorInterval = setInterval(() => { + // Проверяем общий количество записей об ошибках + const totalErrors = (db.prepare("SELECT COUNT(*) as count FROM errors").get() as { count: number }).count; + if (totalErrors >= MAX_ERRORS) { + console.log(`Достигнут максимум ошибок (${MAX_ERRORS}). Генерация аварий остановлена.`); + clearInterval(errorInterval); + return; + } + + // Проверяем текущее количество датчиков в аварийном состоянии const currentCount = (db.prepare("SELECT COUNT(*) as count FROM sensors WHERE value = 2").get() as SensorCount).count; if (currentCount >= 3) { console.log("Максимальное количество датчиков с аварийным состоянием уже достигнуто."); @@ -83,30 +92,21 @@ setInterval(() => { console.log(`Периодическое обновление: для ${countToUpdate} выключенных датчика(ов) установлено состояние 'on' (value = 1).`); }, updateInterval); - - +// Обновление sensor_details — без изменений setInterval(() => { - // Получаем все записи sensor_details const sensorDetails = db.prepare("SELECT id, description FROM sensor_details").all() as { id: number; description: string }[]; sensorDetails.forEach(detail => { try { - // Парсим JSON-описание const parsed = JSON.parse(detail.description); - - // Если есть массив полей, обновляем каждое поле новым значением if (parsed.fields && Array.isArray(parsed.fields)) { parsed.fields = parsed.fields.map((field: any) => { - // Генерируем новое случайное значение (например, от 0 до 10000) const newValue = Math.floor(Math.random() * 10001); console.log(`Обновляем "${field.name}": старое значение = ${field.value}, новое значение = ${newValue}`); return { ...field, value: newValue }; }); } - - // Преобразуем обновлённый объект обратно в строку const newDescription = JSON.stringify(parsed); - // Обновляем запись в базе данных db.prepare("UPDATE sensor_details SET description = ? WHERE id = ?").run(newDescription, detail.id); } catch (error) { console.error(`Ошибка при обновлении описания для sensor_detail id=${detail.id}:`, error); @@ -114,4 +114,4 @@ setInterval(() => { }); console.log("Обновление описаний сенсоров выполнено."); -}, 5000); \ No newline at end of file +}, 5000);