const mqtt = require('mqtt')
const host = 'broker.emqx.io'
const port = '8084'
const clientId = `mqtt_${Math.random().toString(16).slice(3)}`
const mqtt = require('mqtt')
const connectUrl = `mqtt://${host}:${port}`
const client = mqtt.connect(connectUrl, {
clientId,
clean: true,
connectTimeout: 4000,
username: 'emqx',
password: 'public',
reconnectPeriod: 1000,
})
const topic = 'sensor/{clientId}/temperature'
client.on('connect', () => {
console.log('Connected')
client.subscribe([topic], () => {
console.log(`Subscribe to topic '${topic}'`)
})
client.publish(topic, 'nodejs mqtt test', { qos: 0, retain: false }, (error) => {
if (error) {
console.error(error)
}
})
})
client.on('message', (topic, payload) => {
console.log('Received Message:', topic, payload.toString())
})