Creating an MQTT broker on the Pi

If you are using two Pis, carry out this entire section on the broker Pi. If you are using one Pi, do all of this on your one Pi.

We're going to use the Mosca library to set up an MQTT broker on our Pi. The mosca npm library makes it really easy to set up and start an MQTT broker. All we need is a running mongoDB instance (which we took care of in the last step, Setting up light sensor). 

In the broker folder (either on your original or broker Pi), in the index.js file, we're going to set up mosca:

const mosca = require('mosca')

const mqttBroker = new mosca.Server({
port: 1883,
backend: {
type: 'mongo',
url: 'mongodb://localhost:27017/mqtt',
pubsubCollection: 'MQTT-broker-NodeBots',
mongo: {}
}
})

server.on('ready', () => {
console.log('MQTT broker ready!')
})

server.on('clientConnected', (client) => {
console.log('Client connected to MQTT broker: ', client.id)
})

server.on('published', (packet, client) => {
client = client || {id: 'N/A'} // Catches a weird edge case with mosca
console.log(`Client: ${client.id} Topic: ${packet.topic} Message: ${packet.payload.toString()} `)
})

We now have our MQTT broker ready to go! Time to program our client.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.199.122