yantar/assets/Scripts/stores/ErrorManager.ts
Georgy Shive 3fd54fac56 добавил новый тип данных для работы с новым эндпоинтом
теперь вывожу колличество аварий а не колличество
оборудования в аварийном состоянии
2025-02-24 22:13:09 +07:00

155 lines
6.9 KiB
TypeScript
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.

import { _decorator, Component, Node, AudioSource } from 'cc';
import { EquipmentManager } from './EquipmentManager';
import { apiSensors } from './apiSensors';
const { ccclass, property } = _decorator;
// Интерфейсы для ошибок, полученных через API
interface ApiError {
alarmCode: number;
description: string;
timestamp: string;
}
interface ApiErrorsResponse {
[sensorName: string]: ApiError[];
}
@ccclass('ErrorManager')
export class ErrorManager extends Component {
@property(Node)
public errorListNode: Node = null!; // Узел для отображения списка ошибок
@property(AudioSource)
public alertSound: AudioSource = null!; // Аудиокомпонент для звукового оповещения
// Флаг глобального включения звука
private soundEnabled: boolean = true;
// Массив для хранения уникальных тегов ошибок оборудования (EquipmentManager)
private currentErrors: string[] = [];
// Массив для хранения объектов аварий (тип apiSensors) из EquipmentManager
private errorItems: apiSensors[] = [];
// Массив для хранения тегов, для которых оповещение отключено
private disabledAlerts: string[] = [];
// Хранение ошибок, полученных с API (/api/v2/errors)
private apiErrors: ApiErrorsResponse = {};
static instance: ErrorManager;
onLoad() {
ErrorManager.instance = this;
// Отключение звука при взаимодействии с экраном
this.node.on('touchstart', this.disableSoundAlert, this);
}
start() {
if (EquipmentManager.instance) {
// Подписываемся на событие обновления данных от EquipmentManager
EquipmentManager.instance.node.on('data-updated', this.checkErrors, this);
// Периодическая проверка оборудования каждые 5 секунд
this.schedule(this.checkErrors, 5);
} else {
console.warn("EquipmentManager.instance не найден в ErrorManager.start");
}
// Периодический запрос ошибок с API каждые 10 секунд
this.schedule(() => { this.fetchApiErrors(); }, 10);
}
// Возвращает объединённый список ошибок:
// - equipmentErrors: ошибки по данным оборудования (из EquipmentManager)
// - apiErrors: ошибки, полученные с сервера через API
public getErrorList(): { equipmentErrors: apiSensors[], apiErrors: ApiErrorsResponse } {
return { equipmentErrors: this.errorItems, apiErrors: this.apiErrors };
}
// Проверка списка оборудования на наличие аварий (value === 2)
checkErrors() {
const dataList = EquipmentManager.instance.dataList;
let updated = false;
// 1. Удаляем ошибки, которые более не актуальны
const prevErrors = [...this.currentErrors];
this.currentErrors = this.currentErrors.filter(tag =>
dataList.some(item => item.tag === tag && item.value === 2)
);
if (prevErrors.length !== this.currentErrors.length) {
// Обновляем список объектов аварий аналогичным образом
this.errorItems = this.errorItems.filter(item =>
dataList.some(it => it.tag === item.tag && it.value === 2)
);
updated = true;
}
// 2. Добавляем новые ошибки, которых ещё нет в списке
dataList.forEach(item => {
if (item.value === 2 && this.currentErrors.indexOf(item.tag) === -1) {
this.currentErrors.push(item.tag);
this.errorItems.push(item);
this.addErrorToUI(item);
updated = true;
// Воспроизводим звук, если глобально включён и оповещение для этого тега не отключено
if (this.soundEnabled && this.disabledAlerts.indexOf(item.tag) === -1) {
this.playAlertSound();
}
}
});
// Если произошли изменения, эмитируем событие
if (updated) {
this.node.emit('errors-updated');
}
// Обновляем ошибки с API
this.fetchApiErrors();
}
// Метод для асинхронного запроса ошибок с API
async fetchApiErrors() {
try {
const response = await fetch("http://localhost:3030/api/v2/errors");
if (response.ok) {
const errors = await response.json() as ApiErrorsResponse;
this.apiErrors = errors;
this.node.emit('errors-updated');
} else {
console.error("Ошибка при получении ошибок с API, статус:", response.status);
}
} catch (error) {
console.error("Ошибка запроса ошибок с API:", error);
}
}
// Добавление ошибки в UI (примерная реализация)
addErrorToUI(item: apiSensors) {
console.log(`Добавлена ошибка: ${item.name}`);
// Реализуйте обновление UI, например, создание элементов в errorListNode
}
// Воспроизведение звукового оповещения
playAlertSound() {
if (this.alertSound) {
this.alertSound.play();
}
}
// Глобальное отключение звукового оповещения при взаимодействии с экраном
disableSoundAlert() {
this.soundEnabled = false;
}
// Метод для отключения звукового оповещения для конкретной ошибки по тегу
public disableAlertForError(tag: string): void {
if (this.disabledAlerts.indexOf(tag) === -1) {
this.disabledAlerts.push(tag);
console.log(`Оповещение отключено для ошибки с тегом: ${tag}`);
}
}
// Метод для подтверждения устранения ошибки
confirmError(tag: string) {
this.currentErrors = this.currentErrors.filter(e => e !== tag);
this.errorItems = this.errorItems.filter(item => item.tag !== tag);
console.log(`Ошибка подтверждена и удалена: ${tag}`);
this.node.emit('errors-updated');
}
}