summaryrefslogtreecommitdiff
path: root/anzeige0/main.py
blob: c73e847835c5b20fe5e35547be6a5207f754cbac (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
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
#!micropython
print("Start main.py")
import json
import time
import machine
import socket
import micropython as mp

from nodemcu_gpio_lcd import GpioLcd
from machine import Pin, PWM
import network

backlight = PWM(Pin(12), freq=500, duty=200)

wlan = network.WLAN()

lcd = GpioLcd(rs_pin=Pin(16), enable_pin=Pin(5), 
        d4_pin=Pin(4), d5_pin=Pin(0), d6_pin=Pin(2), d7_pin=Pin(14), 
        num_lines=2, num_columns=16)

lcd.clear()
lcd.putstr("Verbinde mit:\n{}".format(wlan.config('essid')))
while not wlan.isconnected():
    continue
lcd.clear()
lcd.putstr("Verbunden")

HOST = b'www.localnet.cc'
HEADERS = b'Host: www.localnet.cc\r\nConnection: close\r\n\r\n'

displays = [
        { #          ################     ################   <- 16 chars
            "name": "Zusammenfassung " + "                ",
            "text": "I: ____ E: ____ " + "W: ____ßS: ____ß",
            "values" : [
                """SELECT sum("d4_count")*30 FROM "stromzaehler3" WHERE time > now() - 2m""",
                """SELECT sum("d1_count")*30 FROM "stromzaehler3" WHERE time > now() - 2m""",
                """SELECT last(value) FROM temp0 WHERE sensor = '28-8B-DC-E9-16-13-01-D5'""",
                """SELECT last(value) FROM temp0 WHERE sensor = '28-7F-69-16-17-13-01-A6'""",
                ]
            },
        { #          ################     ################   <- 16 chars
            "name": "Stromz\xe1hler     " + "   Heute        ",
            "text": "\xf6 Import  ____Wh" + "\xf6 Export  ____Wh",
            "values" : [
                "SELECT last(sum) FROM (SELECT sum(d4_count) FROM stromzaehler3 WHERE time > now() - 1d GROUP BY time(1d)  tz('Europe/Berlin'))",
                "SELECT last(sum) FROM (SELECT sum(d1_count) FROM stromzaehler3 WHERE time > now() - 1d GROUP BY time(1d)  tz('Europe/Berlin'))",
                ],
            },
        { #          ################     ################   <- 16 chars
            "name": "Heizung Solar   " + "                ",
            "text": "Von Dach: ____ß " + "Zum Dach: ____ß ",
            "values" : [
                "SELECT last(value) FROM temp0 WHERE sensor = '28-7F-69-16-17-13-01-A6'",
                "SELECT last(value) FROM temp0 WHERE sensor = '28-99-38-EB-16-13-01-22'",
                ]
            },
        { #          ################     ################   <- 16 chars
            "name": "BFT Rheinau     " + "                ",
            "text": "S95-E5:  __.___ " + "Diesel:  __.___ ",
            "values" : [
                """SELECT last(value) FROM "tankerkoenig.SP95-E5" WHERE "name" = 'Rheinau-Freistett - BFT - Freistett'""",
                """SELECT last(value) FROM "tankerkoenig.Diesel" WHERE "name" = 'Rheinau-Freistett - BFT - Freistett'""",
                ]},
            ]

def query_one(db, select):
    select_esc = select.replace(" ", "%20")
    select_esc = select_esc.replace("\"", "%22")
    addr = socket.getaddrinfo(HOST, 80)[0][-1]
    s = socket.socket()
    s.connect(addr)
    s.send(b'GET /grafana/api/datasources/proxy/3/query?db={}&q={}&epoch=ms\r\n'.format(db, select_esc))
    s.send(HEADERS)
    data = json.load(s)
    s.close()
    return data['results'][0]['series'][0]['values'][0][1]

current_display = 0
def update():
    global UPDATE_RUN, current_display, display, lcd

    lcd.move_to(0, 0)
    text = displays[current_display]["text"]

    s = ""
    cur = ""
    pos = 0
    i = 0
    while i<len(text):
        c = text[i]
        cur_added = False
        if c == '_' or ( len(cur) > 0 and c == '.' ):
            cur += c
            cur_added = True

        if len(cur) > 0 and (not cur_added or i == len(text) - 1):
            value_query = displays[current_display]["values"][pos]
            v = query_one("data", value_query)
            if isinstance(v, float):
                if "." in cur:
                    precision = len(cur) - cur.index(".") - 1
                else:
                    precision = 0
                fmt_string = "{{: >{}.{}f}}".format(len(cur), precision)
            elif isinstance(v, int):
                fmt_string = "{{: >{}d}}".format(len(cur))
            else:
                raise Exception("Wrong type: {}".format(type(v)))
            s += fmt_string.format(v)
            lcd.putstr(s)
            s = ""
            cur = ""
            pos += 1

        if not cur_added:
            s += c

        if not cur_added and i == len(text)-1:
            lcd.putstr(s)
            s = ""

        i += 1

    lcd.putstr(s)

last_update = 0

def schedule_update(timer=None, force=False):
    global last_update
    def ex(none):
        try:
            update()
        except Exception as e:
            lcd.clear()
            msg = "Error: {}".format(str(e)[0:(32-7)])
            lcd.putstr(msg)
            raise e

    now = time.ticks_ms()
    if force:
        last_update = now
        ex(None)
    elif now - last_update > 5000:
        last_update = now
        mp.schedule(ex, None)

timer = machine.Timer(-1)

def switch_display(none):
    global current_display, displays

    current_display += 1
    current_display %= len(displays)
    lcd.move_to(0,0)
    lcd.putstr(displays[current_display]['name'])

    # trigger update in 1s
    last_update = time.ticks_ms() - 4000

last_switch = 0
def switch_pressed(pin):
    global last_switch
    now = time.ticks_ms()
    if pin.value() == 0 and now - last_switch > 200:
        mp.schedule(switch_display, None)
        last_switch = now

switch = machine.Pin(13, machine.Pin.IN)
switch.irq(switch_pressed)

timer.init(period=500, mode=machine.Timer.PERIODIC, callback=schedule_update)

print("main.py finished")