Skip to content
Snippets Groups Projects
bus.py 2.09 KiB
Newer Older
Kasalehlia's avatar
Kasalehlia committed
import re
import requests
import xml.etree.ElementTree as ET
from datetime import datetime
from pystache import render
from time import sleep

CITY = 'Braunschweig';
STOPS = ['Ludwigstraße', 'Hamburger Straße'];
ENTRIES = 6;

def run(emit, log_err):
    templates = dict()
    for name in ['inner','outer']:
        with open('modules/bus/{}.mustache'.format(name), 'r') as f:
            templates[name] = f.read()
    emit(render(templates['outer'], [normalize_stop(s) for s in STOPS]))
    while True:
        for stop in STOPS:
            try:
                ns = normalize_stop(stop)
                deps = get_data(stop, ENTRIES)
                ctx = {'stop': stop, 'normalizedStop': ns, 'deps': deps}
                emit(render(templates['inner'], ctx), outlet=ns)
            except Exception as e:
                log_err(e)
        sleep(60)

def fetch_data(stop):
    url = "http://62.154.206.87/efaws2/default/XML_DM_REQUEST?sessionID=0&requestID=0&language=de&useRealtime=1&coordOutputFormat=WGS84[DD.ddddd]&locationServerActive=1&mode=direct&dmLineSelectionAll=1&depType=STOPEVENTS&useAllStops=1&command=null&type_dm=stop&name_dm={} {}&mId=efa_rc2".format(CITY, stop);
    r = requests.get(url)
    return r.text

def get_data(stop, count):
    t = ET.fromstring(fetch_data(stop))
    deps = t.find('itdDepartureMonitorRequest').find('itdDepartureList')
    out = []
    for dep in list(deps)[:count]:
        line = dep.find('itdServingLine')
        time = dep.find('itdDateTime').find('itdTime')
        out.append({
            'line': line.get('symbol'),
            'renderedLine': render_line(line.get('symbol')),
            'dir': line.get('direction').replace(CITY, '').strip(),
            'platform': dep.get('platform'),
            'hour': time.get('hour').zfill(2),
            'minute': time.get('minute').zfill(2)
        })
    return out

def render_line(line):
    image = ''
    if len(line) < 3:
        image = 'tram.svg'
    else:
        image = 'bus.svg'
    return '<img src="/modules/bus/{}"> {}'.format(image, line)

def normalize_stop(stop):
    return re.sub('[^a-zA-Z0-9_]', '', stop)