Skip to content

Commit daa8dab

Browse files
authored
Merge pull request #4 from makermelissa/master
Added WiFi Manager and changed examples
2 parents 2d1bd43 + 4685648 commit daa8dab

File tree

4 files changed

+174
-79
lines changed

4 files changed

+174
-79
lines changed
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
# The MIT License (MIT)
2+
#
3+
# Copyright (c) 2019 Melissa LeBlanc-Williams for Adafruit Industries
4+
#
5+
# Permission is hereby granted, free of charge, to any person obtaining a copy
6+
# of this software and associated documentation files (the "Software"), to deal
7+
# in the Software without restriction, including without limitation the rights
8+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
# copies of the Software, and to permit persons to whom the Software is
10+
# furnished to do so, subject to the following conditions:
11+
#
12+
# The above copyright notice and this permission notice shall be included in
13+
# all copies or substantial portions of the Software.
14+
#
15+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21+
# THE SOFTWARE.
22+
23+
"""
24+
`adafruit_esp32spi_wifimanager`
25+
================================================================================
26+
27+
WiFi Manager for making ESP32 SPI as WiFi much easier
28+
29+
* Author(s): Melissa LeBlanc-Williams, ladyada
30+
"""
31+
32+
# pylint: disable=no-name-in-module
33+
34+
import neopixel
35+
import adafruit_esp32spi
36+
import adafruit_esp32spi.adafruit_esp32spi_requests as requests
37+
38+
class ESPSPI_WiFiManager:
39+
"""
40+
A class to help manage the Wifi connection
41+
"""
42+
def __init__(self, esp, settings, status_neopixel=None):
43+
"""
44+
:param ESP_SPIcontrol esp: The ESP object we are using
45+
:param dict settings: The WiFi and Adafruit IO Settings (See examples)
46+
:param status_neopixel: (Pptional) The neopixel pin - Usually board.NEOPIXEL (default=None)
47+
:type status_neopixel: Pin
48+
"""
49+
# Read the settings
50+
self._esp = esp
51+
self.debug = False
52+
self.ssid = settings['ssid']
53+
self.password = settings['password']
54+
requests.set_interface(self._esp)
55+
if status_neopixel:
56+
self.neopix = neopixel.NeoPixel(status_neopixel, 1, brightness=0.2)
57+
else:
58+
self.neopix = None
59+
self.neo_status(0)
60+
61+
def connect(self):
62+
"""
63+
Attempt to connect to WiFi using the current settings
64+
"""
65+
if self.debug:
66+
if self._esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
67+
print("ESP32 found and in idle mode")
68+
print("Firmware vers.", self._esp.firmware_version)
69+
print("MAC addr:", [hex(i) for i in self._esp.MAC_address])
70+
for access_pt in self._esp.scan_networks():
71+
print("\t%s\t\tRSSI: %d" % (str(access_pt['ssid'], 'utf-8'), access_pt['rssi']))
72+
while not self._esp.is_connected:
73+
try:
74+
if self.debug:
75+
print("Connecting to AP...")
76+
self.neo_status((100, 0, 0))
77+
self._esp.connect_AP(bytes(self.ssid, 'utf-8'), bytes(self.password, 'utf-8'))
78+
self.neo_status((0, 100, 0))
79+
except (ValueError, RuntimeError) as error:
80+
print("Failed to connect, retrying\n", error)
81+
continue
82+
83+
def get(self, url, **kw):
84+
"""
85+
Pass the Get request to requests and update Status NeoPixel
86+
87+
:param str url: The URL to retrieve data from
88+
:param dict data: (Optional) Form data to submit
89+
:param dict json: (Optional) JSON data to submit. (Data must be None)
90+
:param dict header: (Optional) Header data to include
91+
:param bool stream: (Optional) Whether to stream the Response
92+
:return: The response from the request
93+
:rtype: Response
94+
"""
95+
if not self._esp.is_connected:
96+
self.connect()
97+
self.neo_status((100, 100, 0))
98+
return_val = requests.get(url, **kw)
99+
self.neo_status(0)
100+
return return_val
101+
102+
def post(self, url, **kw):
103+
"""
104+
Pass the Post request to requests and update Status NeoPixel
105+
106+
:param str url: The URL to post data to
107+
:param dict data: (Optional) Form data to submit
108+
:param dict json: (Optional) JSON data to submit. (Data must be None)
109+
:param dict header: (Optional) Header data to include
110+
:param bool stream: (Optional) Whether to stream the Response
111+
:return: The response from the request
112+
:rtype: Response
113+
"""
114+
if not self._esp.is_connected:
115+
self.connect()
116+
self.neo_status((100, 100, 0))
117+
return_val = requests.post(url, **kw)
118+
self.neo_status(0)
119+
return return_val
120+
121+
def ping(self, host, ttl=250):
122+
"""
123+
Pass the Ping request to the ESP32, update Status NeoPixel, return response time
124+
125+
:param str host: The hostname or IP address to ping
126+
:param int ttl: (Optional) The Time To Live in milliseconds for the packet (default=250)
127+
:return: The response time in milliseconds
128+
:rtype: int
129+
"""
130+
if not self._esp.is_connected:
131+
self.connect()
132+
self.neo_status((100, 100, 0))
133+
response_time = self._esp.ping(host, ttl=ttl)
134+
self.neo_status(0)
135+
return response_time
136+
137+
def neo_status(self, value):
138+
"""
139+
Change Status NeoPixel if it was defined
140+
141+
:param value: The value to set the Board's Status NeoPixel to
142+
:type value: int or 3-value tuple
143+
"""
144+
if self.neopix:
145+
self.neopix.fill(value)

docs/examples.rst

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,15 @@ Ensure your device works with this simple test.
66
.. literalinclude:: ../examples/esp32spi_simpletest.py
77
:caption: examples/esp32spi_simpletest.py
88
:linenos:
9+
10+
11+
Other Examples
12+
---------------
13+
14+
.. literalinclude:: ../examples/esp32spi_cheerlights.py
15+
:caption: examples/esp32spi_cheerlights.py
16+
:linenos:
17+
18+
.. literalinclude:: ../examples/esp32spi_aio_post.py
19+
:caption: examples/esp32spi_aio_post.py
20+
:linenos:

examples/esp32spi_aio_post.py

Lines changed: 7 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,60 +1,35 @@
1-
21
import time
32
import board
43
import busio
54
from digitalio import DigitalInOut
65

76
from adafruit_esp32spi import adafruit_esp32spi
8-
import adafruit_esp32spi.adafruit_esp32spi_requests as requests
9-
7+
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
108

119
print("ESP32 SPI webclient test")
1210

1311
# Get wifi details and more from a settings.py file
1412
try:
1513
from esp32spi_settings import settings
1614
except ImportError:
17-
print("WiFi settings are kept in settings.py, please add them there!")
15+
print("WiFi settings are kept in esp32spi_settings.py, please add them there!")
1816
raise
1917

20-
2118
esp32_cs = DigitalInOut(board.D9)
2219
esp32_ready = DigitalInOut(board.D10)
2320
esp32_reset = DigitalInOut(board.D5)
2421
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
2522
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
26-
27-
requests.set_interface(esp)
28-
29-
if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
30-
print("ESP32 found and in idle mode")
31-
print("Firmware vers.", esp.firmware_version)
32-
print("MAC addr:", [hex(i) for i in esp.MAC_address])
33-
for ap in esp.scan_networks():
34-
print("\t%s\t\tRSSI: %d" % (str(ap['ssid'], 'utf-8'), ap['rssi']))
35-
while not esp.is_connected:
36-
try:
37-
print("Connecting to AP...")
38-
esp.connect_AP(bytes(settings['ssid'],'utf-8'), bytes(settings['password'],'utf-8'))
39-
except (ValueError, RuntimeError) as e:
40-
print("Failed to connect, retrying\n", e)
41-
continue
42-
print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi)
43-
print("My IP address is", esp.pretty_ip(esp.ip_address))
44-
23+
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, settings, board.NEOPIXEL)
4524

4625
counter = 0
4726
while True:
4827
try:
49-
while not esp.is_connected:
50-
# settings dictionary must contain 'ssid' and 'password' at a minimum
51-
esp.connect_AP(bytes(settings['ssid'],'utf-8'), bytes(settings['password'],'utf-8'))
52-
# great, lets get the data
5328
print("Posting data...", end='')
54-
data=counter
55-
feed='test'
56-
payload={'value':data}
57-
response=requests.post(
29+
data = counter
30+
feed = 'test'
31+
payload = {'value':data}
32+
response = wifi.post(
5833
"https://io.adafruit.com/api/v2/"+settings['aio_username']+"/feeds/"+feed+"/data",
5934
json=payload,headers={bytes("X-AIO-KEY","utf-8"):bytes(settings['aio_key'],"utf-8")})
6035
print(response.json())

examples/esp32spi_cheerlights.py

Lines changed: 10 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -4,87 +4,51 @@
44
from digitalio import DigitalInOut
55

66
from adafruit_esp32spi import adafruit_esp32spi
7-
import adafruit_esp32spi.adafruit_esp32spi_requests as requests
7+
from adafruit_esp32spi import adafruit_esp32spi_wifimanager
88

99
import neopixel
1010
import adafruit_fancyled.adafruit_fancyled as fancy
1111

12-
13-
1412
# Get wifi details and more from a settings.py file
1513
try:
1614
from esp32spi_settings import settings
1715
except ImportError:
18-
print("WiFi settings are kept in settings.py, please add them there!")
16+
print("WiFi settings are kept in esp32spi_settings.py, please add them there!")
1917
raise
2018

21-
22-
2319
print("ESP32 SPI webclient test")
2420

2521
DATA_SOURCE = "https://api.thingspeak.com/channels/1417/feeds.json?results=1"
2622
DATA_LOCATION = ["feeds", 0, "field2"]
2723

28-
2924
esp32_cs = DigitalInOut(board.D9)
3025
esp32_ready = DigitalInOut(board.D10)
3126
esp32_reset = DigitalInOut(board.D5)
3227
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
3328
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
34-
35-
requests.set_interface(esp)
36-
37-
if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
38-
print("ESP32 found and in idle mode")
39-
print("Firmware vers.", esp.firmware_version)
40-
print("MAC addr:", [hex(i) for i in esp.MAC_address])
41-
for ap in esp.scan_networks():
42-
print("\t%s\t\tRSSI: %d" % (str(ap['ssid'], 'utf-8'), ap['rssi']))
43-
while not esp.is_connected:
44-
try:
45-
print("Connecting to AP...")
46-
esp.connect_AP(bytes(settings['ssid'],'utf-8'), bytes(settings['password'],'utf-8'))
47-
except (ValueError, RuntimeError) as e:
48-
print("Failed to connect, retrying\n", e)
49-
continue
50-
print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi)
51-
print("My IP address is", esp.pretty_ip(esp.ip_address))
52-
29+
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, settings, board.NEOPIXEL)
5330

5431
# neopixels
5532
pixels = neopixel.NeoPixel(board.A1, 16, brightness=0.3)
5633
pixels.fill(0)
57-
builtin = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.1)
58-
builtin[0] = 0
5934

6035
# we'll save the value in question
6136
last_value = value = None
62-
the_time = None
63-
times = 0
64-
6537

6638
while True:
6739
try:
68-
while not esp.is_connected:
69-
builtin[0] = (100, 0, 0)
70-
# settings dictionary must contain 'ssid' and 'password' at a minimum
71-
esp.connect_AP(bytes(settings['ssid'],'utf-8'), bytes(settings['password'],'utf-8'))
72-
builtin[0] = (0, 100, 0)
7340
print("Fetching json from", DATA_SOURCE)
74-
builtin[0] = (100, 100, 0)
75-
r = requests.get(DATA_SOURCE)
76-
builtin[0] = (0, 0, 100)
77-
print(r.json())
78-
value=r.json()
79-
for x in DATA_LOCATION:
80-
value = value[x]
41+
response = wifi.get(DATA_SOURCE)
42+
print(response.json())
43+
value=response.json()
44+
for key in DATA_LOCATION:
45+
value = value[key]
8146
print(value)
82-
r.close()
47+
response.close()
8348
except (ValueError, RuntimeError) as e:
8449
print("Failed to get data, retrying\n", e)
8550
continue
8651

87-
builtin[0] = (100, 100, 100)
8852
if not value:
8953
continue
9054
if last_value != value:
@@ -96,6 +60,5 @@
9660

9761
pixels.fill(gamma_corrected)
9862
last_value = value
99-
times += 1
100-
r = None
63+
response = None
10164
time.sleep(60)

0 commit comments

Comments
 (0)