Skip to content

Commit

Permalink
Initial commit - includes CTA Bus tracker only at this time
Browse files Browse the repository at this point in the history
  • Loading branch information
Conway committed Jun 15, 2016
0 parents commit e081f86
Show file tree
Hide file tree
Showing 8 changed files with 329 additions and 0 deletions.
90 changes: 90 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
.hypothesis/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# IPython Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# dotenv
.env

# virtualenv
venv/
ENV/

# Spyder project settings
.spyderproject

# Rope project settings
.ropeproject
8 changes: 8 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
The MIT License (MIT)
Copyright (c) 2016 Jake Conway

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 changes: 24 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
chicagotransit
==============

A collection of wrappers to communicate with various chicago transit APIs and infosources.

Installation
------------

To install, use ``pip install chicagotransit``

Currently Supported
-------------------

- CTA Bustracker (Bustime)

Future Expansion
----------------

- CTA Traintracker
- Divvy Bikes (WIP)
- Pace Busses*
- Metrarail*

* if some sort of public API can be found
157 changes: 157 additions & 0 deletions chicagotransit/cta.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
import datetime
import errors
import requests
import xmltodict

_base_url = 'http://www.ctabustracker.com/bustime/api/v1/'

class BusTracker(object):

def __init__(self, key):
self.key = key

def _time_translation(time_str):
year = int(time_str[0:4])
month = int(time_str[4:6])
day = int(time_str[6:8])
hour = int(time_str[9:11])
minute = int(time_str[12:14])
second = int(time_str[15:17])
time = datetime.datetime(year=year, month=month, day=day, hour=hour, minute=minute, second=second)
return time

def time(self):
url = _base_url + 'gettime'
result = requests.get(url, params={'key':self.key})
xml = xmltodict.parse(result.text)
if 'tm' in xml['bustime-response'].keys():
time_str = xml['bustime-response']['tm']
return BusTracker._time_translation(time_str)
else:
error = xml['bustime-response']['error']['msg']
errors.error_handler(error)

def bus_by_id(self, vid):
url = _base_url + 'getvehicles'
result = requests.get(url, params={'key':self.key, 'vid':vid})
xml = xmltodict.parse(result.text)
if 'vehicle' in xml['bustime-response'].keys():
v_data = xml['bustime-response']['vehicle']
time = v_data['tmstmp']
latitude = v_data['lat']
longitude = v_data['lon']
heading = v_data['hdg']
pattern_id = v_data['pid']
route = v_data['rt']
destination = v_data['des']
pattern_dist = v_data['pdist']
speed = v_data['spd']
bus = BusTracker.Bus(vid, self, time, latitude, longitude, heading, pattern_id, pattern_dist, route, destination, speed)
return bus
else:
error = xml['bustime-response']['error']['msg']
errors.error_handler(error)

def routes(self, update=False):
if hasattr(self, 'bus_routes') and self.bus_routes != [] and update == False:
return self.bus_routes
url = _base_url + 'getroutes'
result = requests.get(url, params={'key':self.key})
xml = xmltodict.parse(result.text)
if 'error' in xml['bustime-response'].keys():
errors.error_handler(xml['bustime-response']['error']['msg'])
self.bus_routes = []
for resp in xml['bustime-response']['route']:
self.bus_routes.append(BusTracker.Route(resp['rt'], self, resp['rtnm']))
return self.bus_routes

class Bus(object):
def __init__(self, id, bt, time, latitude, longitude, heading, pattern_id, pattern_dist, route, destination, speed, delayed=False):
self.id = id
self.bt = bt
self.time = time
self.latitude = latitude
self.longitude = longitude
self.heading = heading
self.pattern_id = pattern_id
self.pattern_dist = pattern_dist
self.route = route
self.destination = destination
self.delayed = delayed
self.speed = speed

def update(self):
self = self.bt.bus_by_id(id)

def __str__(self):
return "id: {0}, rt {1}".format(self.id, self.route)

class Route(object):
def __init__(self, number, bt, description):
self.number = number
self.bt = bt
self.description = description

def __str__(self):
return str(self.number)

def busses(self, update=False):
url = _base_url + 'getvehicles'
result = requests.get(url, params={'key':self.bt.key, 'rt':self.number})
xml = xmltodict.parse(result.text)
if 'vehicle' in xml['bustime-response'].keys():
for resp in xml['bustime-response']:
vid = resp['vid']
time = resp['tmstmp']
latitude = resp['lat']
longitude = resp['lon']
heading = resp['hdg']
pattern_id = resp['pid']
route = resp['rt']
destination = resp['des']
pattern_dist = resp['pdist']
speed = resp['spd']
bus = BusTracker.Bus(vid, self, time, latitude, longitude, heading, pattern_id, pattern_dist, route, destination, speed)
self.busses.append(bus)
else:
error = xml['bustime-response']['error']['msg']
errors.error_handler(error)

def directions(self, update=False):
if hasattr(self, 'direction') and not update:
return self.direction
else:
self.direction = []
url = _base_url + 'getdirections'
result = requests.get(url, params={'key':self.bt.key, 'rt':self.number})
xml = xmltodict.parse(result.text)
self.direction = xml['bustime-response']['dir']
return self.direction

def stops(self, direction, update=False):
assert(direction in self.directions())
url = _base_url + 'getstops'
result = requests.get(url, params={'key':self.bt.key, 'rt':self.number, 'dir':direction})
xml = xmltodict.parse(result.text)
if hasattr(self, 'stop') and not update:
return self.stops
elif 'stop' in xml['bustime-response'].keys():
self.stop = []
for resp in xml['bustime-response']['stop']:
id = resp['stpid']
name = resp['stpnm']
latitude = resp['lat']
longitude = resp['lon']
self.stop.append(BusTracker.Stop(id, name, latitude, longitude, self.bt))
return self.stop
else:
error = xml['bustime-response']['error']['msg']
errors.error_handler(error)

class Stop(object):
def __init__(self, id, name, latitude, longitude, bt):
self.id = id
self.name = name
self.latitude = latitude
self.longitude = longitude
self.bt = bt
13 changes: 13 additions & 0 deletions chicagotransit/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
def error_handler(exception):
if exception == 'Invalid API access key supplied':
raise InvalidKeyException
elif exception == 'No data found for parameter':
raise NoDataFoundException
else:
raise Exception(exception)

class InvalidKeyException(Exception):
pass

class NoDataFoundException(Exception):
pass
2 changes: 2 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
xmltodict==0.10.2
requests
Empty file added setup.cfg
Empty file.
35 changes: 35 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from setuptools import setup, find_packages
from codecs import open
from os import path

here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()

with open('requirements.txt') as f:
requirements = f.read().splitlines()

setup(
name='chicagotransit',
version='0.1.0',
description='A package for interfacing with Chicago Transit APIs',
long_description=long_description,
url='https://github.com/conway/ChicagoTransit',
author='Jake Conway',
author_email='[email protected]',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Utilities',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Natural Language :: English'
],
keywords=['chicago', 'transit', 'wrapper', 'bus', 'train', 'cta', 'divvy'],
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
install_requires=requirements,
)

0 comments on commit e081f86

Please sign in to comment.