This repository has been archived by the owner on Apr 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
pyrenfe.py
194 lines (150 loc) · 5.63 KB
/
pyrenfe.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
#
# Check the trains schedule (Renfe, Spain)
# ===================================================
#
# Provides a class to check the timetable of the
# trains in Spain.
#
# Jose Ignacio Galarza
#
import argparse
from datetime import datetime, timedelta, time
import re
import sys
from lxml import etree
import requests
# Global information
__uname__ = 'pyrenfe'
__long_name__ = 'Train checker (Cercanias Renfe, Spain)'
__version__ = '1.0'
__author__ = 'Jose Ignacio Galarza'
__email__ = '[email protected]'
__url__ = 'http://github.com/igalarzab/pyrenfe'
__license__ = 'MIT'
class RenfeRoute(object):
'A renfe route between two stations'
# API URL (XML)
URL = 'http://horarios.renfe.com/cer/horarios/horarios.jsp'
def __init__(self, rfrom, rto):
'Initialize the route between an origin an a destine'
self.rfrom = rfrom
self.rto = rto
def timetable(self, day=None, initialHour=0, finalHour=24):
'Show the timetable of the renfe route'
if not day:
day = datetime.now().strftime('%Y%m%d')
if not re.match(r'^\d{8}$', day):
raise ValueError('Incorrect date format, must be %Y%m%d')
if initialHour < 0 or initialHour > 24 or \
finalHour < 0 or finalHour > 24:
raise ValueError('Time values must be between 0 and 23')
return self._downloadTimetable(day, initialHour, finalHour)
def nextTrain(self, quantity=1, margin=5):
'Show the next *quantity* trains, with *margin* minutes'
now = datetime.now()
today = now.strftime('%Y%m%d')
hour = now.strftime('%H')
# Calculates the limit range to search
limitMinute = (now.minute + margin) % 60
limitHour = now.hour if (now.minute + margin) < 60 else (now.hour + 1)
nowLimit = time(limitHour, limitMinute)
timetable = self._downloadTimetable(today, hour)
for i in range(len(timetable)):
if timetable[i]['leave'] > nowLimit:
return timetable[i:i + quantity]
return None
def _downloadTimetable(self, day, initialHour=0, finalHour=24):
'Download the timetable from renfe.com'
params = {
'nucleo': '10',
'o': self.rfrom,
'd': self.rto,
'df': day,
'ho': initialHour,
'hd': finalHour
}
req = requests.get(RenfeRoute.URL, params=params)
timetable = etree.fromstring(req.content)
trains_timetable = []
if timetable[0].text.strip() == 'Datos no disponibles.':
raise ValueError('Invalid origin or destine')
for t in timetable[3]:
duration = [int(x) for x in t[3].text.split(':')]
trains_timetable.append({
'train': t[0].text.strip(),
'leave': time(*[int(x) for x in t[1].text.split(':')]),
'arrive': time(*[int(x) for x in t[2].text.split(':')]),
'time': timedelta(*duration),
})
return trains_timetable
class TimetablePrinter(object):
'Pretty print timetables'
@staticmethod
def as_table(timetable):
'Print the timetable as a table'
print('-' * 41)
print('| Leaves | Arrives | Line |')
print('-' * 41)
for tt in timetable:
print('|%(leave)10s |%(arrive)10s |%(train)08s |' % tt)
print('-' * 41)
@staticmethod
def as_text(timetable):
'Print the timetable as human text'
for tt in timetable:
print('Next train leaves at %(leave)s and '
'arrives at %(arrive)s (line %(train)s)' % tt)
@staticmethod
def as_notification(timetable):
'Raise a notification with pynotify'
pass # TODO: Use pynotify
def create_parser():
'Parse the program arguments'
pparser = argparse.ArgumentParser(description='Check Renfe schedule')
pparser.add_argument('--version',
action='version',
version='%s %s' % (__uname__, __version__))
pparser.add_argument('-o', '--origin',
dest='origin',
required=True,
metavar='RENFE_ID',
type=int,
help='origin renfe station (id, a number)')
pparser.add_argument('-d', '--destine',
dest='destine',
required=True,
metavar='RENFE_ID',
type=int,
help='destine renfe station (id, a number)')
action = pparser.add_mutually_exclusive_group()
action.add_argument('-t', '--timetable',
dest='timetable',
action='store_true',
help='show full timetable instead of the next train')
action.add_argument('-p', '--printer',
dest='printer',
choices=['table', 'text'],
default='text',
help='how to print the info (default: text)')
return pparser
def main():
'Main func'
parser = create_parser()
args = parser.parse_args()
rr = RenfeRoute(args.origin, args.destine)
try:
if args.timetable:
trains = rr.timetable()
else:
trains = rr.nextTrain()
except ValueError as e:
print(e)
sys.exit(-1)
if args.printer == 'table' or args.timetable:
TimetablePrinter.as_table(trains)
else:
TimetablePrinter.as_text(trains)
if __name__ == '__main__':
main()
# vim: ai ts=4 sts=4 et sw=4