-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmeinbus.py
294 lines (260 loc) · 9.94 KB
/
meinbus.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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
from pprint import pprint
from flask import Flask, render_template_string, jsonify
from datetime import datetime, timezone
import requests
import os
app = Flask(__name__)
BASE_URL = "https://transport.opendata.ch/v1/"
# init logging
import logging
logging.basicConfig(level=logging.INFO)
# syslog rfc 5424 format
log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
logging.basicConfig(format=log_format)
logger = logging.getLogger(__name__)
# stdout handler
stdout_handler = logging.StreamHandler()
stdout_handler.setFormatter(logging.Formatter(log_format))
logger.addHandler(stdout_handler)
# Custom filter to format datetime string to hh:mm:ss
@app.template_filter("format_time")
def format_time(value):
if value is None:
logger.error("Error: value is None no prediction available")
return "N/A" # Return a default value or handle the error
dt = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S%z")
return dt.strftime("%H:%M")
# Custom filter to calculate minutes until departure
@app.template_filter("minutes_until")
def minutes_until(value):
if value is None:
logger.error("Error: value is None no prediction available")
return "N/A" # Return a default value or handle the error
departure_time = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S%z")
now = datetime.now(timezone.utc)
delta = departure_time - now
total_seconds = int(delta.total_seconds() // 60)
return total_seconds
@app.route("/healthz")
def healthz():
return jsonify(status="ok"), 200
@app.route("/readiness")
def readiness():
# Add any necessary checks to determine if the app is ready
return jsonify(status="ready"), 200
@app.route("/")
def index():
stop_names = ["Oberwiesenstrasse"]
station_coordinates = {
"Oberwiesenstrasse": {"lat": 47.410473, "lon": 8.532815},
"Birchdörfli": {"lat": 47.3780, "lon": 8.5400},
"Brunnenhof": {"lat": 47.4000, "lon": 8.5500},
"Bad Allenmoos": {"lat": 47.4100, "lon": 8.5600},
}
logger.info(f"Stop names: {stop_names}")
departures = {}
for stop_name in stop_names:
data = get_real_time_data(stop_name)
if data:
departures[stop_name] = data["stationboard"]
disruptions = [] # get_disruptions()
current_time = datetime.now().strftime("%H:%M:%S")
connections = get_connection(from_station="Zürich, Oberwiesenstrasse", to_station="Zürich, Luchswiesen")
html = """
<html>
<head>
<title>Bus Station Abfahrten</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<meta http-equiv="refresh" content="30">
<link rel="manifest" href="/static/manifest.json">
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/static/service-worker.js')
.then(function(registration) {
console.log('Service Worker registered with scope:', registration.scope);
}).catch(function(error) {
console.log('Service Worker registration failed:', error);
});
}
</script>
<style>
body {
background-color: #000;
color: #FFF;
font-size: 28px;
}
.light-mode body {
background-color: #FFF;
color: #000;
}
.table td, .table th {
color: #FFA500;
border: 0;
border-collapse: collapse;
}
.table {
background-color: #000;
}
.light-mode .table {
color: #FFF;
}
table {
font-family: Arial, sans-serif;
font-size: 30px;
color: #333;
background-color: black;
}
.light-mode table {
background-color: white;
color: #FFF;
}
th, td {
padding: 0px;
text-align: left;
border: 0;
border-collapse: collapse;
}
</style>
</head>
<body>
{% for stop_name, stop_departures in departures.items() %}
Abfahrt - {{ stop_name }} - {{ current_time }}
<div class="table-container">
<table class="table is-fullwidth has-text-warning">
<thead class="has-background-black">
<tr>
<th>Linie</th>
<th>Nach</th>
<th>Abfahrt</th>
<th>~</th>
<th>in ca.</th>
</tr>
</thead>
<tbody>
{% for departure in stop_departures %}
<tr>
{% set line = departure['number']|int %}
{% if line == 11 %}
{% set color = 'primary' %}
{% elif line == 62 %}
{% set color = 'link' %}
{% elif line == 61 %}
{% set color = 'info' %}
{% elif line == 32 %}
{% set color = 'warning' %}
{% else %}
{% set color = 'white' %}
{% endif %}
<td><span class="tag is-large is-{{ color }}">{{ line }}</td>
<td>{{ departure['to'] }}</td>
<td>{{ departure['stop']['departure'] | format_time }}</td>
<td>{{ departure['stop']['prognosis']['departure'] | format_time }}</td>
{% set minutes_until = departure['stop']['departure'] | minutes_until %}
{% if minutes_until <= 0 %}
<td> <i class='fa fa-bus'></i> </td>
{% else %}
<td>{{ minutes_until }}' </td>
{% endif %}
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endfor %}
Verbindungen - Oberwiesenstrasse nach Luchswiesen
<div class="table-container">
{% if connections and connections['connections'] %}
<table class="table is-fullwidth has-text-warning">
<thead class="has-background-black">
<tr>
<th>Linie</th>
<th>Abfahrt</th>
<th>Ankunft</th>
<th>Dauer</th>
</tr>
</thead>
<tbody>
{% for connection in connections['connections'] %}
<tr>
<td><i class='fa fa-bus'></i> {{ connection['sections'][0]['journey']['number'] }}</td>
<td>{{ connection['from']['departure'] | format_time }}</td>
<td>{{ connection['to']['arrival'] | format_time }}</td>
<td>{{ connection['duration'] }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>No connections available currently.</p>
{% endif %}
</div>
<div class="tags has-addons">
<span class="tag">Author</span>
<span class="tag is-primary">Bigg01</span>
</div>
</body>
</html>
"""
return render_template_string(
html,
departures=departures,
disruptions=disruptions,
station_coordinates=station_coordinates,
current_time=current_time,
connections=connections,
)
def get_real_time_data(stop_name):
endpoint = f"{BASE_URL}locations"
params = {"query": stop_name, "type": "station"}
response = requests.get(endpoint, params=params)
if response.status_code == 200:
data = response.json()
if data["stations"]:
station_id = data["stations"][0]["id"]
return get_departures(station_id)
else:
logger.error("No station found")
return None
else:
print(f"Error: {response.status_code}")
return None
def get_departures(station_id):
endpoint = f"{BASE_URL}stationboard"
params = {"id": station_id, "limit": 5}
response = requests.get(endpoint, params=params)
if response.status_code == 200:
return response.json()
else:
logger.error(f"Error: {response.status_code}")
return None
def get_disruptions():
endpoint = f"{BASE_URL}disruptions"
response = requests.get(endpoint)
if response.status_code == 200:
return response.json()["disruptions"]
else:
logger.error(f"Error: {response.status_code}")
return []
def get_connection(from_station, to_station):
endpoint = f"{BASE_URL}connections"
current_time = datetime.now().strftime("%H:%M")
current_date = datetime.now().strftime("%Y-%m-%d")
params = {
"from": from_station,
"to": to_station,
"date": current_date,
"time": current_time,
"transportations": "bus",
"limit": 3,
}
response = requests.get(endpoint, params=params)
if response.status_code == 200:
result = response.json()
return result
else:
logger.error(f"Error: {response.status_code}")
return None
if __name__ == "__main__":
logger.info("Starting MeinBus app")
app.run(debug=True, host="0.0.0.0", port=5000)