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

    --mqtt-server=HOST     path to mqtt server [Default: 192.168.8.11]

NUMLEDS is the number of leds to output data for (--add-empty does not count in here)
TIMEFILE refers to a json file which contains all the dates where the bus
drives

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 paho.mqtt.client as mqtt

red = timedelta(minutes=2)
orange = timedelta(minutes=3)
yellow = timedelta(minutes=4)
green = timedelta(minutes=6)
maxtime = timedelta(minutes=15)
def next_date(now,times):
    # now = datetime.now()
    for time in times: #times are sorted
        h,m = [ int(i) for i in time.split(":") ]
        t = datetime.now().replace(hour=h,minute=m,second=0,microsecond=0)
        if (t - maxtime) < now < t:
            return t
    raise ValueError("Unable to find date for today")


def main():
    args = docopt(__doc__)
    numleds = int(args['NUMLEDS'])
    times = json.load(open(args['TIMEFILE']))
    mqtt_server = args["--mqtt-server"]
    last = []
    mq = mqtt.Client()
    mq.connect(mqtt_server,1883,60)
    mq.loop_start()
    val = 0.0
    step = 0.01
    while True:
        try:
            now = datetime.now()
            t = next_date(now,times)
            sys.stdout.write("{}:{} -> {}:{} ".format(now.hour,now.minute,t.hour,t.minute))
            ret = []
            if (t-red) < now < t:
                print("Red alert")
                ret = [[255,0,0]] * 4
            elif (t-orange) < now < t:
                print("orange")
                ret = [[255,128,0]] * 4
            elif (t-yellow) < now < t:
                print("yellow")
                ret = [[255,255,0]] * 4
            elif (t-green) < now < t:
                print("green")
                ret = [[0,255,0]] * 4
            else:
                print("blue")
                ret = [[0,0,255]] * 4
            mq.publish("/leds/nodemcu-switcher/set",json.dumps(ret))
        except ValueError:
            print("No bus for now, you will have to walk!")
            ret = calc_chain(3,val)
            ret.insert(0,[0,0,0])
            mq.publish("/leds/nodemcu-switcher/set",json.dumps(ret))
            val += step % 1
        sleep(1)

if __name__ == "__main__":
    main()