ripped out a large chunk of microWebSrv in order to fit it into the memory space of an esp8266

This commit is contained in:
Maff 2018-05-31 21:39:23 +01:00
parent fd117de9a6
commit fd173c0f73
3 changed files with 13 additions and 177 deletions

View File

@ -41,5 +41,5 @@ if wlan(staif).isconnected() != True:
time.sleep_ms(100)
slept+=1
import webrepl
webrepl.start()
#import webrepl
#webrepl.start()

14
main.py
View File

@ -1,20 +1,20 @@
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)
#import init_sample
#init_sample.init_sample(hw)
# Main app
from uPySensor import BME280, LM75A, SHT21
import uPySensor
sensors={
'bme280': BME280(hw.i2c.bus),
'lm75a': LM75A(hw.i2c.bus),
'sht21': SHT21(hw.i2c.bus),
'bme280': uPySensor.BME280(hw.i2c.bus),
'lm75a': uPySensor.LM75A(hw.i2c.bus),
'sht21': uPySensor.SHT21(hw.i2c.bus),
}
from microWebSrv import MicroWebSrv
ws = MicroWebSrv(webPath='www/')
ws = MicroWebSrv()
ws.WebSocketThreaded = False
wshead={

View File

@ -10,21 +10,9 @@ import _thread
import network
import time
import socket
import websocket
import gc
import re
try:
from microWebTemplate import MicroWebTemplate
except:
pass
try:
from microWebSocket import MicroWebSocket
except:
pass
class MicroWebSrvRoute:
def __init__(self, route, method, func, routeArgNames, routeRegex):
self.route = route
@ -39,35 +27,6 @@ class MicroWebSrv:
# ===( Constants )============================================================
# ============================================================================
_indexPages = [
"index.pyhtml",
"index.html",
"index.htm",
"default.pyhtml",
"default.html",
"default.htm"
]
_mimeTypes = {
".txt": "text/plain",
".htm": "text/html",
".html": "text/html",
".css": "text/css",
".csv": "text/csv",
".js": "application/javascript",
".xml": "application/xml",
".xhtml": "application/xhtml+xml",
".json": "application/json",
".zip": "application/zip",
".pdf": "application/pdf",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".png": "image/png",
".gif": "image/gif",
".svg": "image/svg+xml",
".ico": "image/x-icon"
}
_html_escape_chars = {
"&": "&",
'"': """,
@ -76,8 +35,6 @@ class MicroWebSrv:
"<": "&lt;"
}
_pyhtmlPagesExt = '.pyhtml'
# ============================================================================
# ===( Class globals )=======================================================
# ============================================================================
@ -150,22 +107,6 @@ class MicroWebSrv:
def _unquote_plus(s):
return MicroWebSrv._unquote(s.replace('+', ' '))
# ----------------------------------------------------------------------------
@staticmethod
def _fileExists(path):
try:
stat(path)
return True
except:
return False
# ----------------------------------------------------------------------------
@staticmethod
def _isPyHTMLFile(filename):
return filename.lower().endswith(MicroWebSrv._pyhtmlPagesExt)
# ============================================================================
# ===( Constructor )==========================================================
# ============================================================================
@ -173,21 +114,14 @@ class MicroWebSrv:
def __init__(self,
routeHandlers=[],
port=80,
bindIP='0.0.0.0',
webPath="/flash/www"):
bindIP='0.0.0.0'):
self._srvAddr = (bindIP, port)
self._webPath = webPath
self._notFoundUrl = None
self._started = False
self.thID = None
self.isThreaded = False
self._state = "Stoped"
self.MaxWebSocketRecvLen = 1024
self.WebSocketThreaded = True
self.WebSocketStackSize = 4096
self.AcceptWebSocketCallback = None
self._state = "Stopped"
self._routeHandlers = []
routeHandlers += self._docoratedRouteHandlers
@ -237,7 +171,7 @@ class MicroWebSrv:
break
self._client(self, client, cliAddr)
self._started = False
self._state = "Stoped"
self._state = "Stopped"
self.thID = None
# ============================================================================
@ -298,15 +232,6 @@ class MicroWebSrv:
# ----------------------------------------------------------------------------
def GetMimeTypeFromFilename(self, filename):
filename = filename.lower()
for ext in self._mimeTypes:
if filename.endswith(ext):
return self._mimeTypes[ext]
return None
# ----------------------------------------------------------------------------
def GetRouteHandler(self, resUrl, method):
if self._routeHandlers:
# resUrl = resUrl.upper()
@ -331,20 +256,6 @@ class MicroWebSrv:
return (rh.func, None)
return (None, None)
# ----------------------------------------------------------------------------
def _physPathFromURLPath(self, urlPath):
if urlPath == '/':
for idxPage in self._indexPages:
physPath = self._webPath + '/' + idxPage
if MicroWebSrv._fileExists(physPath):
return physPath
else:
physPath = self._webPath + urlPath
if MicroWebSrv._fileExists(physPath):
return physPath
return None
# ============================================================================
# ===( Class Client )========================================================
# ============================================================================
@ -386,30 +297,9 @@ class MicroWebSrv:
else:
routeHandler(self, response)
elif self._method.upper() == "GET":
filepath = self._microWebSrv._physPathFromURLPath(self._resPath)
if filepath:
if MicroWebSrv._isPyHTMLFile(filepath):
response.WriteResponsePyHTMLFile(filepath)
else:
contentType = self._microWebSrv.GetMimeTypeFromFilename(filepath)
if contentType:
response.WriteResponseFile(filepath, contentType)
else:
response.WriteResponseForbidden()
else:
response.WriteResponseNotFound()
else:
response.WriteResponseMethodNotAllowed()
elif upg == 'websocket' and 'MicroWebSocket' in globals() \
and self._microWebSrv.AcceptWebSocketCallback:
MicroWebSocket(socket=self._socket,
httpClient=self,
httpResponse=response,
maxRecvLen=self._microWebSrv.MaxWebSocketRecvLen,
threaded=self._microWebSrv.WebSocketThreaded,
acceptCallback=self._microWebSrv.AcceptWebSocketCallback,
stackSize=self._microWebSrv.WebSocketStackSize)
return
else:
response.WriteResponseNotImplemented()
else:
@ -654,60 +544,6 @@ class MicroWebSrv:
# ------------------------------------------------------------------------
def WriteResponsePyHTMLFile(self, filepath, headers=None):
if 'MicroWebTemplate' in globals():
with open(filepath, 'r') as file:
code = file.read()
gc.collect()
mWebTmpl = MicroWebTemplate(code, escapeStrFunc=MicroWebSrv.HTMLEscape, filepath=filepath)
try:
tmplResult = mWebTmpl.Execute()
return self.WriteResponse(200, headers, "text/html", "UTF-8", tmplResult)
except Exception as ex:
return self.WriteResponse(500,
None,
"text/html",
"UTF-8",
self._execErrCtnTmpl % {
'module': 'PyHTML',
'message': str(ex)
})
return self.WriteResponseNotImplemented()
# ------------------------------------------------------------------------
def WriteResponseFile(self, filepath, contentType=None, headers=None):
try:
size = stat(filepath)[6]
if size > 0:
with open(filepath, 'rb') as file:
self._writeBeforeContent(200, headers, contentType, None, size)
buf = MicroWebSrv._tryAllocByteArray(1024)
if buf:
while size > 0:
x = file.readinto(buf)
if x < len(buf):
buf = memoryview(buf)[:x]
self._write(buf)
size -= x
return True
self.WriteResponseInternalServerError()
return False
except:
pass
self.WriteResponseNotFound()
return False
# ------------------------------------------------------------------------
def WriteResponseFileAttachment(self, filepath, attachmentName, headers=None):
if not isinstance(headers, dict):
headers = {}
headers["Content-Disposition"] = "attachment; filename=\"%s\"" % attachmentName
return self.WriteResponseFile(filepath, None, headers)
# ------------------------------------------------------------------------
def WriteResponseOk(self, headers=None, contentType=None, contentCharset=None, content=None):
return self.WriteResponse(200, headers, contentType, contentCharset, content)