import { processDeviceData, customerDeviceData} from "../biz/mqttClient";
import { systemConfig } from "../config/serverConfig";

const mqtt = require('mqtt');

// ==================== 启动MQTT客户端并订阅 ====================
export async function startMqttClient() {
    // 在连接选项中添加用户名和密码
    const mqttOptions = {
        username: systemConfig.mqttsrv.username,
        password: systemConfig.mqttsrv.password,
        // 可选：如果遇到连接问题，可以添加以下参数
        // clientId: 'node_subscriber_' + Math.random().toString(16).substring(2, 8),
        // clean: true,
        // connectTimeout: 4000,
        // reconnectPeriod: 1000,
    };
    // 连接MQTT Broker
    const client = mqtt.connect(`mqtt://${systemConfig.mqttsrv.host}:${systemConfig.mqttsrv.port}`, mqttOptions);
    
    client.on('connect', () => {
        console.log('MQTT客户端已连接，正在订阅主题...');
        // 订阅网关的上行主题
        client.subscribe(systemConfig.mqttsrv.topic_env, (err) => {
            if (err) {
                console.error('环境订阅失败:', err);
            } else {
                console.log(`成功订阅环境主题: ${systemConfig.mqttsrv.topic_env}`);
                console.log('等待环境设备数据...');
            }
        });
        client.subscribe(systemConfig.mqttsrv.topic_crowd, (err) => {
            if (err) {
                console.error('客流订阅失败:', err);
            } else {
                console.log(`成功订阅客流主题: ${systemConfig.mqttsrv.topic_crowd}`);
                console.log('等待客流设备数据...');
            }
        });
    });

    // 当收到消息时触发处理
    client.on('message', (topic, message) => {
        // 只处理配置的上行主题
        if (topic === systemConfig.mqttsrv.topic_env) {
            processDeviceData(message);
        }
        if (topic === systemConfig.mqttsrv.topic_crowd) {
            customerDeviceData(message);
        }
    });

    client.on('error', (err) => {
        console.error('MQTT连接错误:', err);
    });
}