0

所以,我为一个主题制作了一个项目,我有一个文件(weather.js),它发布了两个变量,一个在本地/温度,另一个在本地/时间。我正在制作一个订阅它们并使用值(blinds.js)进行操作的文件,但它混合了它们。我同时发送温度和小时,并在订阅者中将第一个值提供给温度局部变量(在blinds.js 中),然后提供给时间局部变量。我能做些什么?

这是 weather.js 文件。

    //Variables
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://localhost:1884')
var topic_temp = 'local/temperature'
var topic_time = 'local/time'


//Publisher (topic)
client.on('connect',() => {
    setInterval(() => {
        console.log('--------------------');
        //creating random temperatures between -5 and 5
        var temperature = Math.floor((Math.random() * 30) + 5);
        var msg1 = temperature.toString();

        //sending the temperature values
        client.publish(topic_temp,msg1);
        console.log('Temperature is ' + msg1 + 'ºC');

        //Console log sent message
        console.log('Temperature sent!');

        setTimeout(function(){
            //creating random time value 24h format
            var time = Math.floor((Math.random() * 24));
            var msg2 = time.toString();

            //sending time value
            client.publish(topic_time,msg2);
            console.log('Time is ' + msg2 + 'h');

            //Console log sent message
            console.log('Time sent!');
            console.log('--------------------');
        }, 3000);


},15000)
})

这是blinds.js 文件。

//Variables
var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://localhost:1884')

var topic_sub1 = 'local/temperature'
var msg1 = false;
var topic_sub2 = 'local/time'
msg2 = false;

var topic_post = 'appliances/blinds'

var blinds = false;

//Subscribing to the topic_sub1
client.on('connect',() => {
    client.subscribe(topic_sub1)
})

//Receiving temp messages
client.on('message',(topic_sub1,temperature) => {
    if (msg2 == false) {
        msg1 = true;
        temp = temperature.toString();
        console.log('--------------------');
        console.log(temp + 'ºC');
    }
})

//Subscribing to the topic_sub2
client.on('connect',() => {
    client.subscribe(topic_sub2)
})

//Receiving time messages
client.on('message',(topic_sub2,times) => {
    if (msg1) {
        msg2 = true;
        time = times.toString();
        console.log(time + 'h');
        console.log('--------------------');
        blind();
    }
})


//blinds function
function blind()    {
    if (temp > 28 || time < 9) {
        blinds = true;
        console.log('Blinds are CLOSED');
    }else if (temp > 28 || time > 19){
        blinds = true;
        console.log('Blinds are CLOSED');
    }else{
        blinds = false;
        console.log('Blinds are OPEN');
    }

    //sending the temperature values
    client.publish(topic_post,blinds.toString());

    msg2 = false;
    msg1 = false;
}
4

1 回答 1

0

您不能添加多个client.on('message')侦听器,只能有一个。

所以只需if在回调中添加一条语句来检查消息到达的主题。

client.on('message', (topic, message) => {
   if (topic == topic_sub1) {
     //handle temp
   } else if ( topic == topic_sub2) {
     //handle time
   }
})
于 2020-01-25T19:10:59.373 回答