Commit 7b97850c authored by Klint Youngmeyer's avatar Klint Youngmeyer
Browse files

Moved picoWebSrv.py to its own repo. http://git.emacinc.com/Micropython/PicoWebSrv.git

parent fabe1289
import pyb
import network
import socket
import logging
# nic = network.RS911X(pyb.SPI(2), pyb.Pin("I0"), pyb.Pin("E3"), pyb.Pin("E4"))
# nic.connect('ASUS_E8_2G', '3197597781')
class PicoWebSrv:
# RS9116 sometimes throws OSError [105] ENOBUFS on a socket.accept() call
allowed_errors = [105]
def __init__(self, host, port, log=logging.INFO):
self.host = host
self.port = port
logging.basicConfig(level=log)
def start(self):
print("Simple Webserver Running at: {}:{}".format(self.host, self.port))
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((self.host, self.port))
server_socket.listen(1)
while True:
attempts = 0
connection = None
address = None
while attempts < 3:
try:
connection, address = server_socket.accept()
break
except OSError as e:
attempts += 1
if e.args[0] not in self.allowed_errors:
logging.info("OS Error: {}".format(e))
pyb.delay(10)
logging.debug("Got connection from {}".format(address))
request = connection.recv(1024).decode('utf-8')
string_list = request.split(' ')
method = string_list[0]
requesting_file = string_list[1]
try:
myfile, data = requesting_file.split('?')
except ValueError:
myfile = requesting_file.split('?')[0]
data = None
myfile = myfile.lstrip('/')
if myfile == '/':
myfile = 'index.html'
try:
file = open(myfile, 'rb')
response = file.read()
file.close()
header = 'HTTP/1.1 200 OK\n'
if myfile.endswith(".jpg"):
mimetype = 'image/jpg'
elif myfile.endswith(".css"):
mimetype = 'text/css'
else:
mimetype = 'text/html'
header += 'Content-Type: '+str(mimetype)+'\n\n'
except Exception:
header = 'HTTP/1.1 404 Not Found\n\n'
response = '<html><body><center><h3>Error 404: File not found</h3><p>Python HTTP Server</p></center></body></html>'.encode('utf-8')
final_response = header.encode('utf-8')
final_response += response
connection.send(final_response)
#connection.close()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment