Last active
December 21, 2018 06:23
-
-
Save gengshenghong/8126467672974a72379c6f1c62892609 to your computer and use it in GitHub Desktop.
test http server with workder threads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' | |
code to test http server with workder threads on esp32 | |
''' | |
# test configurations | |
HTTP_IN_THREAD = True | |
NNN = 1 | |
THREAD_SLEEP = True | |
# ssid configurations | |
SSID = "<ssid>" | |
SSID_PWD = "<password>" | |
import utime | |
import _thread | |
def thread_entry(): | |
while True: | |
if THREAD_SLEEP: | |
utime.sleep(10) | |
for i in range(0, NNN): | |
_thread.start_new_thread(thread_entry, ()) | |
def thread_http(): | |
# https://docs.micropython.org/en/latest/esp8266/tutorial/network_tcp.html | |
import machine | |
pins = [machine.Pin(i, machine.Pin.IN) for i in (0, 2, 4, 5, 12, 13, 14, 15)] | |
html = """<!DOCTYPE html> | |
<html> | |
<head> <title>ESP8266 Pins</title> </head> | |
<body> <h1>ESP8266 Pins</h1> | |
<table border="1"> <tr><th>Pin</th><th>Value</th></tr> %s </table> | |
</body> | |
</html> | |
""" | |
import socket | |
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1] | |
s = socket.socket() | |
s.bind(addr) | |
s.listen(1) | |
print('listening on', addr) | |
while True: | |
cl, addr = s.accept() | |
print('client connected from', addr) | |
cl_file = cl.makefile('rwb', 0) | |
while True: | |
line = cl_file.readline() | |
if not line or line == b'\r\n': | |
break | |
rows = ['<tr><td>%s</td><td>%d</td></tr>' % (str(p), p.value()) for p in pins] | |
response = html % '\n'.join(rows) | |
cl.send(response) | |
cl.close() | |
def connectWifi(ssid, passwd): | |
import network | |
wlan=None | |
# wlan config | |
wlan=network.WLAN(network.STA_IF) #create a wlan object | |
wlan.active(True) #Activate the network interface | |
wlan.disconnect() #Disconnect the last connected WiFi | |
wlan.connect(ssid,passwd) #connect wifi | |
while wlan.isconnected() == False: | |
utime.sleep(1) | |
print("==========WIFI connected==========") | |
print(wlan.ifconfig()) | |
print("==========WIFI connected==========") | |
return True | |
connectWifi(SSID, SSID_PWD) | |
if HTTP_IN_THREAD: | |
_thread.start_new_thread(thread_http, ()) | |
else: | |
thread_http() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment