Linux Format

Checking train times

Les Pounder shows you how to use a web API to retrieve data and then use it at the heart of your own monitoring projects, this one train times!

- Les Pounder is a freelance maker who works with organisati­ons such as the Raspberry Pi Foundation to promote maker skills.

Les Pounder shows us how to use a web API to retrieve data and use it for a project.

The Applicatio­n Programmin­g Interface (API) is an important part of coding. We can use these to power data-driven projects such as displaying weather and news, and in LXF251 we used one to track the Internatio­nal Space Station. But learning how to use an API can be tricky, so in this project we’ll see how to use the free Transport API to create an applicatio­n that tells us departing train times, platforms and operators – using a voice powered by Google’s Text to Speech service.

Getting an API key

To use the Transport API service we need to sign up for a free account at https://developer.transporta­pi. com. Write down your App ID and Key; these are personal to you and identify that you are using the service. Keep them safe and do not share them. In order to use the keys in our code, open the Mu Python editor and save a file called secrets.py. In this file we’ll save two variables, our App ID and Key. app_id = “Your APP ID Goes here” api_key = “Your Key goes here”

Save the file before moving on.

We need to install two Python libraries for this project: gtts for Google Text to Speech, and vlc, which we use for media playback. To install, open a terminal and type:

$ sudo pip3 install gtts python-vlc

Using the Python editor we create a new file, and then save it as get_train_data.py. Remember to save this often!

Our code starts by importing a series of libraries which provide extra features to our code. The first is called requests , which enables us to receive and send data over HTTP. We import vlc to play the audio using the VLC player, now installed as standard on Raspbian. Then we import the sleep function from the time library, the GTTS class from the gtts library and a library called secrets, which we created earlier to contain our API details. Lastly we import datetime and date from the datetime library to get the time and date. import requests import vlc from time import sleep from gtts import GTTS from secrets import * from datetime import datetime, date

To get the current time and date for our train details, we create two variables, current_time and current_ date . To get the current time we use the datetime library and convert the time to a string. But the returned time is too precise, going down to fractions of a second. So in the second line below we use string slicing to extract the hours and minutes and store them in the variable.

current_time = str(datetime.now().time()) current_time = current_time[0:5]

To get the current date in YYYY-MM-DD format, we call the date class and ask it for today’s date, saving this to the variable.

current_date = str(date.today())

The last variable in this section is our train station code. This is the code used by rail companies to identify a station. You can find your station via National Rail Enquiries at www.nationalra­il.co.uk/stations_ destinatio­ns/default.aspx; here we’re using Blackpool North (BPN).

station = “BPN”

In order to get the train data from Transporta­pi, we need to use a carefully crafted web address ( url ) that will get the trains from our station at the current time and date. It will also use our app ID and key. You will see in the URL that there are places where we automatica­lly insert this data from variables in our code.

url = “https://transporta­pi.com/v3/uk/train/ station/”+station+”/”+current_date+”/”+current_ time+”/timetable.json?app_id=”+app_id+”&app_ key=”+api_key+”&train_status=passenger”

With the URL ready we can now use requests to get the data from the URL and save it as an object called r. r = requests.get(url)

The next line checks for the correct response in the r object. If it exists the code will run, else it will fail and skip the code and go to the end. But in this case the code works, so the next three lines trigger the VLC media player, loading the audio file bingbong.mp3 for train station chimes. It plays the file and then pauses for 4.2 seconds (the length of the audio). if r : media = vlc.mediaplaye­r(“bingbong.mp3”) media.play() sleep(4.2)

Moving into more complex code, we use a for loop to iterate over every train departure from our chosen station. For this we use len() to find the number of trains leaving from the returned data. As the returned data is in JSON format, Python treats it just like a dictionary, so we tell Python to look for the ‘departures’ , ‘all’ keys as our source.

for i in range(len(r.json()[‘departures’][‘all’])): Inside the for loop we have four lines of code that look rather intimidati­ng, so let’s go through them step by step. The first line sets the destinatio­n of our train. In the returned JSON data we have a number of keys that enable us to get values for specific pieces of informatio­n. So we ask for all departures; the [i] refers to our for loop which keeps looping until every departure has been listed. The last key is the destinatio­n for that train. So using these keys we get the exact station that our train is heading to.

destinatio­n = (r.json()[‘departures’][‘all’][i] [‘destinatio­n_name’])

The next three lines repeat this pattern, but the final key covers the departure time, platform and who the operator is. This data is then saved to a correspond­ing variable for later use. departure = (r.json()[‘departures’][‘all’][i] [‘aimed_departure_time’]) platform = (r.json()[‘departures’][‘all’][i] [‘platform’]) operator_name = (r.json()[‘departures’][‘all’][i] [‘operator_name’])

So what do we do with this data? Well first, for debug purposes we print the data to the screen. This is one really long sentence made up of written sections and our variables ( departure , destinatio­n , platform ,

operator_name ) joined together.

print(“at “+departure+” the train to “+destinatio­n+” will depart from platform “+platform+”. This service is provided by “+operator_ name)

We now create an object called tts and inside of this we instruct GTTS to convert the long sentence into speech. At the end of the line we can choose the speech language. Here we have chosen American English ( en-us ) as it sounds more natural. tts = GTTS(“AT “+departure+” the train to “+destinatio­n+” will depart from platform “+platform+”. This service is provided by “+operator_ name, lang=”en-us”)

To save the speech we instruct tts to save as

announce.mp3 in the same directory as our code.

tts.save(“announce.mp3”)

To play the audio we use VLC in the same way as the chimes earlier – but this time we add a 10-second delay so that there is enough time for the audio to play.

media = vlc.mediaplaye­r(“announce.mp3”) media.play() sleep(10)

The last section of code is our else condition. This is the code which runs if there is no data to read. It will just print that there has been an error.

else:

print(“there has been an error”)

Great work! In this project we have learned how to use a web API to provide data for an applicatio­n.

 ??  ?? You may see errors in the Python shell, but fear not – these will not break the project but act as warnings for audio playback on Raspbian.
You may see errors in the Python shell, but fear not – these will not break the project but act as warnings for audio playback on Raspbian.
 ??  ??
 ??  ?? The Transport API is a great one with which to start learning, and it can provide data for many projects.
The Transport API is a great one with which to start learning, and it can provide data for many projects.

Newspapers in English

Newspapers from Australia