Skip to content

Instantly share code, notes, and snippets.

@jesseschutt
Created February 16, 2020 00:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jesseschutt/de63cf84734b1993b93b5dc2dd0e7dc6 to your computer and use it in GitHub Desktop.
Save jesseschutt/de63cf84734b1993b93b5dc2dd0e7dc6 to your computer and use it in GitHub Desktop.
A simple node script to subscribe to an MQTT broker and forward on messages to a Laravel application.
process.title = 'mqtt-demo-process-node'
const mqtt = require('mqtt')
const axios = require('axios')
const debug = process.env.NODE_ENV !== 'production'
let endpoint = 'https://####.test/messages'
if(process.env.NODE_ENV === 'production') {
endpoint = 'https://####.com/messages'
}
if(debug){
console.log('connecting')
}
const client = mqtt.connect('mqtt://m16.cloudmqtt.com:#####', {
username: '####',
password: '####'
})
client.on('connect', () => {
if(debug) {
console.log('connected')
}
client.subscribe('+/your-topic',{qos:1})
})
client.on('message',function(topic,message){
if(debug) {
console.log('this message :', message.toString());
}
axios.post(endpoint, {topic, message: message.toString()})
.then(({ data }) => {
if(debug) {
console.log(data);
}
})
.catch(error => {
if(debug) {
console.error(error);
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment