不過, 先做個簡單測試, 睇下 work 唔 work 先.
1) mosquitto - 可以用 chrome apps: MQTTLENS, 又或者 mqtt_spy
2) mongoDB - 可以起左 server 後 執行 mongo.exe 直接連上 MongoDB
3) 裝先行到 node 或者 npm 都應該得掛.
再唔係可以試下呢個 script, 用 node example.js 去行, 佢會起左個 web server.
用 browser 開 localhost:3000 應該見到句 Hello Work 就係得了.
const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World\n'); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });4) 最後, 更係要試下 3 件野係咪夾得埋黎用, 如果唔係, 裝黎托咩.
可以做個簡單既測試:
- 用 nodejs 起個 process
- 睇住 mosquitto 既 message
- 收到想要既 message 就儲入 MongoDB
是旦搵個 folder, 安裝 nodejs 定所需既野. 今次只係要 mqtt 同 mongdb
比如開個新 folder, E:\Node\Tester, 然後走去 E:\Node\Tester 行呢句野:
npm install mqtt mongdb佢就會裝左 mqtt 同 mongdb 既 package 去 E:\Node\Tester\node_modules
之後就開個 text file 叫 example.js copy 呢堆野入去:
consoleLog('MQTT MongoDB Tester Started'); var mqtt=require('mqtt'); var mongodb=require('mongodb'); var mongodbClient=mongodb.MongoClient; var mongodbURI='mongodb://localhost/data'; var deviceRoot='mqtt/demo/'; var collection,client; mongodbClient.connect(mongodbURI, setupCollection); var connInfo = { host: 'localhost', port: 1883, clientId: 'guest169' } function strNow() { return (new Date()).toISOString().replace('T',' ').replace('Z',''); } function consoleLog(msg) { console.log(strNow() + ' : ' + msg); } function setupCollection(err,db) { if(err) throw err; collection=db.collection('mqtt_demo'); client=mqtt.connect(connInfo) client.subscribe(deviceRoot + '#') client.on('message', insertEvent); } function insertEvent(topic,payload) { var now = strNow(); var key=topic.replace(deviceRoot,''); console.log('%s : [%s] - %s', now, key, payload); collection.update( { _id:key }, { $push: { events: { event: { value:payload, when:new Date() } } } }, { upsert:true }, function(err,docs) { if(err) { consoleLog('#### Insert fail'); } } ) }
然後行 node example.js 就可以了.
之後, 用 mqtt_spy 或者 MQTTLENS 去 publish, 個 topic 如果開頭係 "mqtt/demo/" 就會接收, 然後放入 MongoDB. 只要走去 MongoDB, use data, 再 show collections, 應該會見到 mqtt_demo 既, 然後再db.mqtt_demo.find(), 就會見到收左乜野了.