Skip to content

Instantly share code, notes, and snippets.

@puhitaku
Last active September 22, 2016 07:26
Show Gist options
  • Save puhitaku/9d8bb2efafa73d86bc8c12962b55275e to your computer and use it in GitHub Desktop.
Save puhitaku/9d8bb2efafa73d86bc8c12962b55275e to your computer and use it in GitHub Desktop.

What's this?

This is a re-implemented version of Physical Router Driver for MicroPython. This code is experimental: it might cause some problems.

How to use?

Copy main.py into the root dir of Physical Router Driver ( https://github.com/puhitaku/physical_router_driver ) and execute it. Both CPython and MicroPython can run this.

Tested environment

  • MicroPython 1.4.5
import re
from os import system
from os.path import abspath
try:
import usocket as socket
except:
import socket
response_headers = {
"Cache-Control": "no-cache"
}
def make_response(body):
s = 'HTTP/1.0 200 OK\r\n{header}\r\n\r\n{body}'
header = '\r\n'.join(':'.join([k, v]) for k, v in response_headers.items())
return s.format(header=header, body=body)
def respond(request):
if str(request) == '':
return ''
path_raw = str(request).split(' ')[1]
path = path_raw.split('/')
if path_raw == '/':
with open(abspath('./statics/main.html')) as f:
return make_response(f.read())
elif path[-1] in ['f', 's', 'b']:
system(abspath('./drive.sh %s' % path[-1]))
return 'HTTP/1.0 200 OK'
elif any(path[-1].endswith(x) for x in ['js', 'css']):
with open(abspath('./statics/{}'.format(path[-1]))) as f:
return make_response(f.read())
else:
return 'HTTP/1.0 404'
def main(micropython_optimize=False):
s = socket.socket()
ai = socket.getaddrinfo("0.0.0.0", 8080)
print("Bind address info:", ai)
addr = ai[0][-1]
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
s.listen(5)
print("Ready: <host_ip>:8080")
counter = 0
while True:
res = s.accept()
client_sock = res[0]
client_addr = res[1]
print("Client address:", client_addr)
print("Client socket:", client_sock)
if not micropython_optimize:
client_stream = client_sock.makefile("rwb")
else:
client_stream = client_sock
print("Request:")
req = client_stream.readline()
print(req)
while True:
h = client_stream.readline()
if h == b"" or h == b"\r\n":
break
print(h)
client_stream.write(respond(req))
client_stream.close()
if not micropython_optimize:
client_sock.close()
counter += 1
print()
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment