import { ServerConfig, ConnectionTestResult, ConfigValidation } from '../types'; import { createStorageAdapter } from '../storage'; import { ping } from '../../../API/serverConfigPing'; /** * 默认服务器配置 */ export const DEFAULT_SERVER_CONFIG: ServerConfig = { ip: '127.0.0.1', apiPort: 80, mqttPort: 8083, }; export class ConfigService { private static instance: ConfigService; private storage = createStorageAdapter(); private readonly CONFIG_KEY = 'serverConfig'; private constructor() {} static getInstance(): ConfigService { if (!ConfigService.instance) { ConfigService.instance = new ConfigService(); } return ConfigService.instance; } /** * 获取默认配置 */ getDefaultConfig(): ServerConfig { return DEFAULT_SERVER_CONFIG; } /** * 获取服务器配置 */ async getServerConfig(): Promise { try { const configJson = await this.storage.getItem(this.CONFIG_KEY); if (configJson) { return JSON.parse(configJson); } } catch (error) { console.error('读取配置失败:', error); } return this.getDefaultConfig(); } /** * 保存服务器配置 */ async saveServerConfig(config: ServerConfig): Promise { await this.storage.setItem( this.CONFIG_KEY, JSON.stringify(config) ); } /** * 验证 URL 格式 */ validateUrl(url: string): ConfigValidation { const errors: string[] = []; if (!url || url.trim() === '') { errors.push('地址不能为空'); return { valid: false, errors }; } try { const parsed = new URL(url); // 只允许 http 和 https if (!['http:', 'https:'].includes(parsed.protocol)) { errors.push('只支持 HTTP 和 HTTPS 协议'); } // 检查端口范围 if (parsed.port) { const port = parseInt(parsed.port); if (port < 1 || port > 65535) { errors.push('端口号必须在 1-65535 之间'); } } } catch (e) { errors.push('URL 格式不正确'); } return { valid: errors.length === 0, errors, }; } /** * 验证 MQTT URL 格式 */ validateMqttUrl(url: string): ConfigValidation { const errors: string[] = []; if (!url || url.trim() === '') { errors.push('MQTT 地址不能为空'); return { valid: false, errors }; } try { const parsed = new URL(url); // 只允许 ws 和 wss if (!['ws:', 'wss:'].includes(parsed.protocol)) { errors.push('只支持 WS 和 WSS 协议'); } } catch (e) { errors.push('MQTT URL 格式不正确'); } return { valid: errors.length === 0, errors, }; } /** * 测试连接 - 连续检测 10 次,每隔 1 秒 */ async testConnection( onProgress?: (progress: { current: number; total: number }) => void ): Promise { // 连续检测 10 次 for (let i = 0; i < 10; i++) { // 更新进度 onProgress?.({ current: i + 1, total: 10 }); try { console.log(`检测服务器连接 (${i + 1}/10)...`); const response = await ping(); // 检查响应 if (response.code === '0x000000' && response.data === 'pong') { return { success: true, message: `连接成功 (第 ${i + 1} 次检测)`, }; } else { console.warn(`检测失败 (${i + 1}/10): 服务器响应异常 - ${response.description}`); } } catch (error: any) { console.warn(`检测失败 (${i + 1}/10):`, error.message); } // 等待 1 秒后进行下一次检测(最后一次不需要等待) if (i < 9) { await new Promise(resolve => setTimeout(resolve, 1000)); } } // 所有检测都失败 return { success: false, message: '连接失败,所有 10 次检测均未成功', }; } /** * 清除配置 */ async clearConfig(): Promise { await this.storage.removeItem(this.CONFIG_KEY); } } export default ConfigService.getInstance();