import mqtt from 'mqtt'; class MqttClient { constructor(topics, onMessageCallback) { // 固定参数 this.MQTT_MQTTIP = 'wss://ws.emqx.sysuimars.cn/mqtt'; this.MQTT_USERNAME = 'admin'; this.MQTT_PASSWORD = 'admin'; this.topics = topics; // 订阅的主题数组 this.onMessageCallback = onMessageCallback; // 接收数据的回调函数 this.client = null; } connect() { const options = { connectTimeout: 40000, clientId: `clientid-${this.generateClientId()}`, // 生成唯一的客户端 ID username: this.MQTT_USERNAME, password: this.MQTT_PASSWORD, clean: false }; // 连接 MQTT this.client = mqtt.connect(this.MQTT_MQTTIP, options); // 监听连接成功事件 this.client.on('connect', () => { console.log('连接成功'); this.subscribeToTopics(); // 订阅主题 }); // 监听消息事件 this.client.on('message', (topic, message) => { this.onMessageCallback(topic, message.toString()); // 调用回调函数处理消息 }); // 监听重连事件 this.client.on('reconnect', (error) => { console.log('正在重连...', error); }); // 监听错误事件 this.client.on('error', (error) => { console.log('连接失败...', error); }); } // 订阅主题 subscribeToTopics() { if (this.topics && this.topics.length > 0) { this.topics.forEach((topic) => { this.client.subscribe(topic, (err) => { if (!err) { console.log(`订阅成功: ${topic}`); } else { console.log(`订阅失败: ${topic}`, err); } }); }); } else { console.log('未提供订阅主题'); } } // 生成唯一的客户端 ID generateClientId() { const S4 = () => (((1 + Math.random()) * 0x10000) | 0).toString(32).substring(1); return `${S4()}${S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`; } } export default MqttClient;