Project owner: lichnak, PeterBay
Interested:
Related:
Reference: https://Espressif.com
License: Uveďte původ-Zachovejte licenci; CC BY-SA

MQTT klient zapisuje do teplotu na server. Server zpracuje mqtt zprávu zapíše ji mongodb databáze.

JavaScript mqtt2mongodb.js

var mqtt=require('mqtt')  
var mongodb=require('mongodb');  
var mongodbClient=mongodb.MongoClient;  
var mongodbURI='mongodb://username:password@server.mongohq.com:port/database'  
var deviceRoot="demo/device/"  
var collection,client;
mongodbClient.connect(mongodbURI,setupCollection);

function setupCollection(err,db) {  
  if(err) throw err;
  collection=db.collection("test_mqtt");
  client=mqtt.createClient(1883,'localhost')
  client.subscribe(deviceRoot+"+")
  client.on('message', insertEvent);
}

function insertEvent(topic,payload) {  
  var key=topic.replace(deviceRoot,'');
  
collection.update(  
  { _id:key },
  { $push: { events: { event: { value:payload, when:new Date() } } } },
  { upsert:true },
  function(err,docs) {
    if(err) { console.log("Insert fail"); }
  }
  )
}

Configure and add JavaScript mqtt2mongodb.js file to pm2

pm2 start C:\Users\<USER-NAME>\AppData\Roaming\npm\node_modules\mqtt2mongodb.js --save
  • project/nodemcu_mqtt.txt
  • Last modified: 2017/03/11 20:16
  • by licho