Can't connect to MQTT client, using client as global variable [Javascript, MQTT.js]

302 Views Asked by At

I'm working with MQTT.js and Mosquitto as my broker.

I'm trying to connect to my broker on the POST method and it works, storing the "Client" on the variable.

The problem is that the code doesn't work on the GET where my client isn't connecting and therefore, I can't subscribe or message to my topics.

I don't know what is the reason for that, but I solved it when I do de client connection inside the GET, but in this case, I don't want to do the connection inside the GET.

That's because the POST response is given when I login in the platform, and if I do the client connection on the GET that is for see the variables, always that I recharge the page It will connect again and then it will subscribe to the same topic, and after that when I send one message, if is subscribed three times to the same topic, it will Post 3 times.

PD: When I print the client inside the GET, It prints the same value that is assigned in the POST

const express = require("express");
const router = express.Router();
const request = require("request");

let mqtt = require('mqtt');
require("../requestMethods/get.js")();
require("../requestMethods/post.js")();

let client;
let options;

const postMqttData = async (string, body) => {
    const url = `http://localhost:8000/${string}`;
    const data = await postData(url, body)
    console.log(data)


}
const getToken = async (string) => {
    const url = `http://localhost:3000/api/tokenuser/${string}`
    const data = await requestData(url)
    const token = data;
    //console.log(token)
    return token;

}
router.post("/apiClientBroker", (req, res,next) => {
    let {user} = req.body;
    console.log(user)
    getToken(user).then(meta => {
        const { value } = meta.token[0];
        options = { username: user, password: value, clean: true, keepAlive: 60 }
        client = mqtt.connect('mqtt://localhost', options);
        //console.log(client)
       })

})

router.get("/:user/:project",(req, res, next) => {
  //  clientBrokerResponse(req.client)
 // console.log(client)
    const { user } = req.params;
    const { project } = req.params;
    const uri = hostURL + "/variables/" + user + "/" + project;
    
    request.get(uri, (err, resp, body) => {
        //body = JSON.parse(body);

        if (err || resp.status == 500) {
            res.status(500).send({ ERROR: "Error searching" });
        } else {
            if (body.length) {
                const json= JSON.parse(body);
                console.log(client)
            client.on('connect', function () {
              
                for(let i= 0; i<json.length;i++){
                    const {deviceN}= json[i];
                    const {variableN}= json[i];
                    const {variableT}=json[i];
                    const topico = `${user}/${project}/${deviceN}/${variableN}`;
                    if(variableT==='Independiente'){
                       
                       
                            
                            client.subscribe(topico, function (err) {
                                console.log(`suscrito a ${topico}`)
                                if (err) {
                                    console.log("error en la subscripcion")
                                }
                            })
                            
                    
                       
                    }

                }
            })
                client.on('message', function (topic, message) {


                    // message is Buffer
                 
                        json1 = JSON.parse(message.toString()); //de esta manera se convierte el mensaje recibido en un json
                        console.log(json1);
                      //  if (json1.token === value) {
                            json2 = { 'value': json1.value }
                            postMqttData(`${topic}/${json1.token}`, json2)
                        
                            
        
                      //  } else {
                     //       console.log("Se está enviando a otro usuario el dato")
                      //  }
                    
        
                })
        

                res.status(resp.statusCode).send(body);
            } else {
                res
                    .status(404)
                    .send({ message: "Variables not found for this project" });
            }
        }
    });
});
0

There are 0 best solutions below