0
votes

I have a remote device which is nothing but a sensor. It will continuously give me some numbers. Actually I am receiving those numbers in my node.js server, I do not want to publish those data. I want to subscribe my client and want to print my topic and message after client subscribed. Here is my Node.js server and mqtt in c. Run both files using node app.js and gcc main.c after ./a.out.
How can I resolve this problem?
Files are shown below:

app.js

'use strict';

//dependencies
var express          = require('express'),
    passport         = require('passport'),
    strategy         = require('passport-local').Strategy,
    mongoose         = require('mongoose'),
    mongodb          = require('mongodb'),
    bodyParser       = require('body-parser'),
    path             = require('path'),
    acl              = require('acl'),
    mosca            = require('mosca');   

exports.init = function(pp) {
    passport = pp;
    app = pp;
    return exports;
};

exports.root = function(req, res) {
    // Running
    res.send("Running");
};

//create express app
var app         = express();
    app.appname ="watersensor_DB";

//config mongoose
  mongoose.Promise = global.Promise;
  app.db = mongoose.createConnection('localhost/'+app.appname);
  app.db.on('error', console.error.bind(console, 'mongoose connection error: '));
  app.db.once('open', function () {
    // Store All Data
  });

//config mongodb
  mongodb.connect("mongodb://localhost/"+app.appname, function(error, mdb) {
  app.acl=new acl(new acl.mongodbBackend(mdb, app.appname));
  });

//config data models
  require('./models')(app, mongoose);

//Serve Frontend
  app.use(express.static(path.join(__dirname, '/public/')));

//config Routes
  var router = express.Router();
  require('./routes')(app, router, passport);

//config express
  app.set('secret','thisshouldnotbeinplaintext');
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(bodyParser.json());
  app.use(passport.initialize());
  app.use(router);


//config mosca
var ascoltatore = {
  //using ascoltatore 
  type: 'mongo',
  url: 'mongodb://localhost:27017/mqtt',
  pubsubCollection: 'ascoltatori',
  mongo: {}
};

var settings = {
  port: 1883,
  backend: ascoltatore,
  persistence: {
    factory: mosca.persistence.Mongo,
    url: 'mongodb://localhost:27017/mqtt'
  }
};

var server = new mosca.Server(settings);

server.on('clientConnected', function(client) {
    console.log('client connected', client.id);
});

// fired when a message is received 
server.on('published', function(packet, client) {
  console.log('Published', packet.payload); 
});


server.on('ready', setup);

// fired when the mqtt server is ready 
function setup() {
  console.log('Mosca server is up and running');
}

//Port Listening
  app.listen(7000, function(){
    //Running
    console.log("Node.js Server Is Running On localhost:7000");
  });

main.c

#include <stdio.h>

main()
{
    char buf[1024];
    int i;  
    //mosquitto_sub -t 'test/topic' -v
    //mosqui<to_pub -t 'test/topic' -m 'hello'
    for(i=0; ;i++) {
        //sprintf(buf, "mosquitto_pub -h 192.168.43.82 -p 1883 -t 'test' -m '%d'",i);
        sprintf(buf, "mosquitto_pub -t 'test' -m '%d'",i);
        printf("%s\n",buf);
        system(buf);
        sleep(1);
    }
}
1
It really isn't clear what you are asking here. Please try and re-work the question to give a clearer description of what you are trying to achievehardillb

1 Answers

-1
votes

What you mean is that the node.js server get the data published from your remote device? After it, server store the data in MongoDB???

For this meaning, server do not need to subscribe the client. It can get the data from the below code.

server.on('published', function(packet, client) {
    console.log('Published : ', packet.topic + " --- " + packet.payload);

    var MongoClient = require('mongodb').MongoClient;
    var url = "mongodb://localhost:27017/mydb";

    MongoClient.connect(url, function(err, db) {
      if (err) throw err;

      var stringBuf = packet.payload.toString('utf-8');
      var myobj3 = JSON.parse(stringBuf);

      db.collection("customers").insertOne(myobj3, function(err, res) {
        if (err) throw err;
        console.log("1 record inserted");
        db.close();
      });
    });
});