Skip to content

Commit cbc18a0

Browse files
committed
Moved network retry handling into get_prediction
1 parent e03650f commit cbc18a0

File tree

1 file changed

+25
-15
lines changed

1 file changed

+25
-15
lines changed

muniled.py

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -35,21 +35,14 @@ def main(args):
3535
led_strip.all_off()
3636
try:
3737
while True:
38-
try:
39-
update(led_strip)
40-
except urllib2.URLError, e:
41-
print e.reason
42-
pass
43-
except:
44-
raise
45-
finally:
46-
time.sleep(5.0)
38+
update(led_strip)
39+
time.sleep(5.0)
4740
except:
4841
led_strip.all_off()
4942
raise
5043

5144

52-
def get_predictions(route, stop_id):
45+
def get_predictions(route, stop_id, led_strip):
5346
base_url = 'http://webservices.nextbus.com/service/publicXMLFeed'
5447
params = {
5548
'command': 'predictions',
@@ -58,9 +51,20 @@ def get_predictions(route, stop_id):
5851
's': stop_id,
5952
'useShortTitles': 'true'
6053
}
61-
response = urllib2.urlopen('{url}?{params}'.format(
62-
url=base_url,
63-
params=urllib.urlencode(params)))
54+
55+
# attempt to fetch and retry on error after a pause
56+
while True:
57+
try:
58+
response = urllib2.urlopen('{url}?{params}'.format(
59+
url=base_url,
60+
params=urllib.urlencode(params)))
61+
break
62+
except urllib2.URLError, e:
63+
print e.reason
64+
dim(led_strip)
65+
time.sleep(5.0)
66+
pass
67+
6468
dom = minidom.parse(response)
6569
predictions = dom.getElementsByTagName('prediction')
6670
return [int(p.attributes['minutes'].value) for p in predictions]
@@ -70,11 +74,11 @@ def update(led_strip=None):
7074
line = [False for i in range(led_strip.leds)]
7175

7276
# inbound
73-
for prediction in get_predictions('N', 3915):
77+
for prediction in get_predictions('N', 3915, led_strip):
7478
line[80 - prediction - 1] = True
7579

7680
# outbound
77-
for prediction in get_predictions('N', 3914):
81+
for prediction in get_predictions('N', 3914, led_strip):
7882
line[80 + prediction] = True
7983

8084
# set train leds
@@ -91,6 +95,12 @@ def update(led_strip=None):
9195
# Update the strip
9296
led_strip.update()
9397

98+
def dim(led_strip):
99+
# dim all the leds a little
100+
# TODO
101+
pass
102+
103+
94104
if __name__ == "__main__":
95105
parser = argparse.ArgumentParser(description='Muni trains on a LED strip.')
96106
parser.add_argument('-d', '--display', choices=['led', 'console'],

0 commit comments

Comments
 (0)