だから、私は主題のためのプロジェクトを作っています.1つはローカル/温度で、もう1つはローカル/時間で、2つの変数を発行するファイル(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)
})
これがブラインドの 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;
}