let mqtt = require('mqtt')
let ex = require('util')

let pandaxServer = {
    "protocol": "tcp",
    "server": "175.27.166.25:1888",
    "username": "ZWMyYTFiZDEtNWYzMS0zMWRiLThmYzItZmY0NDhmNGM1NzIz",
    "password": "",
    "client_id": ex.uuid(),
}

let publicServer = {
    "protocol": "tcp",
    "server": "175.27.166.25:1883",
    "username": "",
    "password": "",
    "client_id": ex.uuid(),
}

mqtt.connect("pandax", pandaxServer);
mqtt.connect("public", publicServer);

function main() {
    console.log("mqtt client start")
    mqtt.subscribe("public", "$dp", 2, function () {
        let topic = args[0];
        let msg = args[1].slice(3).toObject();
        // {"1522031989":{"L1_QJ_1":{"2025-09-25T02:23:02.000Z":"0.887,-1.844,87.954,2.046,295.685"},"L1_JS_1":{"2025-09-25T02:23:02.000Z":"-3.450,-5.200,0.640"}}}
        
        let deviceId = Object.keys(msg)[0];
        let data = msg[deviceId]?.L1_QJ_1;
        if (!data) {
            return;
        }

        let time = Object.keys(data)[0];
        let value = data[time];
        console.log("deviceId: " + deviceId + " time: " + time + " value: " + value);
        let values = value.split(',');
        console.log("values: " + values);
        
        deviceId = "QJ"+deviceId
        data = {}
        data[deviceId] = {
            X: parseFloat(values[0]),
            Y: parseFloat(values[1]),
            Z: parseFloat(values[2]),
            angle: parseFloat(values[3]),
            AZI: parseFloat(values[4]),
        }

        console.log("data: " + JSON.stringify(data));

        let mqtt = require('mqtt')
        mqtt.publish("pandax", "v1/gateway/telemetry", data, 2);



        console.log("* topic: " + topic + "\nmsg: " + JSON.stringify(msg));
        // mqtt.publish("test", "/user/test", "hello world", 2);
    });

    console.log("mqtt client subscribe $dp")
    // console.input()
}