-
Notifications
You must be signed in to change notification settings - Fork 4
/
mqtt.js
37 lines (31 loc) · 974 Bytes
/
mqtt.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
require('dotenv').config()
const mqtt = require('mqtt')
const logger = require('./logger')
const { json } = require('body-parser')
const client = mqtt.connect(process.env.MQTT_URL)
const init = () => {
client.on('connect', () => {
subscribe('2pai-dev/report')
logger.info('mqtt-init', 'MQTT connected')
})
}
const publish = (topic, msg) => {
client.publish(topic, msg.toString(), { qos: 0 }, (err) => {
if (err) logger.error('mqtt-publish', JSON.stringify(err))
else logger.info('mqtt-publish', 'message published to ' + topic)
})
}
const subscribe = (topic) => {
client.subscribe(topic, { qos: 0 }, (err) => {
if (err) logger.error('mqtt-subscribe', JSON.stringify(err))
else logger.info('mqtt-subscribe', 'success subscribe to ' + topic)
})
}
client.on('message', (topic, message) => {
logger.info('mqtt-message', JSON.stringify({topic:topic,payload:message.toString()}))
})
module.exports = {
init,
publish,
subscribe
}