Keep speaking to each other

Keep Talking

So, it’s that time again. We promised that this post was going to be super-dooper and it is. It. Really. Is.

Here at 23Squared we like to do stuff that interests us and is diverse, in work respects that isn’t always possible so we try as hard as we can to spend any spare time doing so. One of our long running interests is home automation, we think it’s a pretty nifty area and there’s scope for it to progress given the current tech situation.

So, after that brilliant lead up we’re going to begin discussing what we’ve been working on lately…yes folks, you’ve guessed it, it’s something to do with home automation! A few years back we went to a talk by Dr Andy Stanford-Clark (http://stanford-clark.com/) in which he discussed connecting his house to Twitter. This got us thinking. We realised that we could connect a house, an office, heck even a car to Twitter. We decided to have a play around with the Twitter API and see what we could get working.

The Twitter API is extensive and easy to use, we could’ve used it straight out of the box by writing some sort of query generator class but we opted to implement a little more abstraction than that. The two libraries that seem to be the most popular are Twitter4J (http://twitter4j.org/en/) and Spring Social (http://projects.spring.io/spring-social/). We decided to use Spring Social, although there really isn’t much to choose between the two in terms of actual usage but we might suggest that the documentation and user base for Twitter4J is slightly better!

So, what was our first aim? To be able to send tweets from the command line of course! This is an almost trivial endeavour…The trickiest part is setting up your Twitter auth bits and bobs, we aren’t going to regurgitate how to do it on the Twitter side, go take a look here – http://iag.me/socialmedia/how-to-create-a-twitter-app-in-8-easy-steps/. Once you’ve done this, you can use the information supplied to create your TwitterTemplate using Spring Social. To create a template and send a tweet it’s really as simple as the following lines of code –

private void sendTweet(String tweet) {

    twitterTemplate = new TwitterTemplate(consumerKey, consumerSecret, accessToken, accessTokenSecret);
		Tweet tweetResult = null;

		try {
			tweetResult = twitterTemplate.timelineOperations().updateStatus(tweet);
		} catch (RuntimeException ex) {
			log.error("Failed to send tweet: " + tweetResult.toString());
		}
}

Easy peasy! Spring Social is a very nicely laid out library and logically groups all operations.

So, this is all well and good but it isn’t very useful now is it? We need to give this some more oomph! The next step is being able to respond to tweets that lovely people have sent to us. Unfortunately, there isn’t a way (as far as we could see) to get push notifications (Spring Social is pretty new so we suspect this might change). The only option is to poll the API for new tweets. There is a slight issue around the rate limiting implemented by the Twitter API as defined here – https://dev.twitter.com/rest/public/rate-limits but as long as we’re reasonably careful everything should be alright!

So, how to implement this? We decided to use the Vert.x framework because, basically, it’s fantastic! It’s very flexible and provides bags of functionality for every scenario. As it’s so fully featured a complete discussion on how to use it is probably outside the scope of this post but we will try to get round to a post on it to do it justice.

The general approach to responding to tweets is –

1) Set a periodic timer and start it

2) When it expires go and retrieve new mentions

3) Respond to new mentions

4) Somehow mark these tweets as responded to so there’s no double (or triple..!) response

5) Repeat

1 is easy, because Vert.x has great functionality for timers. 3, well, 3 we’ve just covered. So, things we need to do are – 2, 4 and well, technically 5!

2 is simply a case of using Spring Social again in the following fashion –

List<Tweet> mentions = twitterTemplate.timelineOperations().getMentions();

Yes, it really is that simple! Surprisingly the trickier bit is 4. Twitter has no mechanism (at least exposed to the API anyway) to tell if tweets have been read or not. We could’ve stored all the read tweets in a JSON file on the file system but this has two drawbacks –

1) If the file is deleted we lose all records of what we’ve processed

2) To ensure correct functionality the file must be transferred with the application

We opted to use the ‘favourites’ flag to mark tweets as read, possibly not the correctly use of the feature but it allows us to store tweet read status on the server. When we read incoming mentions we can then filter out the ones that have been favourited, ie read so we don’t send multiple responses. This is achieved via the following line of code –

twitterTemplate.timelineOperations().addToFavorites(tweetId);

and then we can iterate through the entries when we read them back in whilst checking the favourited flag. Nice.

So that’s basically all the parts of a working system! We embellished our response with a ‘hello’ here and a ‘you’re cool!’ there but that’s all show! As the tweet data includes the location of th euser that tweeted us we also decided to add in a bit of a weather forecast! By using Open Weather Map (http://openweathermap.org/) at the following endpoint –

http://api.openweathermap.org/data/2.5/weather?q=

and appending the users’ location (a text string such as “London” is fine) it returns a detailed JSON object containing lots of lovely weather data which we can build into our tweet response. We opted to use Unirest (http://unirest.io/) to craft the HTTP request which is another lovely little library that does exactly what it says on the tin. We could equally have used the built in Vert.x ability to send HTTP requests but the cleanness of Unirest in the source and the ability to easy choose synchronous or asynchronous easily calls makes it our preference.

So that’s it! A whirlwind tour of Twitterising things! Where to next we hear you shout! Well, we’ve acquired some temperature and humidity sensors to monitor the twitter house, office, car, park or whatever you want to call it so watch this space!

In the meantime, you’ve been a great audience, we’ve been…

~23Squared