Close

Using Twitter APIs with ESP8266

A project log for ESP8266 Twitter Client

ESP8266 Twitter client with OLED display

Andrei MehiläinenAndrei Mehiläinen 06/08/2017 at 21:030 Comments

Requests issued to the Twitter API must be authenticated. There are two ways to authenticate requests:

Application-only authentication is easier to implement, but it doesn’t allow the application to connect to Streaming endpoints. Additionally, it is not possible to post, retweet or like the tweets with this authentication. That’s why, in this project, the user authentication is implemented, which allows application to issue requests on behalf of the user.

Please make sure to check out the following source code files in order to understand better the description below:

Steps of creating an API request are well described here. Probably the most difficult part is creating a signature, which is described here. To create the signature, we need to collect all the parameters included in the request, percent encode keys and values and then concat them together. The tricky part is that before the concatenation, parameters must be alphabetically sorted. It is not a good idea to implement/use string list sorting on a resource-constrained device such as ESP8266. However, in this application all the possible request parameters are known at the compile time. This allows us to avoid run-time sorting. It is, however, responsibility of the developer to create a list of parameters in alphabetical order before calling formHttpRequest function.

All the communication with Twitter servers happens over HTTPS and thus we need to link SSL library into the project and use espconn_secure_ functions instead of normal espconn_ ones. The limitation of ESP8266 is that when using SSL, it is not possible to establish connection to multiple servers simultaneously. Normally, the device is connected to Streaming API, from which tweets are continuously received. It is possible for user to share, retweet or like the currently shown tweet. So, for example, when the user wants to share a tweet, the following happens:

  1. Disconnect from the Streaming API server
  2. Connect to the REST API server
  3. Form and send HTTP request (direct message with a link to the tweet)
  4. Receive and parse reply
  5. Reconnect back to the Streaming API server
  6. Form and send HTTP request (GET user)
  7. Continue receiving and parsing incoming tweets

Unfortunately, Espressif SSL implementation is not very robust and from time to time ESP8266 disconnects from the server by itself. This issue is discussed on Espressif forum, but no solution is found yet. Various callback functions are called on disconnection event and thus the application will try to reconnect automatically.

Discussions