yantar/assets/Scripts/stores/SensorDetailStore.ts

65 lines
2.6 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 } from 'cc';
import { SensorDescription } from './SensorDescriptionField';
const { ccclass } = _decorator;
@ccclass('SensorDetailStore')
export class SensorDetailStore extends Component {
private static _instance: SensorDetailStore | null = null;
private currentSensorName: string = "";
private currentDetails: SensorDescription = null!;
public static getInstance(): SensorDetailStore {
if (!SensorDetailStore._instance) {
SensorDetailStore._instance = new SensorDetailStore();
}
return SensorDetailStore._instance;
}
onLoad() {
SensorDetailStore._instance = this;
}
/**
* Запрашивает детали датчика по имени и преобразует ответ к нужной структуре.
* @param sensorName Имя датчика, для которого требуется получить детали.
*/
public async fetchSensorDetails(sensorName: string): Promise<SensorDescription | null> {
if (!sensorName) return null;
this.currentSensorName = sensorName;
try {
const response = await fetch("http://localhost:3030/api/v2/sensor-details", {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sensorName: sensorName })
});
if (!response.ok) {
console.error(`[SensorDetailStore] Ошибка ответа от сервера: ${response.status}`);
return null;
}
const json = await response.json();
// Ожидаем, что сервер вернет объект с полями: id, sensor_id, name, description (JSON-объект с fields)
if (json && json.description && json.description.fields) {
const result: SensorDescription = {
sensorName: json.name,
fields: json.description.fields
};
this.currentDetails = result;
return result;
} else {
console.error("[SensorDetailStore] Неверный формат данных:", json);
return null;
}
} catch (err) {
console.error('[SensorDetailStore] Не удалось загрузить данные датчика:', err);
return null;
}
}
public getCurrentDetails(): SensorDescription | null {
return this.currentDetails;
}
}