summaryrefslogtreecommitdiffstats
path: root/ampel.py
blob: b74814aafe1d822c9a423e2f178dcd7644963b6c (plain)
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
#! /usr/bin/env python3
#! nix-shell -i python3 -p python3 python35Packages.docopt python35Packages.paho-mqtt
""" usage: ampel [options] NUMLEDS

    --mqtt-server=HOST     path to mqtt server [Default: 192.168.8.11]
    --no-mqtt              disable mqtt connections for debugging

NUMLEDS is the number of leds to output data for (--add-empty does not count in here)

13         22   24   26   28
|-----------|----|----|----|
BLUE       GR   YEL  RED  BLUE
           EEN  LOW
"""
from docopt import docopt
from fade import calc_chain
import time
from time import sleep
import json
import sys
from datetime import datetime, timedelta
import requests
import logging as log
log.basicConfig(level=log.DEBUG)

import paho.mqtt.client as mqtt

thalesplatz = "5003035"
ditzingen = "5007000"

red = timedelta(minutes=2)
orange = timedelta(minutes=3)
yellow = timedelta(minutes=4)
green = timedelta(minutes=6)
maxtime = timedelta(minutes=15)


def fetch_data():
    from datetime import datetime as dt
    from vvs_efa import VVS_EFA
    efa = VVS_EFA.EFA()
    now = dt.now()
    conns = efa.get_next_connections(
                        "Ditzingen Thalesplatz",
                        "Hauptbahnhof (tief)",
                        now,
                        True)
    for dep in conns:
        if now < dep.time_of_departure:
            return dep.time_of_departure


def main():
    args = docopt(__doc__)
    numleds = int(args['NUMLEDS'])
    mqtt_server = args["--mqtt-server"]
    no_mqtt = args["--no-mqtt"]
    t = fetch_data()
    log.error(t)
    if not no_mqtt:
        log.info("Starting MQTT")
        mq = mqtt.Client()
        mq.connect(mqtt_server,1883,60)
        mq.loop_start()
        pub = lambda topic,data: mq.publish(topic,data)
    else:
        pub = lambda topic,data: log.info("topic: {}\ndata: {}".format(topic,data))

    val = 0.0
    step = 0.01
    oldstate = state = None
    while True:
        ret = []
        now = datetime.now()


        if now > t:
            t = fetch_data()

        delta = t - now
        deltastr = str(delta).split('.', 2)[0]

        if not ( (t - maxtime) < now < t):
            log.error("Bus too far away - {}".format(deltastr))
            ret = calc_chain(3,val)
            ret.insert(0,[0,0,0])
            pub("/leds/nodemcu-switcher/set",json.dumps(ret))
            val += step % 1
        else:
            log.info("{}:{:02d} -> {}:{:02d} delta: {}".format(
                now.hour,now.minute,t.hour,t.minute,deltastr))
            if (t-red) < now < t:
                state = "red"
                ret = [[255,0,0]] * 4
            elif (t-orange) < now < t:
                state = "orange"
                ret = [[255,128,0]] * 4
            elif (t-yellow) < now < t:
                state = "yellow"
                ret = [[255,255,0]] * 4
            elif (t-green) < now < t:
                state = "green"
                ret = [[0,255,0]] * 4
            else:
                state = "blue"
                ret = [[0,0,255]] * 4
            if oldstate != state:
                oldstate = state
                pub("/leds/nodemcu-switcher/set",json.dumps(ret))
        sleep(1)

if __name__ == "__main__":
    main()