Basic MQTT Setup on a RaspberryPi using Node.js

I’m really enjoying Adafruit’s IoT platform - it’s free and offers a nice blend of a dashboard system, a REST API, a basic MQTT broker, and few other handy services.

A recent screwing-around-project involved connecting speakers to a Raspberry Pi, and triggering various sounds/songs to play when buttons were pressed, RFID cards read, or whatever else I could think of. I started with IFTT, but wanted something a little more pub/sub driven, and MQTT is the standard for ‘Internet of Things’ uhhhh, things. You could set up your own MQTT broker (the pub/sub server) pretty easily, but I chose to leverage Adafruit’s system.

The first thing you’ll need is an account with Adafruit if you don’t already have one. Next, create a feed to play around with. Adafruit has a great article to help get you started.

On your Pi, create folder for your app, and cd into it.

Then run:

  1. npm init . to initialize a new node application
  2. npm install mqtt --save to install the mqtt client library

Create a new file for you node app, called app.js and use the following:

  var mqtt = require('mqtt'),
      my_topic_name = 'your-adafruit-username/f/feed-name';

  var client = mqtt.connect('mqtts://',{
    port: 8883,
    username: 'username',
    password: 'apikey'

  client.on('connect', () => {

  client.on('error', (error) => {
    console.log('MQTT Client Errored');

  client.on('message', function (topic, message) {
    // Do some sort of thing here.
    // Could be GPIO related, or in my case running system commands to
    // trigger the omxplayer app to play a certain file.

    console.log(message.toString()); // for demo purposes.

Run node app.js to start your app.

One cool thing I like about Adafruit’s platform is that feeds can be accessed via MQTT or the REST API, which means you can fire up Postman, curl, or whatever and make calls to the REST API and see them logged immediately in the console of your node app that is connected via MQTT. The only caveat when using the REST API is, unlike the MQTT setup where you use the feed name directly, you use the feed id instead (found on your feeds page).

Fire up a shell on your main machine and run the following:

curl --request POST
  --header 'content-type: application/json'
  --header 'x-aio-key: your-adafruit-api-key' 
  --data '{\n  "value": "Hey!"\n}'

You should see your node app output the value ‘Hey!’ to your console.

Now go make stuff.


puts "Hello, Universe!"

# Paradigm shifted. Pack it in for the day.