This is a very fast overview of how to work with Kingston's realtime transit data.
Before we start, you will need to download/install the gtfs-realtime-bindings
package using pip
.
# commands preceded with an exclamation point are run on your system's command line
!pip3 install --user gtfs-realtime-bindings
Now that we have the package, let's load it and do a quick example. In this case we will use the vehicle positions data, but there are service alerts and trip updates as well.
from google.transit import gtfs_realtime_pb2
import requests
feed = gtfs_realtime_pb2.FeedMessage()
# requests will fetch the results from a url, in this case, the positions of all Kingston's buses
response = requests.get('http://kingston.metrolinx.tmix.se/gtfs-realtime/vehicleupdates.pb')
feed.ParseFromString(response.content)
print('There are {} buses in the dataset.'.format(len(feed.entity)))
# looking closely at the first bus
bus = feed.entity[0]
bus
# bus is a special datatype
print(type(bus))
# you can use dot notation to get individual pieces of data
print('bus ID:', bus.id, '\n')
# nested pieces of data just needs additional dots
bus.vehicle.position
bus.vehicle.position.speed
Alternatively, if you'd rather use the data as a dict, it might be worth looking into the protobuf3-to-dict
package.
!pip3 install --user protobuf3-to-dict
from protobuf_to_dict import protobuf_to_dict
# convert to dict from our original protobuf feed
buses_dict = protobuf_to_dict(feed)
type(buses_dict)
# get our first bus
bus_again = buses_dict['entity'][0]
bus_again
# We can then use the bus data just as we would a normal dict.
# Get the speed for example
bus_again['vehicle']['position']['speed']