uPyLibs/main.py

93 lines
3.0 KiB
Python

import uPyConfig
hw = uPyConfig.esp8266(variant='d1-r2')
#print family, variant and IP address (using oled, if available on-board)
import init_sample
init_sample.init_sample(hw)
# Main app
from uPySensor import BME280, LM75A, SHT21
bme280=BME280(hw.i2c.bus)
lm75a =LM75A(hw.i2c.bus)
sht21 =SHT21(hw.i2c.bus)
#MicroWebSrv disabled until i work out how to make it fit into an esp8266's memory space
#wshead={
# 'Server':'horny',
#}
#wsctype='application/json'
#wscharset='UTF-8'
#from microWebSrv import MicroWebSrv
#@MicroWebSrv.route('/')
#def get_root(wscl, wsres):
# wsres.WriteResponseOk(
# headers=wshead,
# contentType=wsctype,
# content='{"result":"error","message":"use /bme280, /lm75a or /sht21 for sensor readings"}'
# )
#@MicroWebSrv.route('/bme280')
#def get_bme280(wscl, wsres):
# bme280.update_sensor()
# wsres.WriteResponseOk(
# headers=wshead,
# contentType=wsctype,
# content='{"temperature":"%0.2f","humidity":"%0.2f","pressure":"%0.2f"}' % (
# bme280.temperature, bme280.humidity, bme280.pressure)
# )
#@MicroWebSrv.route('/lm75a')
#def get_lm75a(wscl, wsres):
# wsres.WriteResponseOk(
# headers=wshead,
# contentType=wsctype,
# content='{"temperature":"%0.1f"}' % lm75a.read_tempC()
# )
#@MicroWebSrv.route('/sht21')
#def sht21(wscl, wsres):
# wsres.WriteResponseOk(
# headers=wshead,
# contentType=wsctype,
# content='{"temperature":"%0.3f","humidity":"%0.3f"}' % (sht21.read_tempC(), sht21.read_hum())
# )
#
#ws = MicroWebSrv()
#ws.Start()
#fallback microserver
def _bme280():
bme280.update_sensor()
return '{"temperature":"%0.2f","humidity":"%0.2f","pressure":"%0.2f"}' % (
bme280.temperature, bme280.humidity, bme280.pressure)
def _lm75a(): return '{"temperature":"%0.1f"}' % lm75a.read_tempC()
def _sht21(): return '{"temperature":"%0.3f","humidity":"%0.3f"}' % (sht21.read_tempC(), sht21.read_hum())
def header(): return "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nServer: horny\r\n\r\n"
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='{"result":"error","message":"use /bme280, /lm75a or /sht21 for sensor readings"}'
elif wcline[1] == b'/sht21': jsn=_sht21 ()
elif wcline[1] == b'/lm75a': jsn=_lm75a ()
elif wcline[1] == b'/bme280': jsn=_bme280()
wcl.send(header()+jsn)
wcl.close()
ws = tinyWebServer()