How to use the connect function from mqtt

Find comprehensive JavaScript mqtt.connect code examples handpicked from public code repositorys.

mqtt.connect is a function in the MQTT.js library for Node.js that creates a client object that can connect to an MQTT broker and send and receive messages using the MQTT protocol.

25
26
27
28
29
30
31
32
33
34
var harmonyDeviceUpdateInterval = 1*60*1000 // 1 minute
var harmonyDeviceUpdateTimers = {}

var mqttClient = config.hasOwnProperty("mqtt_options") ?
    mqtt.connect(config.mqtt_host, config.mqtt_options) :
    mqtt.connect(config.mqtt_host);
var TOPIC_NAMESPACE = config.topic_namespace || "harmony-api";

var enableHTTPserver = config.hasOwnProperty("enableHTTPserver") ?
    config.enableHTTPserver : true;
fork icon118
star icon387
watch icon48

+ 3 other calls in file

138
139
140
141
142
143
144
145
146
147
    device.on('connect', function() {
        ulog('awsiot device connected!');
    });
} 
if (argv.mqtt) {
    var client  = mqtt.connect(argv.mqtt);
    if (!argv.topic) {
        console.log('No MQTT topic prefix specified. Using "teslams/{id}/stream" where {id} is the vehicle id of the car');
        argv.topic = 'teslams';
    }
fork icon112
star icon418
watch icon58

How does mqtt.connect work?

When you use mqtt.connect in your Node.js code, you are creating an MQTT client object that can connect to an MQTT broker and send and receive messages using the MQTT protocol. To use mqtt.connect, you pass an options object as an argument that specifies the connection details for the MQTT broker, such as the hostname, port, and protocol. Once you have created the client object, you can use its methods to connect to the broker, subscribe to topics, publish messages, and handle incoming messages. Here is an example of using mqtt.connect to create an MQTT client object: javascript Copy code {{{{{{{ const mqtt = require('mqtt'); const client = mqtt.connect('mqtt://test.mosquitto.org'); client.on('connect', () => { console.log('Connected to MQTT broker'); client.subscribe('test'); }); client.on('message', (topic, message) => { console.log(`Received message on ${topic}: ${message.toString()}`); }); client.publish('test', 'Hello, world!'); In this example, we are using mqtt.connect to create an MQTT client object that connects to the public Mosquitto MQTT broker. We use the on method to listen for the connect event, which indicates that the client has successfully connected to the broker. We subscribe to the topic 'test', and then use the on method to listen for the message event, which is triggered when a message is received on a subscribed topic. We also use the publish method to send a message to the topic 'test'. Overall, mqtt.connect provides a powerful and flexible way to create MQTT client applications in Node.js, allowing you to build scalable and reliable IoT and messaging systems.

29
30
31
32
33
34
35
36
37

    if (settings.mqtt.clientId) {
        options.clientId = settings.mqtt.clientId
    }

    return mqtt.connect(settings.mqtt.host, options);
}

var mqttClient = getMqttClient();
fork icon62
star icon84
watch icon9

133
134
135
136
137
138
139
140
141
142
}


module.exports = {
  connect (brokerURL, opts) {
    const client = mqtt.connect(brokerURL, opts);
    const asyncClient = new AsyncClient(client);
  
    return asyncClient;
  },
fork icon47
star icon262
watch icon7

+ 3 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const mqtt = require("mqtt");

const client = mqtt.connect("mqtt://test.mosquitto.org");

client.on("connect", () => {
  console.log("Connected to MQTT broker");
  client.subscribe("my/topic");
});

client.on("message", (topic, message) => {
  console.log(`Received message on ${topic}: ${message.toString()}`);
});

client.publish("my/topic", "Hello, world!");

In this example, we are using mqtt.connect to create an MQTT client object that connects to the public Mosquitto MQTT broker. We use the on method to listen for the connect event, which indicates that the client has successfully connected to the broker. We subscribe to the topic 'my/topic', and then use the on method to listen for the message event, which is triggered when a message is received on a subscribed topic. We also use the publish method to send a message to the topic 'my/topic'. Note that mqtt.connect is just one of many functions and utilities available in the MQTT.js library for Node.js, which provides a powerful and flexible way to create MQTT client applications for IoT and messaging systems.

145
146
147
148
149
150
151
152
153
154
}

init() {
  logger.info('Initializing MQTT connection for Plejd addon');

  this.client = mqtt.connect(this.config.mqttBroker, {
    clientId: `hassio-plejd_${Math.random().toString(16).substr(2, 8)}`,
    password: this.config.mqttPassword,
    protocolVersion: 4, // v5 not supported by HassIO Mosquitto
    queueQoSZero: true,
fork icon35
star icon102
watch icon19

+ 3 other calls in file

190
191
192
193
194
195
196
197
198
199
    };
    if (config.user) {
        opts.username = config.user;
        opts.password = config.pass;
    }
    client = mqtt.connect(_url, opts);
} catch (err) {
    adapter.log.error(`Can not connect to mqtt server: ${err}`);
    typeof adapter.terminate === 'function' ? adapter.terminate(11) : process.exit(11);
    return;
fork icon24
star icon44
watch icon14

82
83
84
85
86
87
88
89
90
91

let connected = false;
config
        .getLogger()
        .info(context, 'Connecting to MQTT server %s with options:%s', host, JSON.stringify(this.options));
this.mqttClient = mqtt.connect(host, this.options);
this.mqttClient.on('error', function (error) {
        config.getLogger().error('Error connecting to MQTT server:' + JSON.stringify(error));
});
this.mqttClient.on('message', this.listener);
fork icon40
star icon28
watch icon9

+ 5 other calls in file

25
26
27
28
29
30
31
32
33
34
});

//Start MQTT Broker connection
const mqtt = require('mqtt'); 
console.log("connecting to mqttbroker at "+conf.mqttbroker);
const mqttClient = mqtt.connect(conf.mqttbroker);
//End MQTT Broker connection

mqttClient.on('connect', () => {  
    console.log('connected to mqtt broker...');
fork icon2
star icon2
watch icon5

63
64
65
66
67
68
69
70
71
72
  keepAlive: this.keepalive,
  clean: false,
  rejectUnauthorized: true,
};

this.mqttc = mqtt.connect(this.mqttOptions);

this.logger.info('Binding event callbacks...');
this.mqttc.on('connect', this.onConnect.bind(this));
this.mqttc.on('disconnect', this.onDisconnect.bind(this));
fork icon35
star icon0
watch icon1

109
110
111
112
113
114
115
116
117
118
this.connect = function(host, port, extraParameters) {
        const brokerUrl = url.parse(host || params.brokerHost);
        brokerUrl.port = port || params.brokerPort;
        brokerUrl.protocol = "mqtt://";
        log.info("MQTT", "Connecting to %s%s:%s", brokerUrl.protocol, brokerUrl.href, brokerUrl.port);
        self.mqttClient = mqtt.connect(brokerUrl, extraParameters);

  self.mqttClient.on('connect', function() {
 self.emit('connect');
  });
fork icon21
star icon135
watch icon20

+ 3 other calls in file

2
3
4
5
6
7
8
9
10
11
const coverTopic = 'cover/';
const sensorTopic = 'sensor/';

class MQTTConnector {
    constructor(device, mqttUrl, baseTopic, username, password) {
        const mqttClient = mqtt.connect(mqttUrl, {
            will: {
                topic: `${baseTopic}${coverTopic}${device.id}/connection`,
                payload: 'Offline',
                retain: true
fork icon26
star icon43
watch icon15

52
53
54
55
56
57
58
59
60
61
}
var nodeRI = config.nodeRI || '';
var dKey = config.dKey || '';

var self = this;
var client = mqtt.connect('mqtts://mqtt.sktiot.com', options);
client.on('connect', function () {
  var reqTopic = util.format("/oneM2M/req_msg/+/%s", options.clientId);
  var respTopic = util.format("/oneM2M/resp/%s/+", options.clientId);
  client.subscribe(reqTopic);
fork icon24
star icon31
watch icon23

30
31
32
33
34
35
36
37
38
39


var deviceID = "device10";
var prefix   = "/IoTmanager";
var config   = [];
var client   = mqtt.connect(opt);

// First line
var widget   = "anydata";
var id       = "0"
fork icon31
star icon62
watch icon13

+ 3 other calls in file

102
103
104
105
106
107
108
109
110
```

We can now init our MQTT client.
```javascript
// Connect to MQTT broker
var client = mqtt.connect(url, options);
```

---
fork icon24
star icon41
watch icon6

+ 3 other calls in file

64
65
66
67
68
69
70
71
72
73
        clientId:"raspi",
        username:mqttusername,
        password:mqttpassword,
        clean:true};

var client  = mqtt.connect('mqtt://' + mqtthost, options)

client.on("error",function(error){
        console.log("Can't connect to MQTT server" + error);
        console.log(mqttenabled);
fork icon21
star icon27
watch icon14

8
9
10
11
12
13
14
15
16
 * Copyright (c) 2013, Fabian Affolter <fabian@affolter-engineering.ch>
 * Released under the MIT license. See LICENSE file for details.
 */
var mqtt = require('mqtt');
var mqttbroker = 'localhost:1883';
var mqttclient = mqtt.connect('mqtt://' + mqttbroker);

var socket = require('socket.io');
var io = socket.listen(3000);
fork icon12
star icon25
watch icon5

2
3
4
5
6
7
8
9
10
11
var mqtt = require('mqtt')
var levelStore = require('./')
var manager = levelStore('db')
var client

client = mqtt.connect({
  port: 1883,
  incomingStore: manager.incoming,
  outgoingStore: manager.outgoing
})
fork icon11
star icon23
watch icon7

+ 3 other calls in file

32
33
34
35
36
37
38
39
40
41
42
43
} catch (e) {console.log(e)
    console.log('Could not find ' + config_file + ' or ttn not configured.');
    process.exit(1);
}


var mqtt_client = mqtt.connect('mqtt://localhost');
mqtt_client.on('connect', function () {


    var client  = mqtt.connect('mqtt://nam1.cloud.thethings.network:1883', {'username':config.appID, 'password':config.accessKey})
    client.on('connect', function () {
fork icon8
star icon20
watch icon15

+ 13 other calls in file

303
304
305
306
307
308
309
310
        username: config.mqtt_username,
        password: config.mqtt_password,
    }
}


mqtt_client = mqtt.connect(mqtt_url, mqtt_options);
mqtt_client.on('connect', mqtt_on_connect, mqtt_client);
fork icon8
star icon20
watch icon15

+ 2 other calls in file

299
300
301
302
303
304
305
306
307
308

```javascript
var mqtt = require('mqtt');
var logger = require('./logger.js');

var client  = mqtt.connect('mqtt://broker.hivemq.com');

client.on('connect', function() {
   logger.info("Connected to MQTT");
});
fork icon8
star icon12
watch icon6

+ 3 other calls in file