generated from rivques/CPyProjectTemplate
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinternet.py
80 lines (65 loc) · 2.37 KB
/
internet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import board
import busio
from digitalio import DigitalInOut
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from adafruit_esp32spi import adafruit_esp32spi
import adafruit_requests as requests
from adafruit_io.adafruit_io import IO_HTTP, AdafruitIO_RequestError
from secrets import secrets
import lib.my_wsgi as server
import neopixel
from adafruit_wsgi.wsgi_app import WSGIApp
status_light = neopixel.NeoPixel(
board.NEOPIXEL, 1, brightness=0.2
)
# If you are using a board with pre-defined ESP32 Pins:
esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
print("Connecting to AP...")
while not esp.is_connected:
try:
esp.connect_AP(secrets["ssid"], secrets["password"])
except (RuntimeError, ConnectionError) as e:
print("could not connect to AP, retrying: ", e)
continue
print("Connected to", str(esp.ssid, "utf-8"), "\tRSSI:", esp.rssi)
socket.set_interface(esp)
requests.set_socket(socket, esp)
web_app = WSGIApp()
@web_app.route("/led_on/<r>/<g>/<b>")
def led_on(request, r, g, b): # pylint: disable=unused-argument
print("led on!")
status_light.fill((int(r), int(g), int(b)))
return ("200 OK", [], "led on!")
@web_app.route("/led_off")
def led_off(request): # pylint: disable=unused-argument
print("led off!")
status_light.fill(0)
return ("200 OK", [], "led off!")
@web_app.route("/")
def index(request):
print("index!")
with open("lib/static/index.html") as f:
print("getting HTML...")
html = ''.join(f.readlines())
print("got HTML")
return("200 OK", [], html)
# Here we setup our server, passing in our web_app as the application
server.set_interface(esp)
wsgiServer = server.WSGIServer(80, application=web_app)
print("open this IP in your browser: ", esp.pretty_ip(esp.ip_address))
# print(esp.get_time())
# Start the server
wsgiServer.start()
while True:
# Our main loop where we have the server poll for incoming requests
try:
wsgiServer.update_poll()
# Could do any other background tasks here, like reading sensors
except (ValueError, RuntimeError) as e:
print("Failed to update server, restarting ESP32\n", e)
esp.reset()
continue