Hi,
I'm working on a project where I'm trying to embed the MQTT function within a number of custom nodes and while I've managed to get certain aspects working I've hit a brick wall. I came across this thread ( Examples that publish/subscribe MQTT?) where it seems like the OP may have solved the problem but there wasn't any detailed explanation.
So, I'm trying to incorporate an MQTT client in a custom node that talks to the broker, which then passes the message on to an ESP8266 controller. So far have I have achieved the following:
- I can send messages to the ESP8266 via the broker without a problem & it intreprets the messages
- However, I cannot receive the messages from the ESP via the broker
I'm attaching my code and would appreciate your opinion and any comments on what I'm doing wrong and how I might make this work.
Steve
const mqtt = require('mqtt');
module.exports = function (RED)
{
function MQTTwithinNode(config)
{
RED.nodes.createNode(this, config);
let node = this;
let options = {
username: config.username,
password: config.password,
connectTimeout: 7 * 1000
};
let my_client = mqtt.connect(`mqtt://${config.host}:${config.port}`, options);
node.on('input', function(msg) {
var topic1="DevCtrl/LED/SetFrequency";
var topic2="DevCtrl/LED/SetDutyCycle";
var mqtt_msg = "This is a buffer for mqtt messages";
if (msg.topic == "frequency") {
mqtt_msg = String(msg.payload);
my_client.publish(topic1,mqtt_msg,pub_options);
} else if (msg.topic == "dutycycle") {
mqtt_msg = String(msg.payload);
my_client.publish(topic2,mqtt_msg,pub_options);
}
node.send(msg);
});
var pub_options = {
retain:true,
qos:1
};
my_client.on('connect', function (connack) {
var topic = "DevCtrl/LED/#";
my_client.subscribe(topic,{qos:1});
});
my_client.on('message',function(topic, message, packet) {
console.log("message is "+ message);
console.log("topic is "+ topic);
msg.payload = "topic is: " + topic + " message is: " + message;
node.send(msg);
});
}
RED.nodes.registerType("mqtt-innode", MQTTwithinNode);
}