-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
52 lines (42 loc) · 1.26 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
var mqtt = require('mqtt');
var express = require('express');
var app = express();
var appWs = require('express-ws')(app);
/*
IMPORTANT: Fill in your environment config
*/
var mqttConfig = {
server: '', // typically http://localhost:1883
username: '', // user
password: '' // password
}
var channel = 'arduino/arduino-uno/stream';
/* MQQT client */
var mqttClient = mqtt.connect(mqttConfig.server, {
username: mqttConfig.username,
password: mqttConfig.password,
});
// 1) connect and subscribe to stream topic
mqttClient.on('connect', function () {
mqttClient.subscribe(channel);
});
// 2) when receive a message from the broker, just print it
mqttClient.on('message', function (topic, message) {
console.log(message.toString());
});
/* HTTP server */
app.listen(8001, function () {
console.log('Server listening on port 8001...');
});
app.get('/', function(request, response){
response.sendFile(__dirname + '/index.html');
});
app.use('/js', express.static('js'));
app.use('/css', express.static('css'));
/* Websocket server using current HTTP server */
app.ws('/', function(ws, req) {
// when message received via Websocket, publish it to the MQTT broker
ws.on('message', function(message) {
mqttClient.publish(channel, message);
});
});