MicroTweet for the .NET Micro Framework

Update April 14, 2011: This project is now on CodePlex: MicroTweet – Twitter OAuth API Library for the .NET Micro Framework

I recently purchased a Netduino Plus, a small (but powerful) board based on an Atmel 32-bit microprocessor with the same form factor as an Arduino. The Netduino can run programs written in C# for the .NET Micro Framework and the “Plus” version adds a 10/100 Mbps Ethernet port, giving you a very powerful network-capable device for about $59 USD.

What can you do with it? Quite a lot, actually, as seen in the Project Showcase section of the Netduino Forums. You have access to network sockets via System.Net.Sockets, you can perform HTTP requests via System.Http, and there are even a few lightweight web server implementations available.

The only thing I couldn’t find is a library for Twitter. Looking around, I found a project called Tweet Library for Arduino, which sends tweets through an external website, presumably to avoid implementing OAuth on the Arduino. For this project, I decided to make the Netduino communicate with Twitter’s API directly, which means no external websites or proxies are necessary.

OAuth Overview

Twitter currently requires all API calls to be authenticated with OAuth. To communicate with the Twitter API, you must first register an application to get the necessary Consumer Key and Consumer Secret values. Account-specific API calls require an Access Token and Access Token Secret, which are generated after giving an application permission to access your account. An Access Token and Access Token Secret are automatically provided for your account when you register an application.

Each API request must have an Authentication header with certain OAuth parameters. One of these parameters is the OAuth signature, which is generated by creating an HMAC-SHA1 hash of the HTTP method, the normalized URL, the other OAuth parameters, and any POST variables (or query string parameters for GET requests). This signature is encoded in a Base64 string.

Generating the OAuth signature is the most computationally intensive part of making API calls. I found that it takes around 500-1500ms to generate the signature on a Netduino Plus depending on the input parameters.

It should also be mentioned that one of the OAuth parameters is the current date and time formatted as a Unix timestamp. Without an accurate timestamp all API requests will fail, so it is important to make sure the Netduino’s clock is updated before making API calls.

Implementation

For this project, I am using the following third-party libraries:

  • Elze Kool’s SHA/HMAC Digest Class, with one modification to properly handle secret values that are > 84 characters long
  • The NearlyGenericArrayList class from the MicroLinq project
  • The NTPTime method posted by Chris Seto in the Netduino Forums

The OAuth class created for this project implements most of the OAuth specification, with a few shortcuts taken to save processing time and program space. For example, it assumes that URLs have been properly normalized before they are passed to the OAuth.GetOAuthRequest method.

The TweetBot class has been separated into two different files: TweetBot.cs for the main class structure and TweetBot.HTTPRequests.cs for the HTTP requests. While there is currently only one HTTP request method, this structure will help make sure the code remains easy-to-understand as development continues.

TweetBot instances have a DebugMessage event which you can hook into to print debug messages to a serial port, a log file on an SD card, etc.

Currently, all HTTP operations are performed synchronously but you could probably modify them to run asynchronously fairly easily. Also, there is currently very little error handling so if the Twitter API cannot be reached or if you enter bad access keys you will probably get an unhandled exception. It might be a good idea to wrap all TweetBot method calls in a try/catch block.

Using the TweetBot Class

Using TweetBot is pretty straightforward. First, specify your application and account details somewhere in your program.

#region Twitter Account Details

protected const string consumerKey = "YourAppConsumerKey";
protected const string consumerSecret = "YourAppConsumerSecret";
protected const string userToken = "YourAccountUserToken";
protected const string userTokenSecret = "YourAccountUserTokenSecret";

#endregion

You must first register a new app to get a Consumer Key and Consumer Secret. Once you have completed the registration procedure, open the Twitter Applications page, view your application details, and click the link that says “My Access Token.” That page will display your account’s User Access Token and User Access Token Secret.

In order to create valid OAuth requests, the Netduino’s clock must be set with the correct time.  Here is an example from the Netduino forums for retrieving the current time from an NTP server.  (This code is also included in the demo app.)

To send a tweet, create a new instance of the TweetBot class and call its SendTweet method:

tweetBot = new TweetBot(consumerKey, consumerSecret);
tweetBot.UserToken = userToken;
tweetBot.UserTokenSecret = userTokenSecret;
bool tweetSent = tweetBot.SendTweet("Hello from a " + SystemInfo.OEMString + "!");

That’s it! SendTweet returns true if the tweet was sent successfully.

Demo Program

The demo program included with this project creates a serial “console” on the Netduino Plus’ COM1 port running at 115200bps. This port uses digital pin 0 on the N+ for Rx and pin 1 for Tx. I am using a Bus Pirate to communicate with the Netduino’s serial port, but you could also use an FT232R device (or similar) running at 3.3V or a level converter.

Bus Pirate

Three connections are necessary:

  • Bus Pirate Gnd to Netduino Gnd
  • Bus Pirate Tx to Netduino Rx
  • Bus Pirate Rx to Netduino Tx

Check the Bus Pirate manual for specific pin numbers as they may vary between devices. Once everything is plugged in and turned on, configure the Bus Pirate for 115200bps UART with “Normal” (3.3V/Gnd) output. The command sequence is m, 3, 9, 1, 1, 1, 2.

Next, start the “Transparent bridge” macro by typing “(1)” (with the parenthesis) and then “y” to accept the warning. This configures the Bus Pirate to act as a transparent UART bridge, so all input characters are sent to the Netduino and all output from the Netduino is displayed in your terminal.

Demo Console

When the demo program runs, a help message will be written to the serial port. If you connect after the initial message has been sent, just type “?” and press enter to see it again.
To post a tweet, type “p <message>” and press enter. You can also omit the message to post a generic “Hello from a [OEMString]!” message. (Note that if you try to post the same message multiple times you will probably get a “repeated message” error.)
If everything works, your message will be posted to Twitter from your account:

Code

The code for this project is available from CodePlex: MicroTweet – Twitter OAuth API Library for the .NET Micro Framework

Like the Netduino’s software, this code is released under the Apache 2.0 license.

If you find this code useful or have any suggestions/changes, please let me know! Also, follow me on Twitter for more .NET-related info.

2 thoughts on “MicroTweet for the .NET Micro Framework”

  1. Hi, i need some little code to netduino plus, for send short messages to twitter, do you have some example please, or code, to learn, i need make some, my idea is when i press the button of N+, send
    a message to twitter.

    thanks for your help….excuse me for my english.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.