uPyLibs/main.py

71 lines
2.0 KiB
Python
Raw Normal View History

2018-05-31 15:04:58 +01:00
import uPyConfig
import init_sample
hw = uPyConfig.esp8266(variant='d1-r2')
#print family, variant and IP address (using oled, if available on-board)
init_sample.init_sample(hw)
# Main app
from uPySensor import LM75A, SHT21
thsen=SHT21(hw.i2c.bus)
tsen=LM75A(hw.i2c.bus)
json={
'sht21_t': '{"temperature":"%0.3f"}',
'sht21_h': '{"humidity":"%0.3f"}',
'sht21': '{"temperature":"%0.3f","humidity":"%0.3f"}',
'lm75a_t': '{"temperature":"%0.1f"}',
'lm75a': '{"temperature":"%0.1f"}',
}
json_all='{"sht21":{"temperature":"%0.3f","humidity":"%0.3f"},"lm75a":{"temperature":"%0.1f"}}'
def header():
return "HTTP/1.1 200 OK\r\n" \
"Content-Type: application/json\r\n" \
"Server: horny\r\n" \
"\r\n"
def get():
return json_all % (thsen.read_tempC(), thsen.read_hum(), tsen.read_tempC())
def get_sht21_t():
return json['sht21_t'] % (thsen.read_tempC())
def get_sht21_h():
return json['sht21_h'] % (thsen.read_hum())
def get_sht21():
return json['sht21'] % (thsen.read_tempC(), thsen.read_hum())
def get_lm75a_t():
return json['lm75a_t'] % (tsen.read_tempC())
def get_lm75a():
return json['lm75a'] % (tsen.read_tempC())
#begin web
import socket
wssock=socket.getaddrinfo("0.0.0.0",80)[0][-1]
wss=socket.socket()
wss.bind(wssock)
wss.listen(1)
print("Server started on 0.0.0.0:80")
#main loop
while True:
wcl, wcsock = wss.accept()
print("Client connected")
wclfh = wcl.makefile('rwb', 0)
jsn=''
while True:
wcline = wclfh.readline()
if not wcline or wcline == b'\r\n': break
wcline=wcline.split(b' ')
if len(wcline) == 3 and wcline[2].startswith('HTTP'):
if wcline[0] != b'GET': wcl.close()
elif wcline[1] == b'/': jsn=get()
elif wcline[1] == b'/sht21': jsn=get_sht21()
elif wcline[1] == b'/lm75a': jsn=get_lm75a()
wcl.send(header()+jsn)
wcl.close()