Skip to content

Adding WPA2 Enterprise support to the WiFi manager library #45

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 46 commits into from
Jul 15, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
8e65459
Chunk buffer sends into 64 byte chunks
martymcguire Mar 13, 2019
9cade63
rm temp vars. replace buffer slice w/ memoryview.
martymcguire Mar 13, 2019
79425a6
Fixed infinite loop when socket readline fails
ZachNo May 5, 2019
bf54a08
Update adafruit_esp32spi/adafruit_esp32spi_socket.py
ZachNo May 19, 2019
7386534
Adding WPA2 Enterprise support to the WiFi manager library
docmollo May 19, 2019
d8f4ad2
Added an enum-like class for the WiFi connection type and refactored …
docmollo May 19, 2019
8e2b787
Replaced enum-like class with 2 constants; various fix-ups based on P…
docmollo May 22, 2019
ac4aee5
Merge pull request #42 from ZachNo/socket_hang_fix
ladyada May 25, 2019
c25157e
Make timeout a keyword argument
anecdata Jun 4, 2019
868dd5e
Merge pull request #50 from anecdata/master
makermelissa Jun 4, 2019
4df8144
add first mock api, blinks!
Jun 6, 2019
7772894
add valid pin tupleset check before initialization, raise error
Jun 6, 2019
00e7f97
drop all pull functionality since we dont have it defined in adafruit…
Jun 6, 2019
5e97cb1
add switch_to_x methods, docstrings
Jun 6, 2019
6a0c036
pylinting - 8.79/10, look at drivemode/direction classes...
Jun 6, 2019
4923344
checking in digitalio, ready
Jun 6, 2019
8599c01
add credit to where credit is due :)
Jun 6, 2019
e199972
Merge pull request #51 from brentru/mock-pwmout-digitalio
brentru Jun 6, 2019
6fcb231
Adding pwmout back in
Jun 7, 2019
64ca443
correct pin in attrerror, fixup docstrings
Jun 7, 2019
c916224
set freq
Jun 7, 2019
596b879
frequency should return, not raise
Jun 7, 2019
46b4dea
Merge pull request #52 from brentru/add-pwmout-implementation
brentru Jun 7, 2019
d21b709
add an externally defined rgbled status_led to _wifimanager
Jun 11, 2019
aeae91e
test the pixel attributes within pixel_status
Jun 11, 2019
92182ea
Merge pull request #53 from brentru/expose-rgbled-status-wifimanager
ladyada Jun 11, 2019
0d7c5b5
Adding WPA2 Enterprise support to the WiFi manager library
docmollo May 19, 2019
15ea3cc
Added an enum-like class for the WiFi connection type and refactored …
docmollo May 19, 2019
1eca01c
Replaced enum-like class with 2 constants; various fix-ups based on P…
docmollo May 22, 2019
1ff8edf
Refactored wifimanager connect function into 3 separate functions; re…
docmollo Jun 16, 2019
e01c762
fixing merge conflicts
docmollo Jun 16, 2019
4190bc3
fix the failure_count issue...sorry about that!
docmollo Jun 19, 2019
54bcb5a
make ._esp public
Jul 11, 2019
a23026d
Merge pull request #60 from brentru/make-esp-object-public
brentru Jul 11, 2019
8f964cc
Merge pull request #29 from martymcguire/mm-chunk-socket-sends
siddacious Jul 11, 2019
1e77ef5
merged conflicts
docmollo Jul 13, 2019
a492dda
merged conflicts
docmollo Jul 13, 2019
bce6bfa
merged conflicts
docmollo Jul 13, 2019
cbc7901
merged conflicts
docmollo Jul 13, 2019
447955a
merged conflicts
docmollo Jul 13, 2019
0c07ceb
merged conflicts
docmollo Jul 13, 2019
5931c1b
merged conflicts
docmollo Jul 13, 2019
7bc0ec6
merged conflicts
docmollo Jul 13, 2019
bb679e8
fix a regression due to the rebase'ing...
docmollo Jul 14, 2019
5c7a735
more fix-ups from rebase; fixed param defs in __init__
docmollo Jul 14, 2019
c89d13e
fixing more issues
docmollo Jul 14, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 108 additions & 0 deletions adafruit_esp32spi/PWMOut.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
# The MIT License (MIT)
#
# Copyright (c) 2019 Brent Rubell for Adafruit Industries
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
`PWMOut`
==============================
PWMOut CircuitPython API for ESP32SPI.

* Author(s): Brent Rubell
"""

class PWMOut():
"""
Implementation of CircuitPython PWMOut for ESP32SPI.

:param int esp_pin: Valid ESP32 GPIO Pin, predefined in ESP32_GPIO_PINS.
:param ESP_SPIcontrol esp: The ESP object we are using.
:param int duty_cycle: The fraction of each pulse which is high, 16-bit.
:param int frequency: The target frequency in Hertz (32-bit).
:param bool variable_frequency: True if the frequency will change over time.
"""
ESP32_PWM_PINS = set([0, 1, 2, 4, 5,
12, 13, 14, 15,
16, 17, 18, 19,
21, 22, 23, 25,
26, 27, 32, 33])
def __init__(self, esp, pwm_pin, *, frequency=500, duty_cycle=0, variable_frequency=False):
if pwm_pin in self.ESP32_PWM_PINS:
self._pwm_pin = pwm_pin
else:
raise AttributeError("Pin %d is not a valid ESP32 GPIO Pin."%pwm_pin)
self._esp = esp
self._duty_cycle = duty_cycle
self._freq = frequency
self._var_freq = variable_frequency

def __enter__(self):
return self

def __exit__(self, exc_type, exc_value, exc_traceback):
self.deinit()

def deinit(self):
"""De-initalize the PWMOut object."""
self._duty_cycle = 0
self._freq = 0
self._pwm_pin = None

def _is_deinited(self):
"""Checks if PWMOut object has been previously de-initalized"""
if self._pwm_pin is None:
raise ValueError("PWMOut Object has been deinitialized and can no longer "
"be used. Create a new PWMOut object.")

@property
def duty_cycle(self):
"""Returns the PWMOut object's duty cycle as a
ratio from 0.0 to 1.0."""
self._is_deinited()
return self._duty_cycle

@duty_cycle.setter
def duty_cycle(self, duty_cycle):
"""Sets the PWMOut duty cycle.
:param float duty_cycle: Between 0.0 (low) and 1.0 (high).
:param int duty_cycle: Between 0 (low) and 1 (high).
"""
self._is_deinited()
if not isinstance(duty_cycle, (int, float)):
raise TypeError("Invalid duty_cycle, should be int or float.")
duty_cycle /= 65535.0
if not 0.0 <= duty_cycle <= 1.0:
raise ValueError("Invalid duty_cycle, should be between 0.0 and 1.0")
self._esp.set_analog_write(self._pwm_pin, duty_cycle)

@property
def frequency(self):
"""Returns the PWMOut object's frequency value."""
self._is_deinited()
return self._freq

@frequency.setter
def frequency(self, freq):
"""Sets the PWMOut object's frequency value.
:param int freq: 32-bit value that dictates the PWM frequency in Hertz.
NOTE: Only writeable when constructed with variable_Frequency=True.
"""
self._is_deinited()
self._freq = freq
raise NotImplementedError("PWMOut Frequency not implemented in ESP32SPI")
11 changes: 7 additions & 4 deletions adafruit_esp32spi/adafruit_esp32spi.py
Original file line number Diff line number Diff line change
Expand Up @@ -560,11 +560,14 @@ def socket_write(self, socket_num, buffer):
if self._debug:
print("Writing:", buffer)
self._socknum_ll[0][0] = socket_num
resp = self._send_command_get_response(_SEND_DATA_TCP_CMD,
(self._socknum_ll[0], buffer),
sent_param_len_16=True)
sent = 0
for chunk in range((len(buffer) // 64)+1):
resp = self._send_command_get_response(_SEND_DATA_TCP_CMD,
(self._socknum_ll[0],
memoryview(buffer)[(chunk*64):((chunk+1)*64)]),
sent_param_len_16=True)
sent += resp[0][0]

sent = resp[0][0]
if sent != len(buffer):
raise RuntimeError("Failed to send %d bytes (sent %d)" % (len(buffer), sent))

Expand Down
4 changes: 2 additions & 2 deletions adafruit_esp32spi/adafruit_esp32spi_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def iter_content(self, chunk_size=1, decode_unicode=False):
return

# pylint: disable=too-many-branches, too-many-statements, unused-argument, too-many-arguments, too-many-locals
def request(method, url, data=None, json=None, headers=None, stream=False):
def request(method, url, data=None, json=None, headers=None, stream=False, timeout=1):
"""Perform an HTTP request to the given url which we will parse to determine
whether to use SSL ('https://') or not. We can also send some provided 'data'
or a json dictionary which we will stringify. 'headers' is optional HTTP headers
Expand Down Expand Up @@ -163,7 +163,7 @@ def request(method, url, data=None, json=None, headers=None, stream=False):
sock = socket.socket(addr_info[0], addr_info[1], addr_info[2])
resp = Response(sock) # our response

sock.settimeout(1) # 1 second timeout
sock.settimeout(timeout) # socket read timeout

try:
if proto == "https:":
Expand Down
4 changes: 4 additions & 0 deletions adafruit_esp32spi/adafruit_esp32spi_socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,11 +87,15 @@ def write(self, data): # pylint: disable=no-self-use
def readline(self):
"""Attempt to return as many bytes as we can up to but not including '\r\n'"""
#print("Socket readline")
stamp = time.monotonic()
while b'\r\n' not in self._buffer:
# there's no line already in there, read some more
avail = min(_the_interface.socket_available(self._socknum), MAX_PACKET)
if avail:
self._buffer += _the_interface.socket_read(self._socknum, avail)
elif self._timeout > 0 and time.monotonic() - stamp > self._timeout:
self.close() # Make sure to close socket so that we don't exhaust sockets.
raise RuntimeError("Didn't receive full response, failing out")
firstline, self._buffer = self._buffer.split(b'\r\n', 1)
gc.collect()
return firstline
Expand Down
115 changes: 90 additions & 25 deletions adafruit_esp32spi/adafruit_esp32spi_wifimanager.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,59 +31,121 @@

# pylint: disable=no-name-in-module

from time import sleep
from micropython import const
from adafruit_esp32spi import adafruit_esp32spi
import adafruit_esp32spi.adafruit_esp32spi_requests as requests

class ESPSPI_WiFiManager:
"""
A class to help manage the Wifi connection
"""
def __init__(self, esp, secrets, status_pixel=None, attempts=2):
NORMAL = const(1)
ENTERPRISE = const(2)

# pylint: disable=too-many-arguments
def __init__(self, esp, secrets, status_pixel=None, attempts=2, connection_type=NORMAL):
"""
:param ESP_SPIcontrol esp: The ESP object we are using
:param dict secrets: The WiFi and Adafruit IO secrets dict (See examples)
:param status_pixel: (Optional) The pixel device - A NeoPixel or DotStar (default=None)
:type status_pixel: NeoPixel or DotStar
:param status_pixel: (Optional) The pixel device - A NeoPixel, DotStar,
or RGB LED (default=None)
:type status_pixel: NeoPixel, DotStar, or RGB LED
:param int attempts: (Optional) Failed attempts before resetting the ESP32 (default=2)
:param const connection_type: (Optional) Type of WiFi connection: NORMAL or ENTERPRISE
"""
# Read the settings
self._esp = esp
self.esp = esp
self.debug = False
self.ssid = secrets['ssid']
self.password = secrets['password']
self.attempts = attempts
requests.set_interface(self._esp)
self._connection_type = connection_type
requests.set_interface(self.esp)
self.statuspix = status_pixel
self.pixel_status(0)

# Check for WPA2 Enterprise keys in the secrets dictionary and load them if they exist
if secrets.get('ent_ssid'):
self.ent_ssid = secrets['ent_ssid']
else:
self.ent_ssid = secrets['ssid']
if secrets.get('ent_ident'):
self.ent_ident = secrets['ent_ident']
else:
self.ent_ident = ''
if secrets.get('ent_user'):
self.ent_user = secrets['ent_user']
if secrets.get('ent_password'):
self.ent_password = secrets['ent_password']
# pylint: enable=too-many-arguments

def reset(self):
"""
Perform a hard reset on the ESP32
"""
if self.debug:
print("Resetting ESP32")
self._esp.reset()
self.esp.reset()

def connect(self):
"""
Attempt to connect to WiFi using the current settings
"""
if self.debug:
if self._esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
if self.esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
print("ESP32 found and in idle mode")
print("Firmware vers.", self._esp.firmware_version)
print("MAC addr:", [hex(i) for i in self._esp.MAC_address])
for access_pt in self._esp.scan_networks():
print("Firmware vers.", self.esp.firmware_version)
print("MAC addr:", [hex(i) for i in self.esp.MAC_address])
for access_pt in self.esp.scan_networks():
print("\t%s\t\tRSSI: %d" % (str(access_pt['ssid'], 'utf-8'), access_pt['rssi']))
if self._connection_type == ESPSPI_WiFiManager.NORMAL:
self.connect_normal()
elif self._connection_type == ESPSPI_WiFiManager.ENTERPRISE:
self.connect_enterprise()
else:
raise TypeError("Invalid WiFi connection type specified")

def connect_normal(self):
"""
Attempt a regular style WiFi connection
"""
failure_count = 0
while not self._esp.is_connected:
while not self.esp.is_connected:
try:
if self.debug:
print("Connecting to AP...")
self.pixel_status((100, 0, 0))
self._esp.connect_AP(bytes(self.ssid, 'utf-8'), bytes(self.password, 'utf-8'))
self.esp.connect_AP(bytes(self.ssid, 'utf-8'), bytes(self.password, 'utf-8'))
failure_count = 0
self.pixel_status((0, 100, 0))
except (ValueError, RuntimeError) as error:
print("Failed to connect, retrying\n", error)
failure_count += 1
if failure_count >= self.attempts:
failure_count = 0
self.reset()
continue

def connect_enterprise(self):
"""
Attempt an enterprise style WiFi connection
"""
failure_count = 0
self.esp.wifi_set_network(bytes(self.ent_ssid, 'utf-8'))
self.esp.wifi_set_entidentity(bytes(self.ent_ident, 'utf-8'))
self.esp.wifi_set_entusername(bytes(self.ent_user, 'utf-8'))
self.esp.wifi_set_entpassword(bytes(self.ent_password, 'utf-8'))
self.esp.wifi_set_entenable()
while not self.esp.is_connected:
try:
if self.debug:
print("Waiting for the ESP32 to connect to the WPA2 Enterprise AP...")
self.pixel_status((100, 0, 0))
sleep(1)
failure_count = 0
self.pixel_status((0, 100, 0))
sleep(1)
except (ValueError, RuntimeError) as error:
print("Failed to connect, retrying\n", error)
failure_count += 1
Expand All @@ -104,7 +166,7 @@ def get(self, url, **kw):
:return: The response from the request
:rtype: Response
"""
if not self._esp.is_connected:
if not self.esp.is_connected:
self.connect()
self.pixel_status((0, 0, 100))
return_val = requests.get(url, **kw)
Expand All @@ -123,7 +185,7 @@ def post(self, url, **kw):
:return: The response from the request
:rtype: Response
"""
if not self._esp.is_connected:
if not self.esp.is_connected:
self.connect()
self.pixel_status((0, 0, 100))
return_val = requests.post(url, **kw)
Expand All @@ -141,7 +203,7 @@ def put(self, url, **kw):
:return: The response from the request
:rtype: Response
"""
if not self._esp.is_connected:
if not self.esp.is_connected:
self.connect()
self.pixel_status((0, 0, 100))
return_val = requests.put(url, **kw)
Expand All @@ -160,7 +222,7 @@ def patch(self, url, **kw):
:return: The response from the request
:rtype: Response
"""
if not self._esp.is_connected:
if not self.esp.is_connected:
self.connect()
self.pixel_status((0, 0, 100))
return_val = requests.patch(url, **kw)
Expand All @@ -179,7 +241,7 @@ def delete(self, url, **kw):
:return: The response from the request
:rtype: Response
"""
if not self._esp.is_connected:
if not self.esp.is_connected:
self.connect()
self.pixel_status((0, 0, 100))
return_val = requests.delete(url, **kw)
Expand All @@ -195,37 +257,40 @@ def ping(self, host, ttl=250):
:return: The response time in milliseconds
:rtype: int
"""
if not self._esp.is_connected:
if not self.esp.is_connected:
self.connect()
self.pixel_status((0, 0, 100))
response_time = self._esp.ping(host, ttl=ttl)
response_time = self.esp.ping(host, ttl=ttl)
self.pixel_status(0)
return response_time

def ip_address(self):
"""
Returns a formatted local IP address, update status pixel.
"""
if not self._esp.is_connected:
if not self.esp.is_connected:
self.connect()
self.pixel_status((0, 0, 100))
self.pixel_status(0)
return self._esp.pretty_ip(self._esp.ip_address)
return self.esp.pretty_ip(self.esp.ip_address)

def pixel_status(self, value):
"""
Change Status NeoPixel if it was defined
Change Status Pixel if it was defined

:param value: The value to set the Board's status LED to
:type value: int or 3-value tuple
"""
if self.statuspix:
self.statuspix.fill(value)
if hasattr(self.statuspix, 'color'):
self.statuspix.color = value
else:
self.statuspix.fill(value)

def signal_strength(self):
"""
Returns receiving signal strength indicator in dBm
"""
if not self._esp.is_connected:
if not self.esp.is_connected:
self.connect()
return self._esp.rssi()
return self.esp.rssi()
Loading