• Home
  • pcDuino
  • WiKi
  • Store
  • Distributors
  • Home
  • pcDuino
  • WiKi
  • Store
  • Distributors
HomeArduinoArduino EsploraTrain Schedule – OLED Display
Previous Next

Train Schedule – OLED Display

Posted by: Olva , September 13, 2016
Schedule closeup in station

When and where is the next train going?! The IoL City citizens have things to do and places to be!

Goal

  • Pull in Transport For London API data to get schedule information for a local train stop
  • Display next trains and time to arrival on an OLED screen

Technologies & Components

  • Cactus Micro rev2
    • Arduino LillyPad USB w/ ESP8266 compatible
  • OLED screen
    • 128×64 i2c
  • Transport for London API
    • Unified TFL API
  • Node-RED
    • Platform to wire the Internet of Things
  • PubNub
    • Enterprise real-time pub/sub messaging service
  • MQTT
    • Open source and efficient pub/sub protocol

Overview

The OLED display project will build on the skills and technology learned in theWeather Station project. The basic concept is to utilize a Cactus Micro micro controller (Arduino clone with ESP8266 WiFi built-in) with MQTT messaging to exchange information. But instead of the device sending data, it will be receiving data to display on an OLED screen. In addition, the schedule data will be published to a PubNub channel for use with other IoL City projects.

Transport for London API

As a fun exercise, I wanted to pull in some publicly available data via an API,manipulate it and use it with an application. The TFL API was a great fit for this project. It works by simply going to a website, which responds with information in a JSON format. No need for API keys, just a simple GET request and you have data!

So how does it really work? I’m glad you asked. Basically, there are a number ofURLs that you can visit that return related information. Anything from trains, buses to boats can be retrieved with their “Unified RESTful API”.

All the information can be found here: https://api-portal.tfl.gov.uk/docs

To keep things simple,I’ve selected a local train station near me which has two outbound routes. I will then use that information to determine which direction the train track should be switched to and also display the time it will arrive.

To find the station ID, I first used the following GET URL

https://api.tfl.gov.uk/StopPoint/Search/fields

Which then returns the following result snippet

  1. {“$type”:“Tfl.Api.Presentation.Entities.SearchResponse, Tfl.Api.Presentation.Entities”,“query”:“fields”,“total”:50,“matches”:[{“$type”:“Tfl.Api.Presentation.Entities.MatchedStop, Tfl.Api.Presentation.Entities”,“stationId”:“940GZZLUNFD”,“icsId”:“1000159”,“topMostParentId”:“940GZZLUNFD”,“modes”:[“bus”,“tube”],“status”:true,“id”:“940GZZLUNFD”,“name”:“Northfields Underground Station”,“lat”:51.499324,“lon”:–0.31472},{“$type”:“Tfl.Api.Presentation.Entities.MatchedStop, Tfl.Api.Presentation.Entities”,“stationId”:“940GZZLUSFS”,“icsId”:“1000209”,“topMostParentId”:“940GZZLUSFS”,“modes”:[“bus”,“tube”],“status”:true,“id”:“940GZZLUSFS”,“name”:“Southfields Underground Station”,“lat”:51.445076,“lon”:–0.2066},{“$type”:“Tfl.Api.Presentation.Entities.MatchedStop, Tfl.Api.Presentation.Entities”,“stationId”:“910GLONFLDS”,“icsId”:“1001183”,“topMostParentId”:“910GLONFLDS”,“modes”:[“overground”,“national-rail”],“status”:true,“id”:“910GLONFLDS”,“name”:“London Fields Rail Station”,“lat”:51.541158,“lon”:–0.057747},
  2. ……

I then searched for “London Fields” and found that the ID is910GLONFLDS.

Finally, I used the following URL to retrieve the local train schedule.
URL: https://api.tfl.gov.uk/StopPoint/910GLONFLDS/arrivals

Which then returns the following result snippet

  1. [{“$type”:“Tfl.Api.Presentation.Entities.Prediction, Tfl.Api.Presentation.Entities”,“id”:“-407419356”,“operationType”:1,“vehicleId”:“6uXFyoXFIOb2cMfIGrmiLQ==”,“naptanId”:“910GLONFLDS”,“stationName”:“London Fields Rail Station”,“lineId”:“london-overground”,“lineName”:“London Overground”,“platformName”:“2”,“direction”:“outbound”,“destinationNaptanId”:“910GENFLDTN”,“destinationName”:“Enfield Town Rail Station”,“timestamp”:“2016-01-15T18:38:32.787Z”,“timeToStation”:1680,“currentLocation”:“”,“towards”:“”,“expectedArrival”:“2016-01-15T19:06:32.787Z”,“timeToLive”:“2016-01-15T19:06:32.787Z”,“modeName”:“overground”},{“$type”:“Tfl.Api.Presentation.Entities.Prediction, Tfl.Api.Presentation.Entities”,“id”:“-422333055”,“operationType”:1,“vehicleId”:“Br9J3rKECr9QYjK0MhQCaw==”,“naptanId”:“910GLONFLDS”,“stationName”:“London Fields Rail Station”,“lineId”:“london-overground”,“lineName”:“London Overground”,“platformName”:“1”,“direction”:“inbound”,“destinationNaptanId”:“910GLIVST”,“destinationName”:“London Liverpool Street Rail Station”,“timestamp”:“2016-01-15T18:38:32.802Z”,“timeToStation”:2220,“currentLocation”:“”,“towards”:“”,“expectedArrival”:“2016-01-15T19:15:32.802Z”,“timeToLive”:“2016-01-15T19:15:32.802Z”,“modeName”:“overground”},{“$type”:“Tfl.Api.Presentation.Entities.Prediction, Tfl.Api.Presentation.Entities”,“id”:“1667012363”,“operationType”:1,“vehicleId”:“Dk12CzBKtYQmV+mYwrJh6w==”,“naptanId”:“910GLONFLDS”,“stationName”:“London Fields Rail Station”,“lineId”:“london-overground”,“lineName”:“London
  2. ….

Cool! But that is way too much info for my purposes. I also want to automate this task and send the results to my Internet of Things LEGO

Programming

I will be using Node-RED to perform the plumbing for my two messaging systems,MQTT & PubNub. Although I wrote much of this application originally in pure NodeJS, I found that Node-RED was still more fun to experiment with. For example, I could quickly pipe this data to Twitter/Slack/Twilio to send me a message if my train is close. By just passing around objects and manipulating them with JS in function nodes, I can pretty much do what I want for IoT related tasks and rapid prototyping.

Node-RED Flow – Schedule and Display

Screen Shot 2016-01-15 at 11.40.58 PM

Download flow: Gist

To get the TFL data into the system, I first started by creating a function to define the URL that will be passed to the HTTP Get request node. This was accomplished by using a function node to simply write the msg.url property to the desired station ID. I use an injection node with a repeat schedule to automate the data stream. Because it pulls every second, I placed a delay of 1 minute to not abuse the network. I also added a RESTful interface myself for future use and flexibility.

The API data is returned as a JSON string, which I then use a JSON node to convert it to an object. This is necessary so I can iterate through it and extract the important data.

With the data in hand, its time to extract it and create a new schema. Here’s an example of what a populated data set will look like.

  1. {
  2. “station”: “London Fields Rail Station”,
  3. “schedule”: [
  4. {
  5. “expected”: “3”,
  6. “destination”: “Enfield Town Rail Station”
  7. },
  8. {
  9. “expected”: “15”,
  10. “destination”: “Cheshunt Rail Station”
  11. },
  12. {
  13. “expected”: “25”,
  14. “destination”: “Enfield Town Rail Station”
  15. },
  16. {
  17. “expected”: “35”,
  18. “destination”: “Cheshunt Rail Station”
  19. },
  20. {
  21. “expected”: “50”,
  22. “destination”: “Enfield Town Rail Station”
  23. }
  24. ]
  25. }

But first, the data is originally sent in some arbitrary order, so it needs to be sorted. At the same time, the desired properties are saved to the new schema. This function node takes care of all that:

Screen Shot 2016-01-15 at 11.41.56 PM

  1. var tfl = msg.payload;
  2. var trains = {};
  3. var station;
  4. var expected;
  5. var nextTrains = [];
  6. // check for valid data first
  7. if (msg.statusCode == 200) {
  8. //if(tfl[0] !== undefined){
  9. if(tfl[0]){
  10. station = tfl[0].stationName;
  11. // sort schedule
  12. tfl.sort(function(a,b){
  13. return (a.timeToStation – b.timeToStation);
  14. });
  15. // iterate through all schedule records and save required data
  16. for (var i = 0; i < tfl.length; i++) {
  17. if(tfl[i].direction == ‘outbound’){
  18. nextTrains.push({
  19. ‘expected’: (tfl[i].timeToStation)/60,
  20. ‘destination’: tfl[i].destinationName
  21. });
  22. }
  23. }
  24. }else{
  25. // no schedule received
  26. station = msg.stationid; // use station id as default
  27. nextTrains.push({
  28. ‘expected’: 0,
  29. ‘destination’: “Out of Service”
  30. })
  31. }
  32. trains.station = station;
  33. trains.schedule = nextTrains;
  34. }
  35. // display and send schedule data
  36. console.log(“outbound schedule new schema > “);
  37. console.log(util.inspect(trains, false, null));
  38. msg.payload = trains;
  39. flow.set(‘trainschedule’, msg.payload); // save for flow use
  40. return msg;

 

HTTP response node

By adding an HTTP input and response node, I can toggle the train schedule routine and get a current formatted schedule. Although I am not relying on this for this project, I thought it was a handy option for the future. Maybe a UI dashboard can request that data as needed.

GET Request: http://myNodeRedServer:1880/trainschedule

REST interface for new train scheduleHTTP response node

Example of GET response

  1. {“station”:“London Fields Rail Station”,“schedule”:[{“expected”:”0“,”destination“:”Cheshunt Rail Station“},{“expected“:”18“,”destination“:”Enfield Town Rail Station“},{“expected“:”33“,”destination“:”Cheshunt Rail Station“},{“expected“:”48“,”destination“:”Enfield Town Rail Station“},{“expected“:”63“,”destination“:”Cheshunt Rail Station”}]}

Now that I have the data… the magic begins!

The msg object, which now contains the schedule information, will be passed to multiple nodes for future applications.

MQTT

Send the schedule to the OLED display board.

Since this data is in JSON format, it must first be converted to a simple text string. I also pre-formatted it to avoid too much code on the embedded side. This approach also allows the OLED display board to be easily used for other applications without much adjustment. The schedule was too much text, so the destination names were simplified. Instead of “Enfield Town Rail Station”, the string was split and then the first two words and a space were joined back. I also padded the expected time with a leading 0 if less than 10 so that the station names would line up. Finally, the data was sent to the MQTT topic /trainschedule/910GLONFLDS

Node-RED schedule to MQTT display

Function: Format to MQTT display string

  1. var station = msg.payload.station;
  2. var schedule = msg.payload.schedule;
  3. var destination;
  4. var split;
  5. msg.topic = “/trainschedule/” + msg.stationid;
  6. if (schedule[0].destination == “Out of Service”){
  7. destination = schedule[0].destination;
  8. //destination = “Out of Service”;
  9. msg.payload = destination;
  10. return msg;
  11. }else{
  12. // Split the string and only use the first two words of each value
  13. split = station.split(” “);
  14. station = split[0] +” “+ split[1] + “\n\n”;
  15. msg.payload = station;
  16. for(var x = 0; x < schedule.length; x++){
  17. split = schedule[x].destination.split(” “);
  18. destination = split[0] +” “+ split[1];
  19. msg.payload += pad(schedule[x].expected) + “m” + ” “ + destination + “\n”;
  20. }
  21. return msg;
  22. }
  23. function pad(n) {
  24. return (n < 10) ? (“0” + n) : n;
  25. }

 

Schedule Display

Cactus Micro Rev2

cactus micro rev2 pinout

An Arduino LillyPadUSB clone with built-in ESP8266 module.

Resources:

http://wiki.aprbrother.com/wiki/Cactus_Micro_Rev2

OLED 128×64

OLED screen

128x64 I2C

128×64 I2C

Specifications: 0.96” I2CIIC128X64 OLED LCD LED

Resources: https://www.adafruit.com/products/326

Text Only Library: https://github.com/greiman/SSD1306Ascii

Circuit

The circuit is very simple. Just connect the OLED board to the VCC and ground pins. Then connect the SDA (GPIO 2) and SDC (GPIO 3) pins.

Note: This Fritzing diagram uses an Arduino Nano, so pin placement will be slightly different.

Train Schedule - OLED Fritzing

Code

Before the project code can be uploaded to the Cactus Micro, we must first flash the onboard ESP8266 with the appropriate firmware. To accomplish this, a utility sketch will need to be first uploaded to the Cactus, which will create a transparent bridge to the ESP8266.

Step 1: Configure the Arduino as an ESPprogrammer

Connect the Cactus Micro to your computer, and set the Arduino IDE to use the LillyPad USB for the board. Then upload the following sketch.

sketch esp8266Programmer

More info:

http://wiki.aprbrother.com/wiki/How_to_made_Cactus_Micro_R2_as_ESP8266_programmer

Step 2: Flash the ESP8266 with this firmware

The ESP8266 is now directly accessible from a serial port and can be programmed with the esp tool. Download the firmware and tool, then run the programming command. Be sure to adjust the serial port (e.g.ty.usbmodem1421) to match your configuration.

Firmware: espduino

Tool: esptool

  1. ./esptool.py -p tty.usbmodem1421 write_flash 0x00000 esp8266/release/0x00000.bin 0x40000 esp8266/release/0x40000.bin

 

Step 3: Program project code to Cactus Micro

The general code flow begins with initializing a timer, OLED screen, ESP8266 WiFi and MQTT messaging.

Since this microcontroller only has 32k of memory, space is a real challenge. I originally tried to use the nice Adafruit graphics library, but it wouldn’t fit on the device with the additional communication libraries. So instead, a text only custom library will be used. I’ve also used the MQTT library provided by April Brothers, who manufacture the Cactus Micro.

OLED Graphics Libary

MQTT Library

Once everything is initialized and the device has connected to the MQTT broker over WiFi, the system waits for an incoming train schedule message. Every few seconds, the screen is updated with the new schedule data and periodically splash a brand page “IoL City Train Network”.

Train Schedule - IoL City Train Network

  1. /*** Internet of Lego – Train Schedule Display
  2. * This program connects to WiFi, utilizes MQTT and displays the local train schedule on an OLED screen
  3. * The OLED graphics library is slimmed down to only text for memory efficiency
  4. * https://github.com/greiman/SSD1306Ascii
  5. *
  6. * Hardware: Cactus Micro Rev2 – http://wiki.aprbrother.com/wiki/Cactus_Micro_Rev2
  7. * Written by: Cory Guynn with some snippets from public examples
  8. * 2016
  9. */
  10. // Global Variables
  11. unsigned long time; // used to limit publish frequency
  12. // OLED
  13. #include “SSD1306Ascii.h”
  14. #include “SSD1306AsciiAvrI2c.h”
  15. // 0X3C+SA0 – 0x3C or 0x3D
  16. #define I2C_ADDRESS 0x3C
  17. SSD1306AsciiAvrI2c oled;
  18. // ESP8266 WiFi
  19. #include
  20. #define PIN_ENABLE_ESP 13
  21. #define SSID “yourSSID”
  22. #define PASS “yourpassword”
  23. // MQTT Messaging
  24. #include
  25. ESP esp(&Serial1, &Serial, PIN_ENABLE_ESP);
  26. MQTT mqtt(&esp);
  27. boolean wifiConnected = false;
  28. #define mqttBroker “aws.internetoflego.com”
  29. #define mqttSub “/trainschedule/910GLONFLDS”
  30. String mqttMessage = “”;
  31. /*******************
  32. // Functions
  33. *******************/
  34. void wifiCb(void* response)
  35. {
  36. uint32_t status;
  37. RESPONSE res(response);
  38. if(res.getArgc() == 1) {
  39. res.popArgs((uint8_t*)&status, 4);
  40. if(status == STATION_GOT_IP) {
  41. wifiConnected = true;
  42. Serial.println(“WIFI CONNECTED”);
  43. oled.print(“WiFi Online: “);
  44. oled.println(SSID);
  45. mqtt.connect(mqttBroker, 1883, false);
  46. //or mqtt.connect(“host”, 1883); /*without security ssl*/
  47. } else {
  48. wifiConnected = false;
  49. mqtt.disconnect();
  50. oled.println(“WiFi OFFLINE”);
  51. }
  52. }
  53. }
  54. void mqttConnected(void* response)
  55. {
  56. Serial.println(“MQTT Connected”);
  57. oled.println(“MQTT Connected”);
  58. mqtt.subscribe(mqttSub); //or mqtt.subscribe(“topic”); /*with qos = 0*/
  59. mqtt.publish(“/news”, “OLED display is online”);
  60. }
  61. void mqttDisconnected(void* response)
  62. {
  63. oled.clear();
  64. Serial.println(“MQTT Disconnected”);
  65. }
  66. void mqttData(void* response)
  67. {
  68. RESPONSE res(response);
  69. Serial.println(“mqttTopic:”);
  70. String topic = res.popString();
  71. Serial.println(topic);
  72. oled.println(topic);
  73. Serial.println(“mqttMessage:”);
  74. mqttMessage = res.popString();
  75. Serial.println(mqttMessage);
  76. }
  77. void mqttPublished(void* response)
  78. {
  79. }
  80. void setup() {
  81. // OLED initilize
  82. oled.begin(&Adafruit128x64, I2C_ADDRESS);
  83. oled.setFont(Adafruit5x7);
  84. oled.clear();
  85. oled.println(“OLED online”);
  86. // Hardware Serial (for ESP8266) and Serial Concole initialization
  87. Serial1.begin(19200);
  88. Serial.begin(19200);
  89. esp.enable();
  90. delay(500);
  91. esp.reset();
  92. delay(500);
  93. while(!esp.ready());
  94. Serial.println(“Setup MQTT client”);
  95. if(!mqtt.begin(“TrainScheduleDisplay-LF”, “admin”, “Isb_C4OGD4c3”, 120, 1)) {
  96. Serial.println(“Failed to setup mqtt”);
  97. while(1);
  98. }
  99. Serial.println(“Setup MQTT lwt”);
  100. mqtt.lwt(“/lwt”, “offline”, 0, 0); //or mqtt.lwt(“/lwt”, “offline”);
  101. /*setup mqtt events */
  102. mqtt.connectedCb.attach(&mqttConnected);
  103. mqtt.disconnectedCb.attach(&mqttDisconnected);
  104. mqtt.publishedCb.attach(&mqttPublished);
  105. mqtt.dataCb.attach(&mqttData);
  106. /*setup wifi*/
  107. Serial.println(“Setup WiFi”);
  108. esp.wifiCb.attach(&wifiCb);
  109. esp.wifiConnect(SSID, PASS);
  110. Serial.println(“System Online”);
  111. }
  112. void loop() {
  113. esp.process();
  114. if (millis() > (time + 10000)) {
  115. time = millis();
  116. oled.clear();
  117. oled.set2X();
  118. oled.println(” IoL City “);
  119. oled.println(“”);
  120. oled.set1X();
  121. oled.println(” Train Network”);
  122. delay(2000);
  123. oled.clear();
  124. oled.println(mqttMessage);
  125. if(wifiConnected) {
  126. // publish stuff here
  127. }
  128. }
  129. }

Download Source Code: Gist

the original post is from http://www.internetoflego.com/train-schedule-display-2/

Share!
Tweet

Olva

About the author

Leave a Reply Cancel reply

You must be logged in to post a comment.

Category

  • Home
  • pcDuino
  • WiKi
  • Store
  • Distributors