在文件之间共享mqtt客户端对象 [英] share mqtt client object between files

查看:190
本文介绍了在文件之间共享mqtt客户端对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过以下方式连接到MQTT:

I connect to MQTT this way:

//mqtt.js

const mqtt = require('mqtt');

var options = {
    //needed options
};

var client = mqtt.connect('mqtt://someURL', options);

client.on('connect', () => {
    console.log('Connected to MQTT server');
});

我想以这种方式导出 client 对象:

I want to export the client object this way:

//mqtt.js

module.exports = client;

这样我就可以将其导入其他文件并以这种方式使用它:

So that I can import it in other files and make use of it this way:

//anotherFile.js    

const client = require('./mqtt');
client.publish(...)

但是,我们都知道这将行不通!我该如何实现?

However, we all know that this will not work! How can I achieve this ?

更新

我尝试了 promise (诺言),并且得到了一个非常奇怪的行为.当我在以下文件的同一文件(mqtt.js)中使用promise时,一切正常:

I tried promise and get a very strange behavior. When I use the promise in the same file (mqtt.js) like the code below, everything is OK:

//mqtt.js
const mqtt = require('mqtt');

var mqttPromise = new Promise(function (resolve, reject) {

    var options = {
     //needed options
    };
    var client = mqtt.connect('mqtt://someURL', options);

    client.on('connect', () => {
        client.subscribe('#', (err) => {
            if (!err) {
                console.log('Connected to MQTT server');
                resolve(client);
            } else {
                console.log('Error: ' + err);
                reject(err);
            }
        });
    });
});


mqttPromise.then(function (client) {
    //do sth with client
}, function (err) {
    console.log('Error: ' + err);
});

但是当我导出promise并在另一个文件中使用它时,就像这样:

But when I export the promise and use it in another file, like this:

//mqtt.js

//same code to create the promise    
module.exports = mqttPromise;

//anotherFile.js

const mqttPromise = require('./mqtt');

mqttPromise.then(function (client) {
     //do sth with client
 }, function (err) {
    console.log('Error: ' + err);
 });

我收到此错误:

TypeError:mqttPromise.那不是函数

TypeError: mqttPromise.then is not a function

推荐答案

您可能可以实现创建2个文件的目标,一个文件用于处理mqtt方法,另一个文件用于管理连接对象.

You can probably achieve your goal creating 2 files, one for handling mqtt methods and another to manage the connection object.

这是mqtt处理程序的文件:

Here's the file for the mqtt handler:

    //mqttHandler.js       

    const mqtt = require('mqtt');

    class MqttHandler {
      constructor() {
        this.mqttClient = null;
        this.host = 'YOUR_HOST';
        this.username = 'YOUR_USER'; 
        this.password = 'YOUR_PASSWORD';
      }

      connect() {

        this.mqttClient = mqtt.connect(this.host, {port: 1883});
        // 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`);
        });


         this.mqttClient.on('close', () => {
           console.log(`mqtt client disconnected`);
         });
      }

    //   // Sends a mqtt message to topic: mytopic
      sendMessage(message, topic) {

            this.mqttClient.publish(topic, JSON.stringify(message));

      }
    }

    module.exports = MqttHandler;

现在,让我们使用导出的模块在另一个文件上创建mqtt客户端连接:

Now lets use the exported module to create a mqtt client connection on another file:

    //mqttClient.js

    var mqttHandler = require('./mqttHandler');

    var mqttClient = new mqttHandler();

    mqttClient.connect();

    module.exports = mqttClient;

使用此导出的模块,您现在可以调用客户端连接对象,并使用在另一个文件中的mqttHandler.js文件中创建的方法:

With this exported module you can now call your client connection object and use the methods created in the mqttHandler.js file in another file :

    //main.js
    var mqttClient = require('./mqttClient');

    mqttClient.sendMessage('<your_topic>','<message>');

尽管可能有更好的方法来执行任务,但是这个方法对我来说效果很好...

Although there may be a better method to perform your task, this one worked pretty well for me...

希望有帮助!

这篇关于在文件之间共享mqtt客户端对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆