Node.js MQTT support for Node.js
This page explains the support of the Node.js MQTT framework.
Controller.js defines a publisher with a messenger:
function openGarageDoor () {
// can only open door if we're connected to mqtt and door isn't already open
if (connected && garageState !== 'open') {
// Ask the door to open
client.publish('garage/open', 'true')
}
}
function closeGarageDoor () {
// can only close door if we're connected to mqtt and door isn't already closed
if (connected && garageState !== 'closed') {
// Ask the door to close
client.publish('garage/close', 'true')
}
}
garage.js defines a subscriber as:
client.on('connect', () => {
client.subscribe('garage/open')
client.subscribe('garage/close')
// Inform controllers that garage is connected
client.publish('garage/connected', 'true')
sendStateUpdate()
})
client.on('message', (topic, message) => {
console.log('received message %s %s', topic, message)
switch (topic) {
case 'garage/open':
return handleOpenRequest(message)
case 'garage/close':
return handleCloseRequest(message)
}
})
This will give the following result: