diff options
author | Yves Fischer <yvesf-git@xapek.org> | 2018-08-02 17:21:14 +0200 |
---|---|---|
committer | Yves Fischer <yvesf-git@xapek.org> | 2018-08-02 17:59:06 +0200 |
commit | 74973624deed05d1cc8b297fb1d877cadad50969 (patch) | |
tree | 8304000f99a4dc0e0fad263fc9928d8e5ad6366c /laermsensor0/main.py | |
download | esp8266-74973624deed05d1cc8b297fb1d877cadad50969.tar.gz esp8266-74973624deed05d1cc8b297fb1d877cadad50969.zip |
Diffstat (limited to 'laermsensor0/main.py')
-rw-r--r-- | laermsensor0/main.py | 79 |
1 files changed, 79 insertions, 0 deletions
diff --git a/laermsensor0/main.py b/laermsensor0/main.py new file mode 100644 index 0000000..b46afdb --- /dev/null +++ b/laermsensor0/main.py @@ -0,0 +1,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') |