Easy peasy: just send whatever header is needed ahead of the body separated by a blank line. RTFM.
Code: Select all
header = """HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Access-Control-Allow-Origin: *
"""
Code: Select all
conn.send(header)
conn.send(response)
The header is "Access-Control-Allow-Origin: *".
The response to a GET only needs to be a single string of a few characters and not well-formed HTML.
To get started, I am playing with an example I found on the InterWebs (and have since modified):
Code: Select all
import machine
import network
import socket
import time
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
html = """<!DOCTYPE html>
<html>
<head> <title>ESP8266 LED control</title> </head>
<body> <h1>ESP8266 with MicroPython</h1>
LED Pin 5
<a href="/led5/on"><button>LED ON</button></a>
<a href="/led5/off"><button>LED OFF</button><br><br></a>
LED Pin 16
<a href="/led16/on"><button>LED ON</button></a>
<a href="/led16/off"><button>LED OFF</button><br><br></a>
Delay Sequence
<a href="/led/delay"><button type="submit">Delay</button></a>
</body>
</html>
"""
# the pins assume that they are connected to LEDs with the anode connected to + so that
# low (off) turns them on.
def SwitchON(pin):
print('turning on', pin)
pin.off()
def SwitchOFF(pin):
print('turning off', pin)
pin.on()
# what's the difference between 'socket' and 'usocket'???
s = socket.socket()
s.bind(addr)
s.listen(1)
pin5 = machine.Pin(5, machine.Pin.OUT)
pin16 = machine.Pin(16, machine.Pin.OUT)
print('listening on', addr)
while True:
conn, addr = s.accept() # after a few requests, this hangs when webrepl is connected
print('client connected from', addr)
response = html
request = conn.recv(1024)[0:19] # slice the first 20 chars
if 'favicon' in str(request):
continue # discard second get from Chrome asking for 'favicon'
print(request)
if '/led5/on' in str(request):
print('pin5 on!')
SwitchON(pin5)
elif '/led5/off' in str(request):
print('pin5 off!')
SwitchOFF(pin5)
elif '/led16/on' in str(request):
print('pin16 on!')
SwitchON(pin16)
elif '/led16/off' in str(request):
print('pin16 off!')
SwitchOFF(pin16)
elif '/led/delay' in str(request):
seq = 10
while seq:
print('seqence: ',seq)
time.sleep(0.5)
SwitchON(pin5)
SwitchON(pin16)
time.sleep(0.5)
SwitchOFF(pin5)
SwitchOFF(pin16)
seq -= 1
else:
SwitchOFF(pin5)
SwitchOFF(pin16)
conn.send(response)
conn.close()
Suggestions?
On a side note, in this example, a block of text is assigned to the variable 'html' and later 'html' is assigned to 'response' which is then returned to the client. Do we really need two variables? Does it matter in MicroPython?
Thanks,
--Jeff