Skip to content

implement wifmanager and update examples #28

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 3 commits into from
Feb 27, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
3 changes: 1 addition & 2 deletions adafruit_espatcontrol/adafruit_espatcontrol_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,6 @@ def request(method, url, data=None, json=None, headers=None, stream=None):
sock.write(bytes(data, 'utf-8'))

line = sock.readline()
#print(line)
line = line.split(None, 2)
status = int(line[1])
reason = ""
Expand All @@ -142,7 +141,6 @@ def request(method, url, data=None, json=None, headers=None, stream=None):
if not line or line == b"\r\n":
break

#print(line)
title, content = line.split(b': ', 1)
if title and content:
title = str(title.lower(), 'utf-8')
Expand All @@ -157,6 +155,7 @@ def request(method, url, data=None, json=None, headers=None, stream=None):

except OSError:
sock.close()
print("how did we get here")
raise

resp.status_code = status
Expand Down
204 changes: 204 additions & 0 deletions adafruit_espatcontrol/adafruit_espatcontrol_wifimanager.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,204 @@
# The MIT License (MIT)
#
# Copyright (c) 2019 Melissa LeBlanc-Williams 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.

"""
`adafruit_espatcontrol_wifimanager`
================================================================================

WiFi Manager for making ESP32 AT Control as WiFi much easier

* Author(s): Melissa LeBlanc-Williams, ladyada, Jerry Needell
"""

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

import adafruit_espatcontrol.adafruit_espatcontrol_requests as requests

class ESPAT_WiFiManager:
"""
A class to help manage the Wifi connection
"""
def __init__(self, esp, secrets, status_pixel=None, attempts=2):
"""
: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 int attempts: (Optional) Failed attempts before resetting the ESP32 (default=2)
"""
# Read the settings
self._esp = esp
self.debug = False
self.secrets = secrets
self.attempts = attempts
requests.set_interface(self._esp)
self.statuspix = status_pixel
self.pixel_status(0)

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

def connect(self):
"""
Attempt to connect to WiFi using the current settings
"""
failure_count = 0
while not self._esp.is_connected:
try:
if self.debug:
print("Connecting to AP...")
self.pixel_status((100, 0, 0))
self._esp.connect(self.secrets)
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 get(self, url, **kw):
"""
Pass the Get request to requests and update Status NeoPixel

:param str url: The URL to retrieve data from
:param dict data: (Optional) Form data to submit
:param dict json: (Optional) JSON data to submit. (Data must be None)
:param dict header: (Optional) Header data to include
:param bool stream: (Optional) Whether to stream the Response
:return: The response from the request
:rtype: Response
"""
if not self._esp.is_connected:
self.connect()
self.pixel_status((0, 0, 100))
return_val = requests.get(url, **kw)
self.pixel_status(0)
return return_val

def post(self, url, **kw):
"""
Pass the Post request to requests and update Status NeoPixel

:param str url: The URL to post data to
:param dict data: (Optional) Form data to submit
:param dict json: (Optional) JSON data to submit. (Data must be None)
:param dict header: (Optional) Header data to include
:param bool stream: (Optional) Whether to stream the Response
:return: The response from the request
:rtype: Response
"""
if not self._esp.is_connected:
self.connect()
self.pixel_status((0, 0, 100))
return_val = requests.post(url, **kw)
return return_val

def put(self, url, **kw):
"""
Pass the put request to requests and update Status NeoPixel

:param str url: The URL to PUT data to
:param dict data: (Optional) Form data to submit
:param dict json: (Optional) JSON data to submit. (Data must be None)
:param dict header: (Optional) Header data to include
:param bool stream: (Optional) Whether to stream the Response
:return: The response from the request
:rtype: Response
"""
if not self._esp.is_connected:
self.connect()
self.pixel_status((0, 0, 100))
return_val = requests.put(url, **kw)
self.pixel_status(0)
return return_val

def patch(self, url, **kw):
"""
Pass the patch request to requests and update Status NeoPixel

:param str url: The URL to PUT data to
:param dict data: (Optional) Form data to submit
:param dict json: (Optional) JSON data to submit. (Data must be None)
:param dict header: (Optional) Header data to include
:param bool stream: (Optional) Whether to stream the Response
:return: The response from the request
:rtype: Response
"""
if not self._esp.is_connected:
self.connect()
self.pixel_status((0, 0, 100))
return_val = requests.patch(url, **kw)
self.pixel_status(0)
return return_val

def delete(self, url, **kw):
"""
Pass the delete request to requests and update Status NeoPixel

:param str url: The URL to PUT data to
:param dict data: (Optional) Form data to submit
:param dict json: (Optional) JSON data to submit. (Data must be None)
:param dict header: (Optional) Header data to include
:param bool stream: (Optional) Whether to stream the Response
:return: The response from the request
:rtype: Response
"""
if not self._esp.is_connected:
self.connect()
self.pixel_status((0, 0, 100))
return_val = requests.delete(url, **kw)
self.pixel_status(0)
return return_val

def ping(self, host, ttl=250):
"""
Pass the Ping request to the ESP32, update Status NeoPixel, return response time

:param str host: The hostname or IP address to ping
:param int ttl: (Optional) The Time To Live in milliseconds for the packet (default=250)
:return: The response time in milliseconds
:rtype: int
"""
if not self._esp.is_connected:
self.connect()
self.pixel_status((0, 0, 100))
response_time = self._esp.ping(host, ttl=ttl)
self.pixel_status(0)
return response_time

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

:param value: The value to set the Board's Status NeoPixel to
:type value: int or 3-value tuple
"""
if self.statuspix:
self.statuspix.fill(value)
45 changes: 24 additions & 21 deletions examples/espatcontrol_aio_post.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,16 @@
import board
import busio
from digitalio import DigitalInOut
from adafruit_espatcontrol import adafruit_espatcontrol
from adafruit_espatcontrol import adafruit_espatcontrol_requests as requests

# ESP32 AT
from adafruit_espatcontrol import adafruit_espatcontrol, adafruit_espatcontrol_wifimanager

#Use below for Most Boards
import neopixel
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards
#Uncomment below for ItsyBitsy M4#
#import adafruit_dotstar as dotstar
#status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)


# Get wifi details and more from a secrets.py file
Expand All @@ -15,9 +23,9 @@


# With a Metro or Feather M4
uart = busio.UART(board.TX, board.RX, timeout=0.1)
resetpin = DigitalInOut(board.D5)
rtspin = DigitalInOut(board.D6)
uart = busio.UART(board.TX, board.RX, timeout=0.1)

# With a Particle Argon
"""
Expand All @@ -33,36 +41,31 @@
"""


esp = adafruit_espatcontrol.ESP_ATcontrol(uart, 115200, reset_pin=resetpin,
run_baudrate = 460800, rts_pin=rtspin, debug=True)
print("Resetting ESP module")
esp.hard_reset()
requests.set_interface(esp)
print("ESP AT commands")
esp = adafruit_espatcontrol.ESP_ATcontrol(uart, 115200,
reset_pin=resetpin, rts_pin=rtspin, debug=False)
wifi = adafruit_espatcontrol_wifimanager.ESPAT_WiFiManager(esp, secrets, status_light)

print("Connected to AT software version", esp.get_version())

counter = 0

while True:
try:
# Connect to WiFi if not already
while not esp.is_connected:
print("Connecting...")
esp.connect(secrets)
print("Connected to", esp.remote_AP)
# great, lets get the data
print("Posting data...", end='')
data=counter
feed='test'
payload={'value':data}
response=requests.post(
data = counter
feed = 'test'
payload = {'value':data}
response = wifi.post(
"https://io.adafruit.com/api/v2/"+secrets['aio_username']+"/feeds/"+feed+"/data",
json=payload,headers={bytes("X-AIO-KEY","utf-8"):bytes(secrets['aio_key'],"utf-8")})
json=payload,
headers={bytes("X-AIO-KEY", "utf-8"):bytes(secrets['aio_key'], "utf-8")})
print(response.json())
response.close()
counter = counter + 1
print("OK")
except (ValueError, RuntimeError, adafruit_espatcontrol.OKError) as e:
print("Failed to get data, retrying\n", e)
wifi.reset()
continue
response = None
time.sleep(10)
time.sleep(15)
Loading