// src/mqttClient.js
import mqtt from 'mqtt/dist/mqtt.min';

let client;

const connectMQTT = (brokerUrl = 'ws://broker.emqx.io:8083/mqtt', options = {}) => {
  if (!client || client.disconnected) {
    client = mqtt.connect(brokerUrl, options);

    client.on('connect', () => {
      console.log('Connected to MQTT broker');
      client.subscribe('/mytest/abc', (err) => {
        if (err) {
          console.error('Failed to subscribe to topic:', err);
        } else {
          console.log('Subscribed to topic: /mytest/abc');
        }
      });
    });

    client.on('error', (err) => {
      console.error('MQTT connection error:', err);
      client.end();
    });

    client.on('close', () => {
      console.log('MQTT connection closed');
    });
  } else {
    console.log('MQTT client is already connected');
  }
};

// 导出客户端和连接函数
export { client, connectMQTT };
