"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.mqttWorker = void 0;
const mqtt = require('mqtt');
const types_1 = require("../types");
const connectOptions = {
    port: process.env.MQTT_PORT,
    host: process.env.MQTT_HOST,
    clientId: process.env.MQTT_CLIENTID,
    clean: true,
    username: process.env.MQTT_USERNAME,
    password: process.env.MQTT_PASSWORD,
    rejectUnauthorized: false,
    protocol: process.env.MQTT_PROTOCOL,
    //ca: caFile,
};
class mqttWorker {
    constructor() {
        this.roomMac = 'A4:C1:38:71:6B:48';
        this.device = {
            id: 'shellyplusplugs-80646fd1df84',
            online: false,
            state: types_1.Switch.OFF,
            voltage: 0,
            amperes: 0,
        };
        this.energy = {
            by_minute: [0, 0, 0],
            minute_ts: 0,
            total: 0,
        };
        this.roomData = {
            mac: null,
            temperature: null,
            humidity: null,
            battery: null,
            voltage: null,
        };
        this.notifyHandler = null;
        this.client = mqtt.connect(connectOptions);
        const self = this;
        this.client.on('connect', () => {
            console.log(`\x1b[33m➙  \x1b[32mConnected to MQTT server: \x1b[33m` + process.env.MQTT_HOST + ':' + process.env.MQTT_PORT + `\x1b[0m`);
            this.client.subscribe(this.device.id + '/online', function (err) {
                if (!err) {
                    console.log(`\x1b[33m➙  \x1b[32mSubscribed to MQTT channel: \x1b[33m` + self.device.id + `/online\x1b[0m`);
                }
                else {
                    console.error(err);
                }
            });
            this.client.subscribe(this.device.id + '/events/rpc', function (err) {
                if (!err) {
                    console.log(`\x1b[33m➙  \x1b[32mSubscribed to MQTT channel: \x1b[33m` + self.device.id + `/events/rpc\x1b[0m`);
                }
                else {
                    console.error(err);
                }
            });
            this.client.subscribe('homedata/room/' + this.roomMac, function (err) {
                if (!err) {
                    console.log(`\x1b[33m➙  \x1b[32mSubscribed to MQTT channel: \x1b[33mhomedata/room/` + self.roomMac + `/events/rpc\x1b[0m`);
                }
                else {
                    console.error(err);
                }
            });
        });
        this.client.on('error', function (error) {
            console.log("Can't connect" + error);
            process.exit(1);
        });
        this.client.on('message', function (topic, incomingMessage) {
            self.processIncomingMessage(topic, incomingMessage);
        });
        this.client.on('close', function () {
            console.log("Closing MQTT Client");
            self.client.end();
        });
    }
    getRoomTemperature() {
        return this.roomData.temperature;
    }
    getRoomData() {
        return this.roomData;
    }
    getSwitchState() {
        const topic = this.device.id + '/rpc';
        const message = {
            "id": 1,
            "src": this.device.id + "/events",
            "method": "Switch.GetStatus",
            "params": {
                "id": 0
            }
        };
        //console.log("MQTT PUBLISH CALL", topic, JSON.stringify(message))
        this.publish(topic, JSON.stringify(message));
        return this.device.state;
    }
    getCurrentState() {
        return this.device.state;
    }
    getDeviceInfo() {
        return this.device;
    }
    setSwitchState(state) {
        const topic = this.device.id + '/rpc';
        const message = {
            "id": 1,
            "src": this.device.id + "/events",
            "method": "Switch.Set",
            "params": {
                "id": 0,
                "on": state
            }
        };
        console.log("setSwitchState", topic, message);
        this.publish(topic, JSON.stringify(message));
    }
    publish(topic, message, qos = 0, retain = false) {
        if (this.client.connected == true) {
            this.client.publish(topic, message, { retain: retain, qos: qos }, function (error) {
                if (error) {
                    console.error(error);
                }
                console.log("\x1b[35mMQTT PUBLISH: " + topic + "\t" + message + "\t" + qos + "\t" + retain + "\x1b[0m");
            });
        }
        else {
            console.error("CLIENT NOT CONNECTED");
        }
    }
    processIncomingMessage(topic, incomingMessage) {
        const message = incomingMessage.toString();
        if (topic === "homedata/room/" + this.roomMac) {
            try {
                const data = JSON.parse(message);
                this.roomData = data;
            }
            catch (error) {
                console.log(error);
            }
        }
        if (topic === this.device.id + "/online") {
            try {
                this.device.online = JSON.parse(message);
            }
            catch (error) {
                console.log(error);
            }
        }
        if (topic === this.device.id + "/events/rpc") {
            try {
                const data = JSON.parse(message);
                if (data.method === "NotifyStatus") {
                    //console.log("===>", topic, message);
                    //console.log("NOTIFY STATUS PARAMS:", data.params["switch:0"]);
                    const res = data.params["switch:0"];
                    if (res.output) {
                        if (res.output === true) {
                            this.device.state = types_1.Switch.ON;
                        }
                        if (res.output === false) {
                            this.device.state = types_1.Switch.OFF;
                        }
                    }
                    if (res.aenergy) {
                        this.energy = res.aenergy;
                    }
                    if (res.current) {
                        this.device.amperes = res.current;
                    }
                    if (res.voltage) {
                        this.device.voltage = res.voltage;
                    }
                }
                else if (data.result) {
                    const res = data.result;
                    this.device.voltage = res.voltage;
                    this.device.amperes = res.current;
                    if (res.output === true) {
                        this.device.state = types_1.Switch.ON;
                    }
                    if (res.output === false) {
                        this.device.state = types_1.Switch.OFF;
                    }
                }
                else {
                    console.log("UNKNOWN METHOD:", data);
                }
            }
            catch (error) {
                console.log(error);
            }
        }
    }
}
exports.mqttWorker = mqttWorker;
//# sourceMappingURL=mqttWorker.js.map