-
Notifications
You must be signed in to change notification settings - Fork 1
/
broker.js
68 lines (61 loc) · 1.59 KB
/
broker.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// MQTT broker
let mosca = require('mosca')
let settings = {port: 1883}
let broker = new mosca.Server(settings)
// MySQL
let mysql = require('mysql')
let db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '#Kunci231#',
database: 'mqttJS'
})
db.connect(()=>{
console.log('Database connected!')
})
broker.on('ready', ()=>{
console.log('Broker is ready!')
})
broker.on('published', (packet)=>{
message = packet.payload.toString()
console.log(message)
let dbStat = 'insert into mqttJS set ?'
let data = {
message: message
}
db.query(dbStat, data, (error, output)=>{
if(error){
console.log(error)
} else {
console.log('Data saved to database!')
}
})
})
// function ConnectBroker() {
// }
// function publish() {
// // MQTT publisher
// var mqtt = require('mqtt')
// var client = mqtt.connect('mqtt://localhost:1234')
// var topic = 'LINTANGtest123'
// var message = 'Hello World!'
// client.on('connect', ()=>{
// setInterval(()=>{
// client.publish(topic, message)
// console.log('Message sent!', message)
// }, 5000)
// })
// }
// function subscribe() {
// // MQTT subscriber
// var mqtt = require('mqtt')
// var client = mqtt.connect('mqtt://localhost:1234')
// var topic = 'LINTANGtest123'
// client.on('message', (topic, message)=>{
// message = message.toString()
// console.log(message)
// })
// client.on('connect', ()=>{
// client.subscribe(topic)
// })
// }