Spark.io + Twitter + Node.js

I recently bought a spark core at spark.io and it’s awesome. It’s basically a tiny Arduino with wi-fi built in and it costs around $40. I’ve done some preliminary testing and it seems rock solid. To top it off everything is open source. Kudos to the team at spark.io!

For a personal project I want to consume the twitter stream and filter it for keywords. When the keyword is detected it fires off a call to the spark cloud that then triggers a function on the spark core. I’ll be honest I spent more time researching the best way to do this than actually coding it.

Steps:
1) Buy a spark.
2) Install node.js
3) Set up a Twitter application
4) Create a new node project folder
5) Install twit: npm install twit
6) Install sparkcloud: npm install spark cloud

Install the following on your spark…

int LED = D7;
int State = 0;

void setup() {
    pinMode(LED, OUTPUT);
    Spark.function("led", switchLED);
    Spark.variable("ledState", &State, INT);
}

void loop() {}

int switchLED(String args) {
    digitalWrite(LED, State == 1 ? LOW : HIGH);
    return State = State == 1 ? 0 : 1;
}

Create a node script…

var Twit = require('twit')

var spark = require('sparkcloud')('your_access_token')
var core = spark.device('1234567890')

var T = new Twit({
    consumer_key:         'yourconsumerkey'
  , consumer_secret:      'yourconsumersecret'
  , access_token:         'youraccesstoken'
  , access_token_secret:  'yourtokensecret'
})



var stream = T.stream('statuses/filter', { track: 'bananas' })

stream.on('tweet', function (tweet) {
  console.log(tweet.text)
  core.func( 'led', console.log )
})


Run the script and every time there is a mention of “bananas” on twitter the little blue light on the spark will turn on and if it’s on it’ll turn off.

Pretty powerful if you ask me.

Leave a comment