Skip to content

Instantly share code, notes, and snippets.

@cbh6
Created April 27, 2018 10:55
Show Gist options
  • Save cbh6/7a2443bf99c4e649df41b6850a2ae71f to your computer and use it in GitHub Desktop.
Save cbh6/7a2443bf99c4e649df41b6850a2ae71f to your computer and use it in GitHub Desktop.
const mqtt = require('mqtt');
class MqttHandler {
constructor() {
this.mqttClient = null;
this.host = 'YOUR_HOST';
this.username = 'YOUR_USER'; // mqtt credentials if these are needed to connect
this.password = 'YOUR_PASSWORD';
}
connect() {
// Connect mqtt with credentials (in case of needed, otherwise we can omit 2nd param)
this.mqttClient = mqtt.connect(this.host, { username: this.username, password: this.password });
// Mqtt error calback
this.mqttClient.on('error', (err) => {
console.log(err);
this.mqttClient.end();
});
// Connection callback
this.mqttClient.on('connect', () => {
console.log(`mqtt client connected`);
});
// mqtt subscriptions
this.mqttClient.subscribe('mytopic', {qos: 0});
// When a message arrives, console.log it
this.mqttClient.on('message', function (topic, message) {
console.log(message.toString());
});
this.mqttClient.on('close', () => {
console.log(`mqtt client disconnected`);
});
}
// Sends a mqtt message to topic: mytopic
sendMessage(message) {
this.mqttClient.publish('mytopic', message);
}
}
module.exports = MqttHandler;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment