| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175 |
- 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<ServerConfig> {
- 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<void> {
- 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<ConnectionTestResult> {
- // 连续检测 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<void> {
- await this.storage.removeItem(this.CONFIG_KEY);
- }
- }
- export default ConfigService.getInstance();
|