summaryrefslogtreecommitdiff
path: root/laermsensor0/main.py
blob: b46afdbef1add4a410b59a39c37437b01a97e106 (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
#!micropython
print('Start main.py')
import socket
from micropython import const, schedule
import network
import machine

w = network.WLAN()

print("Waiting for WLAN")
while not w.isconnected():
    machine.idle()

print("WLAN found")

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

UTF_8 = 'utf8'
HTTP_REQUEST = bytes('POST /%s HTTP/1.1\r\n' % PATH, UTF_8)
HTTP_HOST = bytes('Host: %s\r\n' % HOST, UTF_8)
HTTP_CONTENT_TYPE = bytes('Content-Type: application/x-www-urlencoded\r\n', UTF_8)
HTTP_CONTENT_LENGTH = bytes('Content-Length: %s\r\n', UTF_8)
HTTP_CONNECTION = bytes('Connection: close\r\n', UTF_8)
HTTP_NL = bytes('\r\n', UTF_8)

def post(data):
    print('Send HTTP POST: %s' % data)
    addr = socket.getaddrinfo(HOST, PORT)[0][-1]
    data = bytes(data, UTF_8)
    s = socket.socket()
    s.connect(addr)
    s.send(HTTP_REQUEST)
    s.send(HTTP_HOST)
    s.send(HTTP_CONTENT_TYPE)
    s.send(HTTP_CONTENT_LENGTH % len(data))
    s.send(HTTP_CONNECTION)
    s.send(HTTP_NL)
    s.send(data)

    first_data = s.recv(100)
    if first_data:
        line, *_ = first_data.split(HTTP_NL)
        print(line)
        while data:
            data = s.recv(100)
    s.close()

from machine import Timer, ADC
CONVERT = ( 1024.0 * 3.3 ) / 1000.0 # convert to decibel
values = []

def update(args):
    (v_max, v_min, v_mean) = args
    post('laermsensor0 max=%s,min=%s,mean=%s' % (v_max, v_min, v_mean))

def process_adc(t):
    global adc
    global values

    if len(values) == 50:
        v_max = max(values) / CONVERT
        v_min = min(values) / CONVERT
        v_mean = (sum(values) / 50.0) / CONVERT
        schedule(update, (v_max, v_min, v_mean))
        values = []
    else:
        values.append(adc.read())

adc = ADC(0)
timer = Timer(-1)
timer.init(period=100, mode=Timer.PERIODIC, callback=process_adc)

def disable():
    global timer
    timer.deinit()

print('main.py finished')