-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
45 lines (40 loc) · 1.26 KB
/
index.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
let mqtt = require('mqtt');
let prompt = require('prompt');
let client = mqtt.connect('mqtt://localhost:1883', {username: process.env.username, password: process.env.password});
let clients = {};
let processConnection = () => {
prompt.get(['nameTopic'], (err, result) => {
if(!result.nameTopic) return processConnection();
let nombre = result.nameTopic.split(';')[0];
let sala = result.nameTopic.split(';')[1];
client.subscribe(sala);
clients[client.options.clientId] = {
who: nombre,
topic: sala
};
prompt.get(['message'], processMessage);
});
};
let processMessage = (err, result) => {
let payload = {
name: clients[client.options.clientId].who,
msg: result.message,
city: 'Mar del Plata',
sent_at: new Date()
};
client.publish(clients[client.options.clientId].topic, JSON.stringify(payload));
prompt.get(['message'], processMessage);
};
client.on('connect', () => {
prompt.start();
processConnection();
});
client.on('message', (topic, message) => {
let mensaje = message.toString();
let payload = JSON.parse(mensaje);
console.log(`[${payload.sent_at},${payload.city}]${payload.name}:${payload.msg}`);
if(JSON.parse(mensaje).msg.indexOf("EXIT_ROOM") > -1) {
prompt.stop();
client.end();
}
});