Feynman137
Feynman137

Reputation: 181

Node.js mqtt ssl script

I made a script to connect my linux CentOS VM as a client to my mosquitto MQTT broker. Just trying to connect at the moment using SSL. To publish and subscribe the broker requires username and password. But when I run the script using:

node websitemqttclient.js

I am just getting the message below, and the cursor sits in a blank space for approx 1.5 minutes before execution is finished and a new command can be entered. I see the depreciation notice but it doesn't appear to be a problem yet. Also I have verified the 8883 port is open on the broker and its set-up so I believe the issue is with the client and its code.

user [bin]# node websitemqttclient.js
(node:30037) [DEP0123] DeprecationWarning: Setting the TLS ServerName to an IP address is not permitted by RFC 6066. This will be ignored in a future version.
connected  false

Is my script actually connecting to my broker or is it just sitting in the loop without connecting to the broker?

Main Code:

/////////////////////////////////////////////////////////////////////////////////////////
//setup
var mqtt    = require('mqtt'); //for client use
const fs = require('fs');
var count =0; //connected to an end script function
var caFile = fs.readFileSync("/pathway/bin/ca.crt");

var options={
host:'brokerip',
port:8883,
clientId:"yo",
username:"user",
password:"password",
protocol: 'mqtts',
clean:true,
rejectUnauthorized: false,
retain:false, 
ca:caFile 
}

var client  = mqtt.connect(options);
/////////////////////////////////////////////////////////////////////////////////////////
//connection dialog

//handle incoming messages
client.on('message',function(topic, message, packet){
    console.log("message is "+ message);
    console.log("topic is "+ topic);
});
client.on("connect",function(){ 
console.log("connected  "+ client.connected);
})
//handle errors
client.on("error",function(error){
console.log("Can't connect" + error);
process.exit(1)});
/////////////////////////////////////////////////////////////////////////////////////////



/////////////////////////////////////////////////////////////////////////////////////////

count+=1;  //quit script after the execution of two loops
if (count==2) //ens script
    clearTimeout(timer_id); //stop timer
    client.end();

Upvotes: 1

Views: 396

Answers (1)

hardillb
hardillb

Reputation: 59751

client.connected won't return true until after the on connect event handler has been completed.

Add a call to client.subscribe() to the on connect event handler so you actually have some messages to trigger the on message event handler

Upvotes: 1

Related Questions