Mobile
Article

Connecting the IoT and Node.js to IFTTT

By Patrick Catanzariti

IFTTT has huge potential in its ability to connect devices quickly and easily. There was one thing it had been missing for a while – the ability to send and receive generic HTTP GET and POST requests. If you wanted to use IFTTT for something, the specific use for it had to be defined by IFTTT and published on their site within a channel. That is, until now!

IFTTT recently released the Maker Channel. It is exactly what developers have been waiting for! It allows you to define triggers that are set off when they receive a HTTP request, along with actions that can make a HTTP request to a defined location. This opens up IFTTT to be used for virtually anything. It is now completely up to the imagination of the developer community.

To show what the Maker channel is capable of, we are going to set up a simple Arduino to communicate back and forth with IFTTT via Node.js. To experiment with sending triggers to IFTTT, we will toggle a LIFX lightbulb on and off via an Arduino powered light switch. To try out an IFTTT Maker action, we will connect an RGB LED to our Arduino which will change color any time we are mentioned on Twitter. Don’t like Twitter or don’t have a LIFX bulb? Not a problem at all, switch out the action/trigger with something else on IFTTT. Work with the Facebook channel instead of Twitter or trigger actions on your phone instead of a lightbulb. This is a lot of fun to tinker with.

If you are new to IFTTT, I previously covered the basics in my article on Connecting LIFX Light Bulbs to the IoT Using IFTTT. This article assumes you know all about triggers and actions, and now are ready to take it to the next level!

The code

If you’re keen to get straight into the code and try it out, you can find it here on GitHub.

How This Will Work

We are going to have a local Node.js server running with an Arduino connected via USB. Pressing a button on the Arduino set up will trigger a HTTP request to IFTTT to tell it to toggle our LIFX light. Our Node.js server will also have Express running to handle any incoming HTTP requests. Whenever IFTTT sees a new mention of us on Twitter, it’ll make a POST request to our server to trigger our Arduino’s LED.

Our Arduino Sketch

We’ll be connecting up a simple button and an RGB LED to an Arduino.

Button and RGB LED Sketch

Setting Up The Maker Channel

To get started, we will need to go to the Maker Channel on IFTTT and click “Connect”. Once it is set up, you’ll reach a screen that looks like so:

Finding your Maker key

On this screen, it provides your secret key you’ll need to trigger IFTTT actions via HTTP commands. Of course, you’ll need a bit more info than just the key, we need a URL to POST to that’ll trigger the action. To find this, click the link that says “How to Trigger Events”. It’ll open up a page that contains the URL you’ll want to use, conveniently with your key attached to it.

Triggering maker events

The URL we’ll be using for our LIFX bulb looks like this: http://maker.ifttt.com/trigger/light_switch/with/key/{{yourkeyhere}}. The URL part which says light_switch is our event name. We use this when putting together our IFTTT recipe. If you’re not triggering a LIFX bulb, choose a name that matches your event more accurately.

Toggling IFTTT Using Maker Triggers

Our Maker channel is active and ready to be used. We will begin by looking at how to toggle our IFTTT action – toggling a LIFX lightbulb on and off using a button from an Arduino.

Making the recipe itself is quite simple:

  1. We go to the Create New Recipe page on IFTTT.
  2. Select “Maker” as our Trigger Channel.
  3. Click on “Receive a web request” as our trigger type.
  4. Enter our event name of light_switch.
  5. Choose “LIFX” as our Action Channel.
  6. Click on “Toggle lights on/off” as our action type.
  7. Choose the LIFX lights we’d like this to affect.
  8. Give the recipe a title and click “Create Recipe”!

In our Node.js code, we use johnny-five to access our Arduino. When the board is ready, we define our button connected to pin 7 in the btn variable:

board.on('ready', function() {
    console.log('Board ready');

    btn = new five.Button(7);

Within the board’s ready event, we set up a watch for the button’s down event. If we detect the button has been pressed, we log that click to the console for debugging purposes (in the situation where a wire on the breadboard comes loose or something along those lines, having these console logs can save a lot of time!). Then, we use the npm module request to make a HTTP POST request to the URL we found above. We’ve got console logs upon its success for debugging purposes also.

btn.on('down', function(value) {
    console.log('Light toggle pressed.');
    
    request.post({
      url: 'http://maker.ifttt.com/trigger/light_switch/with/key/{{yourkeyhere}}'
    }, function(error, response, body) {
      console.log('Body response was ', body);
      console.log('Error was ', error);
    });
  });

Upon running the code, when we click the button and the request is successful, it should switch our LIFX lightbulb on and off! IFTTT will return a nice message that will look like so in our console.log:

Body response was Congratulations! You've fired the light_switch event

It is really simple to put together but has a lot of potential.

One thing to note – if you want to make a call to the IFTTT service via HTTPS, you’ll need a properly secured HTTPS server too. I had errors when using a local test server, so it may need to have a certificate that isn’t self signed.

Responding To IFTTT Triggers

We now can trigger IFTTT actions via Node.js and our Arduino. Let’s look at how to do things the opposite way – making our Arduino respond to IFTTT triggers. We’ll set up IFTTT to tell our Node.js server and Arduino whenever we are mentioned on Twitter.

We put together the recipe the other way around:

  1. We go to the Create New Recipe page on IFTTT.
  2. Select “Twitter” as our Trigger Channel.
  3. Click on “New mention of you” as our trigger type.
  4. Click “Create Trigger”.
  5. Choose “Maker” as our Action Channel.
  6. Click on “Make a web request” as our action type.
  7. Put in your POST request settings (we’ll cover these below) and click “Create Action”!

The screen with our HTTP request settings will look like so:

Making IFTTT JSON Requests

  1. Put in a publically accessible URL for your Node server. I personally use ngrok for testing all of this out. I cover how to use ngrok and similar services in my article on Accessing Localhost From Anywhere. Choose POST for the method (a GET request should work too if you’d prefer it).
  2. Choose “application/json” for the content type as our Node server will be expecting to receive JSON.
  3. Finally, include the JSON message we’d like to send. I put down {"color":"#55acee", "text":Text}. #55acee is the color I found from Twitter’s bird mascot, so I thought it the most appropriate choice!
  4. Text is a field dynamically filled in by IFTTT with the text from the tweet it found mentioning you. These fields are called IFTTT ingredients. We don’t really use it to change our LED color but I wanted to include an IFTTT ingredient in there to show how it’s done.
  5. To add an ingredient into your JSON, click on the body field to enter in your JSON string and you’ll find a test tube icon on the right hand side. If you click it, you’ll open a menu which will let you choose a field to include:

    Choosing ingredients

Within our Node code, we set up our LED so that our johnny-five module knows about it and set up the server to listen for that POST request. It will respond to it by changing our LED.

Within the board’s ready event, we define our LED attached to pins 9, 10 and 11 within the variable of led like so:

led = new five.Led.RGB([11,10,9]);

The code might look odd as the pins count down from 11 rather than up. The reason for this is I prefer my wiring to have red, green and then blue from top to bottom on the Arduino board (e.g. 11, then 10 and 9).

We set its initial color to green:

led.color('#00ff00');

Outside of the board’s ready event, we create our routing for the /led POST request using express. Within the callback function for this route, we get the JSON data sent from IFTTT inside req.body and find the color key within it. We give that color to johnny-five‘s led.color() function to change the color of our LED to what we’ve been given. We log the JSON data in our console too.

app.post('/led', function (req, res) {
    var response = req.body;
    console.log('Response was ', response);

    led.color(response.color);
    res.send('LED request successful!');
  });

Something to keep in mind – If you’re putting this on a publically accessible server that will be available for more than just test purposes, I’d recommend checking that the JSON data being provided is actually a color and is a legitimate request.

If you run the Node server and then recieve a tweet at your account, after a little while (it won’t be instant as it seems to take time for IFTTT to refresh that info from Twitter at times), your LED should go Twitter blue! In your console.log, you should see something like the following:

Response was { color: '#55acee', text: '@thatpatrickguy WOO HOO' }

Then, if you set up various other services along the same lines but with different colors, you can have a wide variety of LED color changes!

Conclusion

Having the ecosystem of IFTTT and all of its channels available to makers of any internet enabled technology that can send and receive HTTP requests is huge. Whilst we’ve been able to do things like include the Twitter API into Node.js applications for a long time now, this provides a whole range of possibilities in an API that is much easier to use and is incredibly modular. Switch out Twitter for something else and everything should still work with only a few adjustments!

If you make some really neat IFTTT Maker Channel creation from this guide, leave a note in the comments or get in touch with me on Twitter (@thatpatrickguy), I’d like to take a look!

  • M S i N Lund

    Is there any way i could insert a greater number of steps between those described?

    • Patrick Catanzariti

      What steps are you looking to do? Do you mean more fine tuning of the Twitter API requests? (That’s limited to the various options provided by IFTTT) Or adding in more actions to the responses in Node? (That’s totally possible, you could do any number of things with the results you get back, or perform additional actions than just turning on a light) Or something else?

  • http://martinkronberg.com Martin Kronberg

    Great article, thanks! I used it as a starting point for a similar project: http://martinkronberg.com/new-blog/2015/6/30/ifttt-and-intel-edison. Check it out if you want

    • Patrick Catanzariti

      That’s fantastic! Sorry for the delay, I didn’t receive a notification that you’d commented here! I might actually be including a link to your article on an upcoming guide page for Intel board projects on http://www.devdiner.com if that’s okay? :)

  • Yael

    Does this require your web service to be hosted in a public server? Can this be used in a private LAN? Thanks

    • Patrick Catanzariti

      You could use IFTTT in an IoT set up on a private LAN, but only actions which send out to IFTTT. You wouldn’t be able to use IFTTT to trigger events on your private LAN this way because there’d be no public URL for it to access.

  • Arne Könnecker

    Any possibility to get this running with a Raspberry Pi 2 as well?

    • Patrick Catanzariti

      Yep! You’d be able to do the same sort of idea with Node running on the Pi 2 :) I might try and do that as an upcoming article actually!

  • Patrick Catanzariti

    Hmmmm, this might be a limitation on IFTTT, because the data in that needs to be escaped first and it looks like they aren’t escaping it. Maybe try sending it as a different content type? Like text/plain? Then potentially handling it via some of these ideas – http://stackoverflow.com/questions/17887189/how-to-handle-plain-text-server-response

  • Monbo

    I wonder, the web request uses GET method, but would be a POST or PUT method more appropriate one because it changes the resources (color of the LED)?
    Thanks anyone for an explanation and clarification!

    • wak

      get 应该就好象墙壁上的开关,0 1 !

  • balsimpson

    Hi, I have been trawling the net looking for some info on doing an HTTP Post the right way. What am trying to do is to get/parse some JSON data that IFTTT is sending my nodeMCU. But the JSON file has too many nested values, how do I extract just the values I want? Any help would be appreciated.

    • Patrick Catanzariti

      You can get the values you want using libraries like underscore.js to parse it all a bit easier :) That might help!

  • Richard C Hidalgo Lorite

    have you found any solution to this? i have same problem on another context, need to escape text to get valid json

    • wak

      自己麻烦处理下,2总要选择1的

  • Domenic Z

    Can this be used to do a simple web hit to a public URL? I have a node.js that can accept commands to control my Sonos system through a simple URL. I am not passing any extra data at all just simply http://myipaddres:3006/playlist/Zac. Putting that into a browser will simply make that playlist play on all of my Sonos speakers in the house.

    • Patrick Catanzariti

      Yep! As long as the URL accepts a simple GET request and is accessible to the open internet (e.g. not localhost but visible to the outside world), that should potentially work :)

      • Domenic Z

        I have tried everything and I cannot get it to hit a simple website with what I posted. Not sure what I’m doing wrong, it seems so basic.

  • wak

    最后一句严重同意!

  • Luke Jacob

    Is it possible to somehow get the tweet ID through the twitter app when doing this?

    • https://www.devdiner.com Patrick Catanzariti

      I don’t think it is… unless the linkToTweet or embed code includes that somehow? But you’d need to build your own way to parse it.

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in Mobile, once a week, for free.