summaryrefslogtreecommitdiff
path: root/stromzähler3/main.py
blob: 65499ffc328591b4d428998b39de43268a552968 (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
#!micropython
print("Start main.py")

import os
import machine
import socket
import time
import micropython as mp


HOST = config['CONFIG_INFLUXDB_HOST']
PORT = config['CONFIG_INFLUXDB_PORT']
PATH = config['CONFIG_INFLUXDB_PATH']

H_REQUEST = bytes('POST /%s HTTP/1.1\r\n' % PATH, 'utf8')
H_HOST = bytes('Host: %s\r\n' % HOST, 'utf8')
H_CONTENT_TYPE = bytes('Content-Type: application/x-www-urlencoded\r\n', 'utf8')
H_CONTENT_LENGTH = bytes('Content-Length: %s\r\n', 'utf8')
H_CONNECTION = bytes('Connection: close\r\n', 'utf8')
H_NL = bytes('\r\n', 'utf8')

def post(data):
    print('[%d] Send HTTP POST: %s. Response: ' % (time.ticks_ms(), data), end='')
    addr = socket.getaddrinfo(HOST, PORT)[0][-1]
    data = bytes(data, 'utf8')
    s = socket.socket()
    s.connect(addr)
    s.send(H_REQUEST)
    s.send(H_HOST)
    s.send(H_CONTENT_TYPE)
    s.send(H_CONTENT_LENGTH % len(data))
    s.send(H_CONNECTION)
    s.send(H_NL)
    s.send(data)

    first_data = s.recv(100)
    if first_data:
        line, *_ = first_data.split(b'\r\n')
        print(line, end='')
        while data:
            data = s.recv(100)
    s.close()
    print('')

d4_total = 0
d4_count = 0

d1_total = 0
d1_count = 0

def update(t):
    global d4_total, d4_count, d1_total, d1_count
    d4 = d4_count
    d1 = d1_count
    post('stromzaehler3 d4_count=%d,d4_total=%d,d1_count=%d,d1_total=%d' % (
        d4, d4_total, d1, d1_total))
    d4_count -= d4
    d1_count -= d1

timer1 = machine.Timer(-1)
timer1.init(period=10000, mode=machine.Timer.PERIODIC, callback=update)

def persist(t):
    write_persistent_int("d4_total.txt", d4_total)
    write_persistent_int("d1_total.txt", d1_total)


# Import
def cb_d4(p):
    global d4_total, d4_count
    v = p.value()
    if v != 1: # skip rising edge
        d4_total += 1
        d4_count += 1

d4 = machine.Pin(2, machine.Pin.IN, pull=machine.Pin.PULL_UP)
d4.irq(handler=lambda p: mp.schedule(cb_d4, p))

# Export
def cb_d1(p):
    global d1_total, d1_count
    v = p.value()
    if v != 1: # skip rising edge
        d1_count += 1
        d1_total += 1

d1 = machine.Pin(5, machine.Pin.IN)
d1.irq(handler=lambda p: mp.schedule(cb_d1, p))

# Pumpe
d3_last_value = 0

def cb_d3(p):
    global d3_last_value
    print('[%d] %s = %d' % (time.ticks_ms(), repr(p), p.value()))
    v = 1 - p.value()
    if v != d3_last_value:
        post('stromzaehler3.Pumpe Status=%s' % v)
        d3_last_value = v

d3 = machine.Pin(0, machine.Pin.IN, pull=machine.Pin.PULL_UP)
d3.irq(handler=lambda p: mp.schedule(cb_d3, p))

print("main.py finished")