Compare commits

...

54 commits

Author SHA1 Message Date
dherrada
01f3f6674b Fixed discord invite link 2020-07-08 16:49:04 -04:00
Scott Shawcroft
4f2f8c9f99
Merge pull request #88 from adafruit/tannewt-patch-2
Use secrets.py for ssid and password.
2020-07-06 15:16:19 -07:00
Scott Shawcroft
15f2a45a5d
Use secrets import from other examples 2020-07-06 15:12:19 -07:00
Scott Shawcroft
93b17712e7
lint 2020-07-03 13:43:18 -07:00
Scott Shawcroft
dbe91f0f7f
Merge branch 'master' into tannewt-patch-2 2020-07-02 15:45:08 -07:00
Scott Shawcroft
522df976fd
Merge pull request #99 from Flameeyes/master
Apply REUSE recommendations for code, documentation, and examples licensing.
2020-06-01 14:55:35 -07:00
Diego Elio Pettenò
f70ac1ad67 Add a pre-commit hook configuration to check YAML and whitespace.
These are minor, but avoids those coming up during reviews at all.

Signed-off-by: Diego Elio Pettenò <flameeyes@flameeyes.com>
2020-05-30 10:36:49 +01:00
Diego Elio Pettenò
2077d83a49 Move black testing definition as part of pre-commit.
For this to work, the black command line options need to be replaced with a
pyproject.toml file defining the settings, that can be reused.
2020-05-30 10:36:49 +01:00
Diego Elio Pettenò
5daca027ed Add pre-commit configuration and integration for REUSE.software.
pre-commit.com provides a way to configure pre-commit hooks for multiple
tools, including `reuse lint` (configured here), isort, black, and more.

This is also integrated with GitHub actions in the example configuration.
2020-05-30 10:36:49 +01:00
Diego Elio Pettenò
dd7b4fffc4 Apply SPDX copyright and license headers in compliance with REUSE.
The REUSE specifications[1] are meant to make it explicit and easier to
apply code licensing information for a project. The provided lint tool
makes it easy to ensure all the content (code and not code) is tagged.

Important notes:

 * All the code (and documentation) that otherwise didn't have an explicit
   license headers have been tagged with ladyada's copyright as per the
   LICENSE file.
 * favicon.ico and CODE_OF_CONDUCT.md have been synced from the
   source-of-truth repositories.
 * All configuration files have been tagged with ladyada's copyright and
   Unlicense[2]. The current REUSE recommendation is to use CC0-1.0, but
   that has… side effects. There's some discussion in [3] about the
   recommendation for likely-uncopyrightable files (such as configuration
   files).

[1]: https://reuse.software/
[2]: https://unlicense.org/
[3]: https://github.com/fsfe/reuse-docs/issues/62
2020-05-30 10:36:49 +01:00
Diego Elio Pettenò
d15014f9aa Sync Code of Conduct from source-of-truth repository. 2020-05-30 10:36:44 +01:00
Brent Rubell
94b03517c1
Merge pull request #97 from dearmash/master
Add UDP support
2020-05-07 09:25:50 -04:00
Brent Rubell
96887eeb60
Merge pull request #98 from brentru/update-simpletest
Update Simpletest
2020-05-05 10:59:56 -04:00
brentru
b9154b55d6 add airlift shield, reflect featherwing 2020-05-05 10:29:44 -04:00
Harold De Armas
974820a293 Clarify log statemeny 2020-04-30 14:04:59 -07:00
Harold De Armas
2c0466f786 fix indentation for easier merge 2020-04-30 00:17:50 -07:00
Harold De Armas
82edb0ab39 pylint 2020-04-30 00:15:36 -07:00
Harold De Armas
aa96dd1448 pylint 2020-04-30 00:13:04 -07:00
Harold De Armas
f437871fa3 Formatting 2020-04-30 00:02:47 -07:00
Harold De Armas
138bccbe9e Add UDP support
Writing to UDP requires separate APIs to use to append data and finalize.

TCP sends and confirms per-write and finalize is a no-op.  UDP appends to a buffer and finalize sends all at once.

The simple socket_open method doesn't actually create a socket per https://github.com/arduino/nina-fw.

Since socket_connect is a convenience method anyway, and connect doesn't really make sense for UDP, add the start_server call for UDP to that method to have a socket to write as well as read on.

e.x. usage

esp.socket_connect(socket_num, dest, port, esp.UDP_MODE)
esp.socket_write(socket_num, buffer, esp.UDP_MODE)
avail = esp.socket_available(socket_num)
recv = esp.socket_read(socket_num, avail)
esp.socket_close(socket_num)
2020-04-29 23:54:40 -07:00
Brent Rubell
3cf7b8a2a8
Merge pull request #89 from anecdata/gpio
Example using ESP32 GPIO pins from CircuitPython
2020-04-21 14:08:24 -04:00
anecdata
5e5a5a526c removed unnecessary code 2020-04-21 11:31:05 -05:00
anecdata
4d5f884f52 fix pylint 2020-04-21 10:37:13 -05:00
anecdata
bfdac54d8a fix pylint 2020-04-21 10:23:26 -05:00
anecdata
8a9ed1ae9e locally black'd output file 2020-04-21 10:13:20 -05:00
anecdata
bbbd5f79d2 Fix black error(s) 2020-04-21 09:51:52 -05:00
anecdata
64528f50a9 Minor comment edits 2020-04-20 23:13:52 -05:00
Scott Shawcroft
4c327a39a3
Merge pull request #96 from adafruit/black-update
Black reformatting with Python 3 target.
2020-04-09 09:38:14 -07:00
Kattni Rembor
8bb6884fb3 Black reformatting with Python 3 target. 2020-04-08 15:07:27 -04:00
sommersoft
37e3ca2ae0 build.yml: add black formatting check
Signed-off-by: sommersoft <sommersoft@gmail.com>
2020-04-07 16:09:52 -05:00
Kattni
bbccf26580
Merge pull request #93 from adafruit/pylint-update
Ran black, updated to pylint 2.x
2020-03-17 15:20:06 -04:00
dherrada
d387561329 Ran black, updated to pylint 2.x 2020-03-16 15:56:34 -04:00
sommersoft
29a457bfd5 update code of coduct: discord moderation contact section
Signed-off-by: sommersoft <sommersoft@gmail.com>
2020-03-15 18:31:29 -05:00
sommersoft
bb21a87b84
Merge pull request #92 from sommersoft/patch_coc
Update Code of Conduct
2020-03-13 14:57:44 -05:00
sommersoft
c5727b1707 update code of conduct 2020-03-13 13:57:51 -05:00
sommersoft
a73ca4cc50 update pylintrc for black
Signed-off-by: sommersoft <sommersoft@gmail.com>
2020-03-08 19:11:47 -05:00
sommersoft
1f84da8cd1 build.yml: move pylint, black, and Sphinx installs to each repo; add description to 'actions-ci/install.sh'
Signed-off-by: sommersoft <sommersoft@gmail.com>
2020-03-05 10:11:09 -06:00
Kattni
c29ea4ae49
Merge pull request #91 from FoamyGuy/master
trying single line comments for pylint
2020-02-28 14:19:44 -05:00
FoamyGuy
4965fcc04f trying single line comments for pylint 2020-02-28 13:07:16 -06:00
foamyguy
fbbe97788e
Merge pull request #66 from mytechnotalent/ESP32-MAC-order-library-fix
Fixed MAC reverse byte order issue within the ESP32SPI library as it …
2020-02-27 21:43:24 -06:00
anecdata
f6c3e5e9c9 simplified print output 2020-02-21 10:00:00 -06:00
anecdata
927476a3b4 improve comments 2020-02-21 09:37:57 -06:00
anecdata
0d0da219ce Fix PyLint issue 2020-02-21 09:30:49 -06:00
anecdata
f3c18ef140 Fix Pylint issues 2020-02-21 09:19:04 -06:00
anecdata
936ad82652 Merge branch 'gpio' of https://github.com/anecdata/Adafruit_CircuitPython_ESP32SPI into gpio 2020-02-21 09:05:11 -06:00
anecdata
a25513a228 Example of using ESP32 pins as GPIO 2020-02-21 09:00:54 -06:00
anecdata
68e5b5280c ESP32SPI GPIO example & documentation 2020-02-20 23:59:04 -06:00
Limor "Ladyada" Fried
f523b2316b
Merge pull request #87 from adafruit/tannewt-patch-1
Add pins for Itsy M4 AirLift
2020-01-30 22:54:10 -05:00
Scott Shawcroft
d22f1a4025
Use secrets.py for ssid and password. 2020-01-30 19:48:12 -08:00
mytechnotalent
00b6b952d4 Updated comment for new function. 2019-08-22 04:56:09 -04:00
mytechnotalent
da9f67fef2 Fixed MAC reverse byte order by adding new function to the ESP32SPI library calling the actual MAC address and providing a usage of the function in the webserver code within WSGISERVER. This time with line breaks at end to not break Travis. 2019-08-22 04:49:36 -04:00
mytechnotalent
3fd6a12118 Fixed MAC reverse byte order by adding new function to the ESP32SPI library calling the actual MAC address and providing a usage of the function in the webserver code within WSGISERVER. 2019-08-22 04:46:51 -04:00
mytechnotalent
ec97d6b068 Fixedblank line issus at EOF so Travis can run. 2019-08-21 07:30:07 -04:00
mytechnotalent
87095f617e Fixed MAC reverse byte order issue within the ESP32SPI library as it was originally echoing the MAC address in reverse byte order. Added portable MAC function call within WSGISERVER.PY example to properly echo MAC address when running example. 2019-08-21 07:03:15 -04:00
38 changed files with 1430 additions and 559 deletions

View file

@ -1,3 +1,7 @@
# SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
#
# SPDX-License-Identifier: Unlicense
name: Build CI name: Build CI
on: [pull_request, push] on: [pull_request, push]
@ -34,11 +38,18 @@ jobs:
with: with:
repository: adafruit/actions-ci-circuitpython-libs repository: adafruit/actions-ci-circuitpython-libs
path: actions-ci path: actions-ci
- name: Install deps - name: Install dependencies
# (e.g. - apt-get: gettext, etc; pip: circuitpython-build-tools, requirements.txt; etc.)
run: | run: |
source actions-ci/install.sh source actions-ci/install.sh
- name: Pip install pylint, Sphinx, pre-commit
run: |
pip install --force-reinstall pylint Sphinx sphinx-rtd-theme pre-commit
- name: Library version - name: Library version
run: git describe --dirty --always --tags run: git describe --dirty --always --tags
- name: Pre-commit hooks
run: |
pre-commit run --all-files
- name: PyLint - name: PyLint
run: | run: |
pylint $( find . -path './adafruit*.py' ) pylint $( find . -path './adafruit*.py' )

View file

@ -1,3 +1,7 @@
# SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
#
# SPDX-License-Identifier: Unlicense
name: Release Actions name: Release Actions
on: on:

4
.gitignore vendored
View file

@ -1,3 +1,7 @@
# SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
#
# SPDX-License-Identifier: Unlicense
*.mpy *.mpy
.idea .idea
__pycache__ __pycache__

19
.pre-commit-config.yaml Normal file
View file

@ -0,0 +1,19 @@
# SPDX-FileCopyrightText: 2020 Diego Elio Pettenò
#
# SPDX-License-Identifier: Unlicense
repos:
- repo: https://github.com/python/black
rev: 19.10b0
hooks:
- id: black
- repo: https://github.com/fsfe/reuse-tool
rev: latest
hooks:
- id: reuse
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.3.0
hooks:
- id: check-yaml
- id: end-of-file-fixer
- id: trailing-whitespace

View file

@ -1,3 +1,7 @@
# SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
#
# SPDX-License-Identifier: Unlicense
[MASTER] [MASTER]
# A comma-separated list of package or module names from where C extensions may # A comma-separated list of package or module names from where C extensions may
@ -52,7 +56,7 @@ confidence=
# no Warning level messages displayed, use"--disable=all --enable=classes # no Warning level messages displayed, use"--disable=all --enable=classes
# --disable=W" # --disable=W"
# disable=import-error,print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call # disable=import-error,print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call
disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error,bad-continuation
# Enable the message, report, category or checker with the given id(s). You can # Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option # either give multiple identifier separated by comma (,) or put this option

View file

@ -1,3 +1,7 @@
# SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
#
# SPDX-License-Identifier: Unlicense
python: python:
version: 3 version: 3
requirements_file: requirements.txt requirements_file: requirements.txt

View file

@ -1,3 +1,9 @@
<!--
SPDX-FileCopyrightText: 2014 Coraline Ada Ehmke
SPDX-FileCopyrightText: 2019 Kattni Rembor for Adafruit Industries
SPDX-License-Identifier: CC-BY-4.0
-->
# Adafruit Community Code of Conduct # Adafruit Community Code of Conduct
## Our Pledge ## Our Pledge
@ -34,6 +40,8 @@ Examples of unacceptable behavior by participants include:
* Excessive or unwelcome helping; answering outside the scope of the question * Excessive or unwelcome helping; answering outside the scope of the question
asked asked
* Trolling, insulting/derogatory comments, and personal or political attacks * Trolling, insulting/derogatory comments, and personal or political attacks
* Promoting or spreading disinformation, lies, or conspiracy theories against
a person, group, organisation, project, or community
* Public or private harassment * Public or private harassment
* Publishing others' private information, such as a physical or electronic * Publishing others' private information, such as a physical or electronic
address, without explicit permission address, without explicit permission
@ -72,10 +80,10 @@ You may report in the following ways:
In any situation, you may send an email to <support@adafruit.com>. In any situation, you may send an email to <support@adafruit.com>.
On the Adafruit Discord, you may send an open message from any channel On the Adafruit Discord, you may send an open message from any channel
to all Community Helpers by tagging @community helpers. You may also send an to all Community Moderators by tagging @community moderators. You may
open message from any channel, or a direct message to @kattni#1507, also send an open message from any channel, or a direct message to
@tannewt#4653, @Dan Halbert#1614, @cater#2442, @sommersoft#0222, or @kattni#1507, @tannewt#4653, @danh#1614, @cater#2442,
@Andon#8175. @sommersoft#0222, @Mr. Certainly#0472 or @Andon#8175.
Email and direct message reports will be kept confidential. Email and direct message reports will be kept confidential.

324
LICENSES/CC-BY-4.0.txt Normal file
View file

@ -0,0 +1,324 @@
Creative Commons Attribution 4.0 International Creative Commons Corporation
("Creative Commons") is not a law firm and does not provide legal services
or legal advice. Distribution of Creative Commons public licenses does not
create a lawyer-client or other relationship. Creative Commons makes its licenses
and related information available on an "as-is" basis. Creative Commons gives
no warranties regarding its licenses, any material licensed under their terms
and conditions, or any related information. Creative Commons disclaims all
liability for damages resulting from their use to the fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and conditions
that creators and other rights holders may use to share original works of
authorship and other material subject to copyright and certain other rights
specified in the public license below. The following considerations are for
informational purposes only, are not exhaustive, and do not form part of our
licenses.
Considerations for licensors: Our public licenses are intended for use by
those authorized to give the public permission to use material in ways otherwise
restricted by copyright and certain other rights. Our licenses are irrevocable.
Licensors should read and understand the terms and conditions of the license
they choose before applying it. Licensors should also secure all rights necessary
before applying our licenses so that the public can reuse the material as
expected. Licensors should clearly mark any material not subject to the license.
This includes other CC-licensed material, or material used under an exception
or limitation to copyright. More considerations for licensors : wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public licenses, a licensor
grants the public permission to use the licensed material under specified
terms and conditions. If the licensor's permission is not necessary for any
reasonfor example, because of any applicable exception or limitation to copyrightthen
that use is not regulated by the license. Our licenses grant only permissions
under copyright and certain other rights that a licensor has authority to
grant. Use of the licensed material may still be restricted for other reasons,
including because others have copyright or other rights in the material. A
licensor may make special requests, such as asking that all changes be marked
or described. Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More considerations for the public
: wiki.creativecommons.org/Considerations_for_licensees Creative Commons Attribution
4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree to
be bound by the terms and conditions of this Creative Commons Attribution
4.0 International Public License ("Public License"). To the extent this Public
License may be interpreted as a contract, You are granted the Licensed Rights
in consideration of Your acceptance of these terms and conditions, and the
Licensor grants You such rights in consideration of benefits the Licensor
receives from making the Licensed Material available under these terms and
conditions.
Section 1 Definitions.
a. Adapted Material means material subject to Copyright and Similar Rights
that is derived from or based upon the Licensed Material and in which the
Licensed Material is translated, altered, arranged, transformed, or otherwise
modified in a manner requiring permission under the Copyright and Similar
Rights held by the Licensor. For purposes of this Public License, where the
Licensed Material is a musical work, performance, or sound recording, Adapted
Material is always produced where the Licensed Material is synched in timed
relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright and Similar
Rights in Your contributions to Adapted Material in accordance with the terms
and conditions of this Public License.
c. Copyright and Similar Rights means copyright and/or similar rights closely
related to copyright including, without limitation, performance, broadcast,
sound recording, and Sui Generis Database Rights, without regard to how the
rights are labeled or categorized. For purposes of this Public License, the
rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
d. Effective Technological Measures means those measures that, in the absence
of proper authority, may not be circumvented under laws fulfilling obligations
under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996,
and/or similar international agreements.
e. Exceptions and Limitations means fair use, fair dealing, and/or any other
exception or limitation to Copyright and Similar Rights that applies to Your
use of the Licensed Material.
f. Licensed Material means the artistic or literary work, database, or other
material to which the Licensor applied this Public License.
g. Licensed Rights means the rights granted to You subject to the terms and
conditions of this Public License, which are limited to all Copyright and
Similar Rights that apply to Your use of the Licensed Material and that the
Licensor has authority to license.
h. Licensor means the individual(s) or entity(ies) granting rights under this
Public License.
i. Share means to provide material to the public by any means or process that
requires permission under the Licensed Rights, such as reproduction, public
display, public performance, distribution, dissemination, communication, or
importation, and to make material available to the public including in ways
that members of the public may access the material from a place and at a time
individually chosen by them.
j. Sui Generis Database Rights means rights other than copyright resulting
from Directive 96/9/EC of the European Parliament and of the Council of 11
March 1996 on the legal protection of databases, as amended and/or succeeded,
as well as other essentially equivalent rights anywhere in the world.
k. You means the individual or entity exercising the Licensed Rights under
this Public License. Your has a corresponding meaning.
Section 2 Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License, the Licensor
hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive,
irrevocable license to exercise the Licensed Rights in the Licensed Material
to:
A. reproduce and Share the Licensed Material, in whole or in part; and
B. produce, reproduce, and Share Adapted Material.
2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions
and Limitations apply to Your use, this Public License does not apply, and
You do not need to comply with its terms and conditions.
3. Term. The term of this Public License is specified in Section 6(a).
4. Media and formats; technical modifications allowed. The Licensor authorizes
You to exercise the Licensed Rights in all media and formats whether now known
or hereafter created, and to make technical modifications necessary to do
so. The Licensor waives and/or agrees not to assert any right or authority
to forbid You from making technical modifications necessary to exercise the
Licensed Rights, including technical modifications necessary to circumvent
Effective Technological Measures. For purposes of this Public License, simply
making modifications authorized by this Section 2(a)(4) never produces Adapted
Material.
5. Downstream recipients.
A. Offer from the Licensor Licensed Material. Every recipient of the Licensed
Material automatically receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this Public License.
B. No downstream restrictions. You may not offer or impose any additional
or different terms or conditions on, or apply any Effective Technological
Measures to, the Licensed Material if doing so restricts exercise of the Licensed
Rights by any recipient of the Licensed Material.
6. No endorsement. Nothing in this Public License constitutes or may be construed
as permission to assert or imply that You are, or that Your use of the Licensed
Material is, connected with, or sponsored, endorsed, or granted official status
by, the Licensor or others designated to receive attribution as provided in
Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not licensed under this
Public License, nor are publicity, privacy, and/or other similar personality
rights; however, to the extent possible, the Licensor waives and/or agrees
not to assert any such rights held by the Licensor to the limited extent necessary
to allow You to exercise the Licensed Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this Public License.
3. To the extent possible, the Licensor waives any right to collect royalties
from You for the exercise of the Licensed Rights, whether directly or through
a collecting society under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly reserves any right
to collect such royalties.
Section 3 License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the following
conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified form), You must:
A. retain the following if it is supplied by the Licensor with the Licensed
Material:
i. identification of the creator(s) of the Licensed Material and any others
designated to receive attribution, in any reasonable manner requested by the
Licensor (including by pseudonym if designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of warranties;
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
B. indicate if You modified the Licensed Material and retain an indication
of any previous modifications; and
C. indicate the Licensed Material is licensed under this Public License, and
include the text of, or the URI or hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner
based on the medium, means, and context in which You Share the Licensed Material.
For example, it may be reasonable to satisfy the conditions by providing a
URI or hyperlink to a resource that includes the required information.
3. If requested by the Licensor, You must remove any of the information required
by Section 3(a)(1)(A) to the extent reasonably practicable.
4. If You Share Adapted Material You produce, the Adapter's License You apply
must not prevent recipients of the Adapted Material from complying with this
Public License.
Section 4 Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that apply to
Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract,
reuse, reproduce, and Share all or a substantial portion of the contents of
the database;
b. if You include all or a substantial portion of the database contents in
a database in which You have Sui Generis Database Rights, then the database
in which You have Sui Generis Database Rights (but not its individual contents)
is Adapted Material; and
c. You must comply with the conditions in Section 3(a) if You Share all or
a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not replace
Your obligations under this Public License where the Licensed Rights include
other Copyright and Similar Rights.
Section 5 Disclaimer of Warranties and Limitation of Liability.
a. Unless otherwise separately undertaken by the Licensor, to the extent possible,
the Licensor offers the Licensed Material as-is and as-available, and makes
no representations or warranties of any kind concerning the Licensed Material,
whether express, implied, statutory, or other. This includes, without limitation,
warranties of title, merchantability, fitness for a particular purpose, non-infringement,
absence of latent or other defects, accuracy, or the presence or absence of
errors, whether or not known or discoverable. Where disclaimers of warranties
are not allowed in full or in part, this disclaimer may not apply to You.
b. To the extent possible, in no event will the Licensor be liable to You
on any legal theory (including, without limitation, negligence) or otherwise
for any direct, special, indirect, incidental, consequential, punitive, exemplary,
or other losses, costs, expenses, or damages arising out of this Public License
or use of the Licensed Material, even if the Licensor has been advised of
the possibility of such losses, costs, expenses, or damages. Where a limitation
of liability is not allowed in full or in part, this limitation may not apply
to You.
c. The disclaimer of warranties and limitation of liability provided above
shall be interpreted in a manner that, to the extent possible, most closely
approximates an absolute disclaimer and waiver of all liability.
Section 6 Term and Termination.
a. This Public License applies for the term of the Copyright and Similar Rights
licensed here. However, if You fail to comply with this Public License, then
Your rights under this Public License terminate automatically.
b. Where Your right to use the Licensed Material has terminated under Section
6(a), it reinstates:
1. automatically as of the date the violation is cured, provided it is cured
within 30 days of Your discovery of the violation; or
2. upon express reinstatement by the Licensor.
c. For the avoidance of doubt, this Section 6(b) does not affect any right
the Licensor may have to seek remedies for Your violations of this Public
License.
d. For the avoidance of doubt, the Licensor may also offer the Licensed Material
under separate terms or conditions or stop distributing the Licensed Material
at any time; however, doing so will not terminate this Public License.
e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
Section 7 Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or
conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the Licensed
Material not stated herein are separate from and independent of the terms
and conditions of this Public License.
Section 8 Interpretation.
a. For the avoidance of doubt, this Public License does not, and shall not
be interpreted to, reduce, limit, restrict, or impose conditions on any use
of the Licensed Material that could lawfully be made without permission under
this Public License.
b. To the extent possible, if any provision of this Public License is deemed
unenforceable, it shall be automatically reformed to the minimum extent necessary
to make it enforceable. If the provision cannot be reformed, it shall be severed
from this Public License without affecting the enforceability of the remaining
terms and conditions.
c. No term or condition of this Public License will be waived and no failure
to comply consented to unless expressly agreed to by the Licensor.
d. Nothing in this Public License constitutes or may be interpreted as a limitation
upon, or waiver of, any privileges and immunities that apply to the Licensor
or You, including from the legal processes of any jurisdiction or authority.
Creative Commons is not a party to its public licenses. Notwithstanding, Creative
Commons may elect to apply one of its public licenses to material it publishes
and in those instances will be considered the "Licensor." The text of the
Creative Commons public licenses is dedicated to the public domain under the
CC0 Public Domain Dedication. Except for the limited purpose of indicating
that material is shared under a Creative Commons public license or as otherwise
permitted by the Creative Commons policies published at creativecommons.org/policies,
Creative Commons does not authorize the use of the trademark "Creative Commons"
or any other trademark or logo of Creative Commons without its prior written
consent including, without limitation, in connection with any unauthorized
modifications to any of its public licenses or any other arrangements, understandings,
or agreements concerning use of licensed material. For the avoidance of doubt,
this paragraph does not form part of the public licenses.
Creative Commons may be contacted at creativecommons.org.

19
LICENSES/MIT.txt Normal file
View file

@ -0,0 +1,19 @@
MIT License Copyright (c) <year> <copyright holders>
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 (including the next
paragraph) 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.

20
LICENSES/Unlicense.txt Normal file
View file

@ -0,0 +1,20 @@
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute
this software, either in source code form or as a compiled binary, for any
purpose, commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and
to the detriment of our heirs and successors. We intend this dedication to
be an overt act of relinquishment in perpetuity of all present and future
rights to this software under copyright law.
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
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. For more information,
please refer to <https://unlicense.org/>

View file

@ -6,7 +6,7 @@ Introduction
:alt: Documentation Status :alt: Documentation Status
.. image:: https://img.shields.io/discord/327254708534116352.svg .. image:: https://img.shields.io/discord/327254708534116352.svg
:target: https://discord.gg/nBQh6qu :target: https://adafru.it/discord
:alt: Discord :alt: Discord
.. image:: https://github.com/adafruit/Adafruit_CircuitPython_ESP32SPI/workflows/Build%20CI/badge.svg .. image:: https://github.com/adafruit/Adafruit_CircuitPython_ESP32SPI/workflows/Build%20CI/badge.svg

3
README.rst.license Normal file
View file

@ -0,0 +1,3 @@
SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
SPDX-License-Identifier: MIT

View file

@ -1,24 +1,7 @@
# The MIT License (MIT) # SPDX-FileCopyrightText: Copyright (c) 2019 Brent Rubell for Adafruit Industries
# #
# Copyright (c) 2019 Brent Rubell for Adafruit Industries # SPDX-License-Identifier: MIT
#
# 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`
============================== ==============================
@ -27,7 +10,8 @@ PWMOut CircuitPython API for ESP32SPI.
* Author(s): Brent Rubell * Author(s): Brent Rubell
""" """
class PWMOut():
class PWMOut:
""" """
Implementation of CircuitPython PWMOut for ESP32SPI. Implementation of CircuitPython PWMOut for ESP32SPI.
@ -37,16 +21,18 @@ class PWMOut():
:param int frequency: The target frequency in Hertz (32-bit). :param int frequency: The target frequency in Hertz (32-bit).
:param bool variable_frequency: True if the frequency will change over time. :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, ESP32_PWM_PINS = set(
16, 17, 18, 19, [0, 1, 2, 4, 5, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 25, 26, 27, 32, 33]
21, 22, 23, 25, )
26, 27, 32, 33])
def __init__(self, esp, pwm_pin, *, frequency=500, duty_cycle=0, variable_frequency=False): def __init__(
self, esp, pwm_pin, *, frequency=500, duty_cycle=0, variable_frequency=False
):
if pwm_pin in self.ESP32_PWM_PINS: if pwm_pin in self.ESP32_PWM_PINS:
self._pwm_pin = pwm_pin self._pwm_pin = pwm_pin
else: else:
raise AttributeError("Pin %d is not a valid ESP32 GPIO Pin."%pwm_pin) raise AttributeError("Pin %d is not a valid ESP32 GPIO Pin." % pwm_pin)
self._esp = esp self._esp = esp
self._duty_cycle = duty_cycle self._duty_cycle = duty_cycle
self._freq = frequency self._freq = frequency
@ -67,8 +53,10 @@ class PWMOut():
def _is_deinited(self): def _is_deinited(self):
"""Checks if PWMOut object has been previously de-initalized""" """Checks if PWMOut object has been previously de-initalized"""
if self._pwm_pin is None: if self._pwm_pin is None:
raise ValueError("PWMOut Object has been deinitialized and can no longer " raise ValueError(
"be used. Create a new PWMOut object.") "PWMOut Object has been deinitialized and can no longer "
"be used. Create a new PWMOut object."
)
@property @property
def duty_cycle(self): def duty_cycle(self):

267
adafruit_esp32spi/adafruit_esp32spi.py Normal file → Executable file
View file

@ -1,24 +1,7 @@
# The MIT License (MIT) # SPDX-FileCopyrightText: Copyright (c) 2019 ladyada for Adafruit Industries
# #
# Copyright (c) 2019 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT
#
# 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_esp32spi` `adafruit_esp32spi`
================================================================================ ================================================================================
@ -83,6 +66,7 @@ _REQ_HOST_BY_NAME_CMD = const(0x34)
_GET_HOST_BY_NAME_CMD = const(0x35) _GET_HOST_BY_NAME_CMD = const(0x35)
_START_SCAN_NETWORKS = const(0x36) _START_SCAN_NETWORKS = const(0x36)
_GET_FW_VERSION_CMD = const(0x37) _GET_FW_VERSION_CMD = const(0x37)
_SEND_UDP_DATA_CMD = const(0x39)
_GET_TIME = const(0x3B) _GET_TIME = const(0x3B)
_GET_IDX_BSSID_CMD = const(0x3C) _GET_IDX_BSSID_CMD = const(0x3C)
_GET_IDX_CHAN_CMD = const(0x3D) _GET_IDX_CHAN_CMD = const(0x3D)
@ -90,6 +74,7 @@ _PING_CMD = const(0x3E)
_SEND_DATA_TCP_CMD = const(0x44) _SEND_DATA_TCP_CMD = const(0x44)
_GET_DATABUF_TCP_CMD = const(0x45) _GET_DATABUF_TCP_CMD = const(0x45)
_INSERT_DATABUF_TCP_CMD = const(0x46)
_SET_ENT_IDENT_CMD = const(0x4A) _SET_ENT_IDENT_CMD = const(0x4A)
_SET_ENT_UNAME_CMD = const(0x4B) _SET_ENT_UNAME_CMD = const(0x4B)
_SET_ENT_PASSWD_CMD = const(0x4C) _SET_ENT_PASSWD_CMD = const(0x4C)
@ -106,7 +91,7 @@ _SET_ANALOG_READ_CMD = const(0x54)
_START_CMD = const(0xE0) _START_CMD = const(0xE0)
_END_CMD = const(0xEE) _END_CMD = const(0xEE)
_ERR_CMD = const(0xEF) _ERR_CMD = const(0xEF)
_REPLY_FLAG = const(1<<7) _REPLY_FLAG = const(1 << 7)
_CMD_FLAG = const(0) _CMD_FLAG = const(0)
SOCKET_CLOSED = const(0) SOCKET_CLOSED = const(0)
@ -140,15 +125,19 @@ ADC_ATTEN_DB_6 = const(2)
ADC_ATTEN_DB_11 = const(3) ADC_ATTEN_DB_11 = const(3)
# pylint: enable=bad-whitespace # pylint: enable=bad-whitespace
class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-instance-attributes class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-instance-attributes
"""A class that will talk to an ESP32 module programmed with special firmware """A class that will talk to an ESP32 module programmed with special firmware
that lets it act as a fast an efficient WiFi co-processor""" that lets it act as a fast an efficient WiFi co-processor"""
TCP_MODE = const(0) TCP_MODE = const(0)
UDP_MODE = const(1) UDP_MODE = const(1)
TLS_MODE = const(2) TLS_MODE = const(2)
# pylint: disable=too-many-arguments # pylint: disable=too-many-arguments
def __init__(self, spi, cs_pin, ready_pin, reset_pin, gpio0_pin=None, *, debug=False): def __init__(
self, spi, cs_pin, ready_pin, reset_pin, gpio0_pin=None, *, debug=False
):
self._debug = debug self._debug = debug
self.set_psk = False self.set_psk = False
self.set_crt = False self.set_crt = False
@ -168,6 +157,7 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
if self._gpio0: if self._gpio0:
self._gpio0.direction = Direction.INPUT self._gpio0.direction = Direction.INPUT
self.reset() self.reset()
# pylint: enable=too-many-arguments # pylint: enable=too-many-arguments
def reset(self): def reset(self):
@ -188,13 +178,13 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
def _wait_for_ready(self): def _wait_for_ready(self):
"""Wait until the ready pin goes low""" """Wait until the ready pin goes low"""
if self._debug >= 3: if self._debug >= 3:
print("Wait for ESP32 ready", end='') print("Wait for ESP32 ready", end="")
times = time.monotonic() times = time.monotonic()
while (time.monotonic() - times) < 10: # wait up to 10 seconds while (time.monotonic() - times) < 10: # wait up to 10 seconds
if not self._ready.value: # we're ready! if not self._ready.value: # we're ready!
break break
if self._debug >= 3: if self._debug >= 3:
print('.', end='') print(".", end="")
time.sleep(0.05) time.sleep(0.05)
else: else:
raise RuntimeError("ESP32 not responding") raise RuntimeError("ESP32 not responding")
@ -234,7 +224,7 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
self._sendbuf[ptr] = len(param) & 0xFF self._sendbuf[ptr] = len(param) & 0xFF
ptr += 1 ptr += 1
for j, par in enumerate(param): for j, par in enumerate(param):
self._sendbuf[ptr+j] = par self._sendbuf[ptr + j] = par
ptr += len(param) ptr += len(param)
self._sendbuf[ptr] = _END_CMD self._sendbuf[ptr] = _END_CMD
@ -246,9 +236,12 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
break break
else: else:
raise RuntimeError("ESP32 timed out on SPI select") raise RuntimeError("ESP32 timed out on SPI select")
spi.write(self._sendbuf, start=0, end=packet_len) # pylint: disable=no-member spi.write(
self._sendbuf, start=0, end=packet_len
) # pylint: disable=no-member
if self._debug >= 3: if self._debug >= 3:
print("Wrote: ", [hex(b) for b in self._sendbuf[0:packet_len]]) print("Wrote: ", [hex(b) for b in self._sendbuf[0:packet_len]])
# pylint: disable=too-many-branches # pylint: disable=too-many-branches
def _read_byte(self, spi): def _read_byte(self, spi):
@ -318,12 +311,20 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
print("Read %d: " % len(responses[0]), responses) print("Read %d: " % len(responses[0]), responses)
return responses return responses
def _send_command_get_response(self, cmd, params=None, *, def _send_command_get_response(
reply_params=1, sent_param_len_16=False, self,
recv_param_len_16=False): cmd,
params=None,
*,
reply_params=1,
sent_param_len_16=False,
recv_param_len_16=False
):
"""Send a high level SPI command, wait and return the response""" """Send a high level SPI command, wait and return the response"""
self._send_command(cmd, params, param_len_16=sent_param_len_16) self._send_command(cmd, params, param_len_16=sent_param_len_16)
return self._wait_response_cmd(cmd, reply_params, param_len_16=recv_param_len_16) return self._wait_response_cmd(
cmd, reply_params, param_len_16=recv_param_len_16
)
@property @property
def status(self): def status(self):
@ -351,9 +352,19 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
"""A bytearray containing the MAC address of the ESP32""" """A bytearray containing the MAC address of the ESP32"""
if self._debug: if self._debug:
print("MAC address") print("MAC address")
resp = self._send_command_get_response(_GET_MACADDR_CMD, [b'\xFF']) resp = self._send_command_get_response(_GET_MACADDR_CMD, [b"\xFF"])
return resp[0] return resp[0]
@property
def MAC_address_actual(self): # pylint: disable=invalid-name
"""A bytearray containing the actual MAC address of the ESP32"""
if self._debug:
print("MAC address")
resp = self._send_command_get_response(_GET_MACADDR_CMD, [b"\xFF"])
new_resp = bytearray(resp[0])
new_resp = reversed(new_resp)
return new_resp
def start_scan_networks(self): def start_scan_networks(self):
"""Begin a scan of visible access points. Follow up with a call """Begin a scan of visible access points. Follow up with a call
to 'get_scan_networks' for response""" to 'get_scan_networks' for response"""
@ -368,18 +379,18 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
'ssid', 'rssi', 'encryption', bssid, and channel entries, one for each AP found""" 'ssid', 'rssi', 'encryption', bssid, and channel entries, one for each AP found"""
self._send_command(_SCAN_NETWORKS) self._send_command(_SCAN_NETWORKS)
names = self._wait_response_cmd(_SCAN_NETWORKS) names = self._wait_response_cmd(_SCAN_NETWORKS)
#print("SSID names:", names) # print("SSID names:", names)
APs = [] # pylint: disable=invalid-name APs = [] # pylint: disable=invalid-name
for i, name in enumerate(names): for i, name in enumerate(names):
a_p = {'ssid': name} a_p = {"ssid": name}
rssi = self._send_command_get_response(_GET_IDX_RSSI_CMD, ((i,),))[0] rssi = self._send_command_get_response(_GET_IDX_RSSI_CMD, ((i,),))[0]
a_p['rssi'] = struct.unpack('<i', rssi)[0] a_p["rssi"] = struct.unpack("<i", rssi)[0]
encr = self._send_command_get_response(_GET_IDX_ENCT_CMD, ((i,),))[0] encr = self._send_command_get_response(_GET_IDX_ENCT_CMD, ((i,),))[0]
a_p['encryption'] = encr[0] a_p["encryption"] = encr[0]
bssid = self._send_command_get_response(_GET_IDX_BSSID_CMD, ((i,),))[0] bssid = self._send_command_get_response(_GET_IDX_BSSID_CMD, ((i,),))[0]
a_p['bssid'] = bssid a_p["bssid"] = bssid
chan = self._send_command_get_response(_GET_IDX_CHAN_CMD, ((i,),))[0] chan = self._send_command_get_response(_GET_IDX_CHAN_CMD, ((i,),))[0]
a_p['channel'] = chan[0] a_p["channel"] = chan[0]
APs.append(a_p) APs.append(a_p)
return APs return APs
@ -439,40 +450,44 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
def _wifi_set_ap_passphrase(self, ssid, passphrase, channel): def _wifi_set_ap_passphrase(self, ssid, passphrase, channel):
"""Creates an Access point with SSID, passphrase, and Channel""" """Creates an Access point with SSID, passphrase, and Channel"""
resp = self._send_command_get_response(_SET_AP_PASSPHRASE_CMD, [ssid, passphrase, channel]) resp = self._send_command_get_response(
_SET_AP_PASSPHRASE_CMD, [ssid, passphrase, channel]
)
if resp[0][0] != 1: if resp[0][0] != 1:
raise RuntimeError("Failed to setup AP password") raise RuntimeError("Failed to setup AP password")
@property @property
def ssid(self): def ssid(self):
"""The name of the access point we're connected to""" """The name of the access point we're connected to"""
resp = self._send_command_get_response(_GET_CURR_SSID_CMD, [b'\xFF']) resp = self._send_command_get_response(_GET_CURR_SSID_CMD, [b"\xFF"])
return resp[0] return resp[0]
@property @property
def bssid(self): def bssid(self):
"""The MAC-formatted service set ID of the access point we're connected to""" """The MAC-formatted service set ID of the access point we're connected to"""
resp = self._send_command_get_response(_GET_CURR_BSSID_CMD, [b'\xFF']) resp = self._send_command_get_response(_GET_CURR_BSSID_CMD, [b"\xFF"])
return resp[0] return resp[0]
@property @property
def rssi(self): def rssi(self):
"""The receiving signal strength indicator for the access point we're """The receiving signal strength indicator for the access point we're
connected to""" connected to"""
resp = self._send_command_get_response(_GET_CURR_RSSI_CMD, [b'\xFF']) resp = self._send_command_get_response(_GET_CURR_RSSI_CMD, [b"\xFF"])
return struct.unpack('<i', resp[0])[0] return struct.unpack("<i", resp[0])[0]
@property @property
def network_data(self): def network_data(self):
"""A dictionary containing current connection details such as the 'ip_addr', """A dictionary containing current connection details such as the 'ip_addr',
'netmask' and 'gateway'""" 'netmask' and 'gateway'"""
resp = self._send_command_get_response(_GET_IPADDR_CMD, [b'\xFF'], reply_params=3) resp = self._send_command_get_response(
return {'ip_addr': resp[0], 'netmask': resp[1], 'gateway': resp[2]} _GET_IPADDR_CMD, [b"\xFF"], reply_params=3
)
return {"ip_addr": resp[0], "netmask": resp[1], "gateway": resp[2]}
@property @property
def ip_address(self): def ip_address(self):
"""Our local IP address""" """Our local IP address"""
return self.network_data['ip_addr'] return self.network_data["ip_addr"]
@property @property
def is_connected(self): def is_connected(self):
@ -495,7 +510,7 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
def connect(self, secrets): def connect(self, secrets):
"""Connect to an access point using a secrets dictionary """Connect to an access point using a secrets dictionary
that contains a 'ssid' and 'password' entry""" that contains a 'ssid' and 'password' entry"""
self.connect_AP(secrets['ssid'], secrets['password']) self.connect_AP(secrets["ssid"], secrets["password"])
def connect_AP(self, ssid, password, timeout_s=10): # pylint: disable=invalid-name def connect_AP(self, ssid, password, timeout_s=10): # pylint: disable=invalid-name
""" """
@ -510,10 +525,10 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
if self._debug: if self._debug:
print("Connect to AP", ssid, password) print("Connect to AP", ssid, password)
if isinstance(ssid, str): if isinstance(ssid, str):
ssid = bytes(ssid, 'utf-8') ssid = bytes(ssid, "utf-8")
if password: if password:
if isinstance(password, str): if isinstance(password, str):
password = bytes(password, 'utf-8') password = bytes(password, "utf-8")
self.wifi_set_passphrase(ssid, password) self.wifi_set_passphrase(ssid, password)
else: else:
self.wifi_set_network(ssid) self.wifi_set_network(ssid)
@ -529,7 +544,9 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
raise RuntimeError("No such ssid", ssid) raise RuntimeError("No such ssid", ssid)
raise RuntimeError("Unknown error 0x%02X" % stat) raise RuntimeError("Unknown error 0x%02X" % stat)
def create_AP(self, ssid, password, channel=1, timeout=10): # pylint: disable=invalid-name def create_AP(
self, ssid, password, channel=1, timeout=10
): # pylint: disable=invalid-name
""" """
Create an access point with the given name, password, and channel. Create an access point with the given name, password, and channel.
Will wait until specified timeout seconds and return on success Will wait until specified timeout seconds and return on success
@ -550,10 +567,10 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
if isinstance(channel, int): if isinstance(channel, int):
channel = bytes(channel) channel = bytes(channel)
if isinstance(ssid, str): if isinstance(ssid, str):
ssid = bytes(ssid, 'utf-8') ssid = bytes(ssid, "utf-8")
if password: if password:
if isinstance(password, str): if isinstance(password, str):
password = bytes(password, 'utf-8') password = bytes(password, "utf-8")
self._wifi_set_ap_passphrase(ssid, password, channel) self._wifi_set_ap_passphrase(ssid, password, channel)
else: else:
self._wifi_set_ap_network(ssid, channel) self._wifi_set_ap_network(ssid, channel)
@ -574,7 +591,7 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
def unpretty_ip(self, ip): # pylint: disable=no-self-use, invalid-name def unpretty_ip(self, ip): # pylint: disable=no-self-use, invalid-name
"""Converts a dotted-quad string to a bytearray IP address""" """Converts a dotted-quad string to a bytearray IP address"""
octets = [int(x) for x in ip.split('.')] octets = [int(x) for x in ip.split(".")]
return bytes(octets) return bytes(octets)
def get_host_by_name(self, hostname): def get_host_by_name(self, hostname):
@ -583,7 +600,7 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
if self._debug: if self._debug:
print("*** Get host by name") print("*** Get host by name")
if isinstance(hostname, str): if isinstance(hostname, str):
hostname = bytes(hostname, 'utf-8') hostname = bytes(hostname, "utf-8")
resp = self._send_command_get_response(_REQ_HOST_BY_NAME_CMD, (hostname,)) resp = self._send_command_get_response(_REQ_HOST_BY_NAME_CMD, (hostname,))
if resp[0][0] != 1: if resp[0][0] != 1:
raise RuntimeError("Failed to request hostname") raise RuntimeError("Failed to request hostname")
@ -598,7 +615,7 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
# ttl must be between 0 and 255 # ttl must be between 0 and 255
ttl = max(0, min(ttl, 255)) ttl = max(0, min(ttl, 255))
resp = self._send_command_get_response(_PING_CMD, (dest, (ttl,))) resp = self._send_command_get_response(_PING_CMD, (dest, (ttl,)))
return struct.unpack('<H', resp[0])[0] return struct.unpack("<H", resp[0])[0]
def get_socket(self): def get_socket(self):
"""Request a socket from the ESP32, will allocate and return a number that """Request a socket from the ESP32, will allocate and return a number that
@ -621,19 +638,24 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
self._socknum_ll[0][0] = socket_num self._socknum_ll[0][0] = socket_num
if self._debug: if self._debug:
print("*** Open socket") print("*** Open socket")
port_param = struct.pack('>H', port) port_param = struct.pack(">H", port)
if isinstance(dest, str): # use the 5 arg version if isinstance(dest, str): # use the 5 arg version
dest = bytes(dest, 'utf-8') dest = bytes(dest, "utf-8")
resp = self._send_command_get_response(_START_CLIENT_TCP_CMD, resp = self._send_command_get_response(
(dest, b'\x00\x00\x00\x00', _START_CLIENT_TCP_CMD,
(
dest,
b"\x00\x00\x00\x00",
port_param, port_param,
self._socknum_ll[0], self._socknum_ll[0],
(conn_mode,))) (conn_mode,),
),
)
else: # ip address, use 4 arg vesion else: # ip address, use 4 arg vesion
resp = self._send_command_get_response(_START_CLIENT_TCP_CMD, resp = self._send_command_get_response(
(dest, port_param, _START_CLIENT_TCP_CMD,
self._socknum_ll[0], (dest, port_param, self._socknum_ll[0], (conn_mode,)),
(conn_mode,))) )
if resp[0][0] != 1: if resp[0][0] != 1:
raise RuntimeError("Could not connect to remote server") raise RuntimeError("Could not connect to remote server")
@ -643,28 +665,52 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
SOCKET_FIN_WAIT_2, SOCKET_CLOSE_WAIT, SOCKET_CLOSING, SOCKET_LAST_ACK, or SOCKET_FIN_WAIT_2, SOCKET_CLOSE_WAIT, SOCKET_CLOSING, SOCKET_LAST_ACK, or
SOCKET_TIME_WAIT""" SOCKET_TIME_WAIT"""
self._socknum_ll[0][0] = socket_num self._socknum_ll[0][0] = socket_num
resp = self._send_command_get_response(_GET_CLIENT_STATE_TCP_CMD, self._socknum_ll) resp = self._send_command_get_response(
_GET_CLIENT_STATE_TCP_CMD, self._socknum_ll
)
return resp[0][0] return resp[0][0]
def socket_connected(self, socket_num): def socket_connected(self, socket_num):
"""Test if a socket is connected to the destination, returns boolean true/false""" """Test if a socket is connected to the destination, returns boolean true/false"""
return self.socket_status(socket_num) == SOCKET_ESTABLISHED return self.socket_status(socket_num) == SOCKET_ESTABLISHED
def socket_write(self, socket_num, buffer): def socket_write(self, socket_num, buffer, conn_mode=TCP_MODE):
"""Write the bytearray buffer to a socket""" """Write the bytearray buffer to a socket"""
if self._debug: if self._debug:
print("Writing:", buffer) print("Writing:", buffer)
self._socknum_ll[0][0] = socket_num self._socknum_ll[0][0] = socket_num
sent = 0 sent = 0
for chunk in range((len(buffer) // 64)+1): total_chunks = (len(buffer) // 64) + 1
resp = self._send_command_get_response(_SEND_DATA_TCP_CMD, send_command = _SEND_DATA_TCP_CMD
(self._socknum_ll[0], if conn_mode == self.UDP_MODE: # UDP requires a different command to write
memoryview(buffer)[(chunk*64):((chunk+1)*64)]), send_command = _INSERT_DATABUF_TCP_CMD
sent_param_len_16=True) for chunk in range(total_chunks):
resp = self._send_command_get_response(
send_command,
(
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 conn_mode == self.UDP_MODE:
# UDP verifies chunks on write, not bytes
if sent != total_chunks:
raise RuntimeError(
"Failed to write %d chunks (sent %d)" % (total_chunks, sent)
)
# UDP needs to finalize with this command, does the actual sending
resp = self._send_command_get_response(_SEND_UDP_DATA_CMD, self._socknum_ll)
if resp[0][0] != 1:
raise RuntimeError("Failed to send UDP data")
return
if sent != len(buffer): if sent != len(buffer):
raise RuntimeError("Failed to send %d bytes (sent %d)" % (len(buffer), sent)) raise RuntimeError(
"Failed to send %d bytes (sent %d)" % (len(buffer), sent)
)
resp = self._send_command_get_response(_DATA_SENT_TCP_CMD, self._socknum_ll) resp = self._send_command_get_response(_DATA_SENT_TCP_CMD, self._socknum_ll)
if resp[0][0] != 1: if resp[0][0] != 1:
@ -674,7 +720,7 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
"""Determine how many bytes are waiting to be read on the socket""" """Determine how many bytes are waiting to be read on the socket"""
self._socknum_ll[0][0] = socket_num self._socknum_ll[0][0] = socket_num
resp = self._send_command_get_response(_AVAIL_DATA_TCP_CMD, self._socknum_ll) resp = self._send_command_get_response(_AVAIL_DATA_TCP_CMD, self._socknum_ll)
reply = struct.unpack('<H', resp[0])[0] reply = struct.unpack("<H", resp[0])[0]
if self._debug: if self._debug:
print("ESPSocket: %d bytes available" % reply) print("ESPSocket: %d bytes available" % reply)
return reply return reply
@ -682,14 +728,17 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
def socket_read(self, socket_num, size): def socket_read(self, socket_num, size):
"""Read up to 'size' bytes from the socket number. Returns a bytearray""" """Read up to 'size' bytes from the socket number. Returns a bytearray"""
if self._debug: if self._debug:
print("Reading %d bytes from ESP socket with status %d" % print(
(size, self.socket_status(socket_num))) "Reading %d bytes from ESP socket with status %d"
% (size, self.socket_status(socket_num))
)
self._socknum_ll[0][0] = socket_num self._socknum_ll[0][0] = socket_num
resp = self._send_command_get_response(_GET_DATABUF_TCP_CMD, resp = self._send_command_get_response(
(self._socknum_ll[0], _GET_DATABUF_TCP_CMD,
(size & 0xFF, (size >> 8) & 0xFF)), (self._socknum_ll[0], (size & 0xFF, (size >> 8) & 0xFF)),
sent_param_len_16=True, sent_param_len_16=True,
recv_param_len_16=True) recv_param_len_16=True,
)
return bytes(resp[0]) return bytes(resp[0])
def socket_connect(self, socket_num, dest, port, conn_mode=TCP_MODE): def socket_connect(self, socket_num, dest, port, conn_mode=TCP_MODE):
@ -701,6 +750,12 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
print("*** Socket connect mode", conn_mode) print("*** Socket connect mode", conn_mode)
self.socket_open(socket_num, dest, port, conn_mode=conn_mode) self.socket_open(socket_num, dest, port, conn_mode=conn_mode)
if conn_mode == self.UDP_MODE:
# UDP doesn't actually establish a connection
# but the socket for writing is created via start_server
self.start_server(port, socket_num, conn_mode)
return True
times = time.monotonic() times = time.monotonic()
while (time.monotonic() - times) < 3: # wait 3 seconds while (time.monotonic() - times) < 3: # wait 3 seconds
if self.socket_connected(socket_num): if self.socket_connected(socket_num):
@ -717,12 +772,14 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
if resp[0][0] != 1: if resp[0][0] != 1:
raise RuntimeError("Failed to close socket") raise RuntimeError("Failed to close socket")
def start_server(self, port, socket_num, conn_mode=TCP_MODE, ip=None): # pylint: disable=invalid-name def start_server(
self, port, socket_num, conn_mode=TCP_MODE, ip=None
): # pylint: disable=invalid-name
"""Opens a server on the specified port, using the ESP32's internal reference number""" """Opens a server on the specified port, using the ESP32's internal reference number"""
if self._debug: if self._debug:
print("*** starting server") print("*** starting server")
self._socknum_ll[0][0] = socket_num self._socknum_ll[0][0] = socket_num
params = [struct.pack('>H', port), self._socknum_ll[0], (conn_mode,)] params = [struct.pack(">H", port), self._socknum_ll[0], (conn_mode,)]
if ip: if ip:
params.insert(0, ip) params.insert(0, ip)
resp = self._send_command_get_response(_START_SERVER_TCP_CMD, params) resp = self._send_command_get_response(_START_SERVER_TCP_CMD, params)
@ -756,8 +813,7 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
pin_mode = 0 pin_mode = 0
else: else:
pin_mode = mode pin_mode = mode
resp = self._send_command_get_response(_SET_PIN_MODE_CMD, resp = self._send_command_get_response(_SET_PIN_MODE_CMD, ((pin,), (pin_mode,)))
((pin,), (pin_mode,)))
if resp[0][0] != 1: if resp[0][0] != 1:
raise RuntimeError("Failed to set pin mode") raise RuntimeError("Failed to set pin mode")
@ -768,8 +824,9 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
:param int pin: ESP32 GPIO pin to write to. :param int pin: ESP32 GPIO pin to write to.
:param bool value: Value for the pin. :param bool value: Value for the pin.
""" """
resp = self._send_command_get_response(_SET_DIGITAL_WRITE_CMD, resp = self._send_command_get_response(
((pin,), (value,))) _SET_DIGITAL_WRITE_CMD, ((pin,), (value,))
)
if resp[0][0] != 1: if resp[0][0] != 1:
raise RuntimeError("Failed to write to pin") raise RuntimeError("Failed to write to pin")
@ -781,8 +838,9 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
:param float value: 0=off 1.0=full on :param float value: 0=off 1.0=full on
""" """
value = int(255 * analog_value) value = int(255 * analog_value)
resp = self._send_command_get_response(_SET_ANALOG_WRITE_CMD, resp = self._send_command_get_response(
((pin,), (value,))) _SET_ANALOG_WRITE_CMD, ((pin,), (value,))
)
if resp[0][0] != 1: if resp[0][0] != 1:
raise RuntimeError("Failed to write to pin") raise RuntimeError("Failed to write to pin")
@ -796,14 +854,14 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
fw_semver_maj = bytes(self.firmware_version).decode("utf-8")[2] fw_semver_maj = bytes(self.firmware_version).decode("utf-8")[2]
assert int(fw_semver_maj) >= 5, "Please update nina-fw to 1.5.0 or above." assert int(fw_semver_maj) >= 5, "Please update nina-fw to 1.5.0 or above."
resp = self._send_command_get_response(_SET_DIGITAL_READ_CMD, resp = self._send_command_get_response(_SET_DIGITAL_READ_CMD, ((pin,),))[0]
((pin,),))[0]
if resp[0] == 0: if resp[0] == 0:
return False return False
elif resp[0] == 1: if resp[0] == 1:
return True return True
else: raise ValueError(
raise ValueError("_SET_DIGITAL_READ response error: response is not boolean", resp[0]) "_SET_DIGITAL_READ response error: response is not boolean", resp[0]
)
def set_analog_read(self, pin, atten=ADC_ATTEN_DB_11): def set_analog_read(self, pin, atten=ADC_ATTEN_DB_11):
""" """
@ -816,11 +874,12 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
fw_semver_maj = bytes(self.firmware_version).decode("utf-8")[2] fw_semver_maj = bytes(self.firmware_version).decode("utf-8")[2]
assert int(fw_semver_maj) >= 5, "Please update nina-fw to 1.5.0 or above." assert int(fw_semver_maj) >= 5, "Please update nina-fw to 1.5.0 or above."
resp = self._send_command_get_response(_SET_ANALOG_READ_CMD, resp = self._send_command_get_response(_SET_ANALOG_READ_CMD, ((pin,), (atten,)))
((pin,), (atten,))) resp_analog = struct.unpack("<i", resp[0])
resp_analog = struct.unpack('<i', resp[0])
if resp_analog[0] < 0: if resp_analog[0] < 0:
raise ValueError("_SET_ANALOG_READ parameter error: invalid pin", resp_analog[0]) raise ValueError(
"_SET_ANALOG_READ parameter error: invalid pin", resp_analog[0]
)
if self._debug: if self._debug:
print(resp, resp_analog, resp_analog[0], 16 * resp_analog[0]) print(resp, resp_analog, resp_analog[0], 16 * resp_analog[0])
return 16 * resp_analog[0] return 16 * resp_analog[0]
@ -829,12 +888,14 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
"""The current unix timestamp""" """The current unix timestamp"""
if self.status == WL_CONNECTED: if self.status == WL_CONNECTED:
resp = self._send_command_get_response(_GET_TIME) resp = self._send_command_get_response(_GET_TIME)
resp_time = struct.unpack('<i', resp[0]) resp_time = struct.unpack("<i", resp[0])
if resp_time == (0,): if resp_time == (0,):
raise ValueError("_GET_TIME returned 0") raise ValueError("_GET_TIME returned 0")
return resp_time return resp_time
if self.status in (WL_AP_LISTENING, WL_AP_CONNECTED): if self.status in (WL_AP_LISTENING, WL_AP_CONNECTED):
raise RuntimeError("Cannot obtain NTP while in AP mode, must be connected to internet") raise RuntimeError(
"Cannot obtain NTP while in AP mode, must be connected to internet"
)
raise RuntimeError("Must be connected to WiFi before obtaining NTP.") raise RuntimeError("Must be connected to WiFi before obtaining NTP.")
def set_certificate(self, client_certificate): def set_certificate(self, client_certificate):
@ -845,9 +906,11 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
if self._debug: if self._debug:
print("** Setting client certificate") print("** Setting client certificate")
if self.status == WL_CONNECTED: if self.status == WL_CONNECTED:
raise RuntimeError("set_certificate must be called BEFORE a connection is established.") raise RuntimeError(
"set_certificate must be called BEFORE a connection is established."
)
if isinstance(client_certificate, str): if isinstance(client_certificate, str):
client_certificate = bytes(client_certificate, 'utf-8') client_certificate = bytes(client_certificate, "utf-8")
if "-----BEGIN CERTIFICATE" not in client_certificate: if "-----BEGIN CERTIFICATE" not in client_certificate:
raise TypeError(".PEM must start with -----BEGIN CERTIFICATE") raise TypeError(".PEM must start with -----BEGIN CERTIFICATE")
assert len(client_certificate) < 1300, ".PEM must be less than 1300 bytes." assert len(client_certificate) < 1300, ".PEM must be less than 1300 bytes."
@ -865,9 +928,11 @@ class ESP_SPIcontrol: # pylint: disable=too-many-public-methods, too-many-insta
if self._debug: if self._debug:
print("** Setting client's private key.") print("** Setting client's private key.")
if self.status == WL_CONNECTED: if self.status == WL_CONNECTED:
raise RuntimeError("set_private_key must be called BEFORE a connection is established.") raise RuntimeError(
"set_private_key must be called BEFORE a connection is established."
)
if isinstance(private_key, str): if isinstance(private_key, str):
private_key = bytes(private_key, 'utf-8') private_key = bytes(private_key, "utf-8")
if "-----BEGIN RSA" not in private_key: if "-----BEGIN RSA" not in private_key:
raise TypeError(".PEM must start with -----BEGIN RSA") raise TypeError(".PEM must start with -----BEGIN RSA")
assert len(private_key) < 1700, ".PEM must be less than 1700 bytes." assert len(private_key) < 1700, ".PEM must be less than 1700 bytes."

View file

@ -1,24 +1,6 @@
# The MIT License (MIT) # SPDX-FileCopyrightText: Copyright (c) 2019 ladyada for Adafruit Industries
# #
# Copyright (c) 2019 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT
#
# 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_esp32spi_socket` `adafruit_esp32spi_socket`
@ -37,11 +19,14 @@ from micropython import const
from adafruit_esp32spi import adafruit_esp32spi from adafruit_esp32spi import adafruit_esp32spi
_the_interface = None # pylint: disable=invalid-name _the_interface = None # pylint: disable=invalid-name
def set_interface(iface): def set_interface(iface):
"""Helper to set the global internet interface""" """Helper to set the global internet interface"""
global _the_interface # pylint: disable=global-statement, invalid-name global _the_interface # pylint: disable=global-statement, invalid-name
_the_interface = iface _the_interface = iface
SOCK_STREAM = const(1) SOCK_STREAM = const(1)
AF_INET = const(2) AF_INET = const(2)
NO_SOCKET_AVAIL = const(255) NO_SOCKET_AVAIL = const(255)
@ -55,22 +40,28 @@ def getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0):
if not isinstance(port, int): if not isinstance(port, int):
raise RuntimeError("Port must be an integer") raise RuntimeError("Port must be an integer")
ipaddr = _the_interface.get_host_by_name(host) ipaddr = _the_interface.get_host_by_name(host)
return [(AF_INET, socktype, proto, '', (ipaddr, port))] return [(AF_INET, socktype, proto, "", (ipaddr, port))]
# pylint: enable=too-many-arguments, unused-argument # pylint: enable=too-many-arguments, unused-argument
# pylint: disable=unused-argument, redefined-builtin, invalid-name # pylint: disable=unused-argument, redefined-builtin, invalid-name
class socket: class socket:
"""A simplified implementation of the Python 'socket' class, for connecting """A simplified implementation of the Python 'socket' class, for connecting
through an interface to a remote device""" through an interface to a remote device"""
# pylint: disable=too-many-arguments # pylint: disable=too-many-arguments
def __init__(self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None, socknum=None): def __init__(
self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None, socknum=None
):
if family != AF_INET: if family != AF_INET:
raise RuntimeError("Only AF_INET family supported") raise RuntimeError("Only AF_INET family supported")
if type != SOCK_STREAM: if type != SOCK_STREAM:
raise RuntimeError("Only SOCK_STREAM type supported") raise RuntimeError("Only SOCK_STREAM type supported")
self._buffer = b'' self._buffer = b""
self._socknum = socknum if socknum else _the_interface.get_socket() self._socknum = socknum if socknum else _the_interface.get_socket()
self.settimeout(0) self.settimeout(0)
# pylint: enable=too-many-arguments # pylint: enable=too-many-arguments
def connect(self, address, conntype=None): def connect(self, address, conntype=None):
@ -80,9 +71,11 @@ class socket:
host, port = address host, port = address
if conntype is None: if conntype is None:
conntype = _the_interface.TCP_MODE conntype = _the_interface.TCP_MODE
if not _the_interface.socket_connect(self._socknum, host, port, conn_mode=conntype): if not _the_interface.socket_connect(
self._socknum, host, port, conn_mode=conntype
):
raise RuntimeError("Failed to connect to host", host) raise RuntimeError("Failed to connect to host", host)
self._buffer = b'' self._buffer = b""
def send(self, data): # pylint: disable=no-self-use def send(self, data): # pylint: disable=no-self-use
"""Send some data to the socket""" """Send some data to the socket"""
@ -97,9 +90,9 @@ class socket:
def readline(self): def readline(self):
"""Attempt to return as many bytes as we can up to but not including '\r\n'""" """Attempt to return as many bytes as we can up to but not including '\r\n'"""
#print("Socket readline") # print("Socket readline")
stamp = time.monotonic() stamp = time.monotonic()
while b'\r\n' not in self._buffer: while b"\r\n" not in self._buffer:
# there's no line already in there, read some more # there's no line already in there, read some more
avail = self.available() avail = self.available()
if avail: if avail:
@ -107,7 +100,7 @@ class socket:
elif self._timeout > 0 and time.monotonic() - stamp > self._timeout: elif self._timeout > 0 and time.monotonic() - stamp > self._timeout:
self.close() # Make sure to close socket so that we don't exhaust sockets. self.close() # Make sure to close socket so that we don't exhaust sockets.
raise RuntimeError("Didn't receive full response, failing out") raise RuntimeError("Didn't receive full response, failing out")
firstline, self._buffer = self._buffer.split(b'\r\n', 1) firstline, self._buffer = self._buffer.split(b"\r\n", 1)
gc.collect() gc.collect()
return firstline return firstline
@ -115,7 +108,7 @@ class socket:
"""Reads some bytes from the connected remote address. """Reads some bytes from the connected remote address.
:param int bufsize: maximum number of bytes to receive :param int bufsize: maximum number of bytes to receive
""" """
#print("Socket read", bufsize) # print("Socket read", bufsize)
if bufsize == 0: # read as much as we can at the moment if bufsize == 0: # read as much as we can at the moment
while True: while True:
avail = self.available() avail = self.available()
@ -125,7 +118,7 @@ class socket:
break break
gc.collect() gc.collect()
ret = self._buffer ret = self._buffer
self._buffer = b'' self._buffer = b""
gc.collect() gc.collect()
return ret return ret
stamp = time.monotonic() stamp = time.monotonic()
@ -133,7 +126,7 @@ class socket:
to_read = bufsize - len(self._buffer) to_read = bufsize - len(self._buffer)
received = [] received = []
while to_read > 0: while to_read > 0:
#print("Bytes to read:", to_read) # print("Bytes to read:", to_read)
avail = self.available() avail = self.available()
if avail: if avail:
stamp = time.monotonic() stamp = time.monotonic()
@ -143,13 +136,13 @@ class socket:
gc.collect() gc.collect()
if self._timeout > 0 and time.monotonic() - stamp > self._timeout: if self._timeout > 0 and time.monotonic() - stamp > self._timeout:
break break
#print(received) # print(received)
self._buffer += b''.join(received) self._buffer += b"".join(received)
ret = None ret = None
if len(self._buffer) == bufsize: if len(self._buffer) == bufsize:
ret = self._buffer ret = self._buffer
self._buffer = b'' self._buffer = b""
else: else:
ret = self._buffer[:bufsize] ret = self._buffer[:bufsize]
self._buffer = self._buffer[bufsize:] self._buffer = self._buffer[bufsize:]
@ -177,18 +170,19 @@ class socket:
"""Whether or not we are connected to the socket""" """Whether or not we are connected to the socket"""
if self.socknum == NO_SOCKET_AVAIL: if self.socknum == NO_SOCKET_AVAIL:
return False return False
elif self.available(): if self.available():
return True return True
else:
status = _the_interface.socket_status(self.socknum) status = _the_interface.socket_status(self.socknum)
result = status not in (adafruit_esp32spi.SOCKET_LISTEN, result = status not in (
adafruit_esp32spi.SOCKET_LISTEN,
adafruit_esp32spi.SOCKET_CLOSED, adafruit_esp32spi.SOCKET_CLOSED,
adafruit_esp32spi.SOCKET_FIN_WAIT_1, adafruit_esp32spi.SOCKET_FIN_WAIT_1,
adafruit_esp32spi.SOCKET_FIN_WAIT_2, adafruit_esp32spi.SOCKET_FIN_WAIT_2,
adafruit_esp32spi.SOCKET_TIME_WAIT, adafruit_esp32spi.SOCKET_TIME_WAIT,
adafruit_esp32spi.SOCKET_SYN_SENT, adafruit_esp32spi.SOCKET_SYN_SENT,
adafruit_esp32spi.SOCKET_SYN_RCVD, adafruit_esp32spi.SOCKET_SYN_RCVD,
adafruit_esp32spi.SOCKET_CLOSE_WAIT) adafruit_esp32spi.SOCKET_CLOSE_WAIT,
)
if not result: if not result:
self.close() self.close()
self._socknum = NO_SOCKET_AVAIL self._socknum = NO_SOCKET_AVAIL
@ -202,4 +196,6 @@ class socket:
def close(self): def close(self):
"""Close the socket, after reading whatever remains""" """Close the socket, after reading whatever remains"""
_the_interface.socket_close(self._socknum) _the_interface.socket_close(self._socknum)
# pylint: enable=unused-argument, redefined-builtin, invalid-name # pylint: enable=unused-argument, redefined-builtin, invalid-name

View file

@ -1,24 +1,6 @@
# The MIT License (MIT) # SPDX-FileCopyrightText: Copyright (c) 2019 Melissa LeBlanc-Williams for Adafruit Industries
# #
# Copyright (c) 2019 Melissa LeBlanc-Williams for Adafruit Industries # SPDX-License-Identifier: MIT
#
# 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_esp32spi_wifimanager` `adafruit_esp32spi_wifimanager`
@ -42,12 +24,20 @@ class ESPSPI_WiFiManager:
""" """
A class to help manage the Wifi connection A class to help manage the Wifi connection
""" """
NORMAL = const(1) NORMAL = const(1)
ENTERPRISE = const(2) ENTERPRISE = const(2)
# pylint: disable=too-many-arguments # pylint: disable=too-many-arguments
def __init__(self, esp, secrets, status_pixel=None, attempts=2, def __init__(
connection_type=NORMAL, debug=False): self,
esp,
secrets,
status_pixel=None,
attempts=2,
connection_type=NORMAL,
debug=False,
):
""" """
:param ESP_SPIcontrol esp: The ESP object we are using :param ESP_SPIcontrol esp: The ESP object we are using
:param dict secrets: The WiFi and Adafruit IO secrets dict (See examples) :param dict secrets: The WiFi and Adafruit IO secrets dict (See examples)
@ -60,8 +50,8 @@ class ESPSPI_WiFiManager:
# Read the settings # Read the settings
self.esp = esp self.esp = esp
self.debug = debug self.debug = debug
self.ssid = secrets['ssid'] self.ssid = secrets["ssid"]
self.password = secrets.get('password', None) self.password = secrets.get("password", None)
self.attempts = attempts self.attempts = attempts
self._connection_type = connection_type self._connection_type = connection_type
requests.set_socket(socket, esp) requests.set_socket(socket, esp)
@ -69,18 +59,19 @@ class ESPSPI_WiFiManager:
self.pixel_status(0) self.pixel_status(0)
# Check for WPA2 Enterprise keys in the secrets dictionary and load them if they exist # Check for WPA2 Enterprise keys in the secrets dictionary and load them if they exist
if secrets.get('ent_ssid'): if secrets.get("ent_ssid"):
self.ent_ssid = secrets['ent_ssid'] self.ent_ssid = secrets["ent_ssid"]
else: else:
self.ent_ssid = secrets['ssid'] self.ent_ssid = secrets["ssid"]
if secrets.get('ent_ident'): if secrets.get("ent_ident"):
self.ent_ident = secrets['ent_ident'] self.ent_ident = secrets["ent_ident"]
else: else:
self.ent_ident = '' self.ent_ident = ""
if secrets.get('ent_user'): if secrets.get("ent_user"):
self.ent_user = secrets['ent_user'] self.ent_user = secrets["ent_user"]
if secrets.get('ent_password'): if secrets.get("ent_password"):
self.ent_password = secrets['ent_password'] self.ent_password = secrets["ent_password"]
# pylint: enable=too-many-arguments # pylint: enable=too-many-arguments
def reset(self): def reset(self):
@ -101,7 +92,10 @@ class ESPSPI_WiFiManager:
print("Firmware vers.", self.esp.firmware_version) print("Firmware vers.", self.esp.firmware_version)
print("MAC addr:", [hex(i) for i in self.esp.MAC_address]) print("MAC addr:", [hex(i) for i in self.esp.MAC_address])
for access_pt in self.esp.scan_networks(): for access_pt in self.esp.scan_networks():
print("\t%s\t\tRSSI: %d" % (str(access_pt['ssid'], 'utf-8'), access_pt['rssi'])) print(
"\t%s\t\tRSSI: %d"
% (str(access_pt["ssid"], "utf-8"), access_pt["rssi"])
)
if self._connection_type == ESPSPI_WiFiManager.NORMAL: if self._connection_type == ESPSPI_WiFiManager.NORMAL:
self.connect_normal() self.connect_normal()
elif self._connection_type == ESPSPI_WiFiManager.ENTERPRISE: elif self._connection_type == ESPSPI_WiFiManager.ENTERPRISE:
@ -119,7 +113,9 @@ class ESPSPI_WiFiManager:
if self.debug: if self.debug:
print("Connecting to AP...") print("Connecting to AP...")
self.pixel_status((100, 0, 0)) 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 failure_count = 0
self.pixel_status((0, 100, 0)) self.pixel_status((0, 100, 0))
except (ValueError, RuntimeError) as error: except (ValueError, RuntimeError) as error:
@ -143,9 +139,11 @@ class ESPSPI_WiFiManager:
print("Waiting for AP to be initialized...") print("Waiting for AP to be initialized...")
self.pixel_status((100, 0, 0)) self.pixel_status((100, 0, 0))
if self.password: if self.password:
self.esp.create_AP(bytes(self.ssid, 'utf-8'), bytes(self.password, 'utf-8')) self.esp.create_AP(
bytes(self.ssid, "utf-8"), bytes(self.password, "utf-8")
)
else: else:
self.esp.create_AP(bytes(self.ssid, 'utf-8'), None) self.esp.create_AP(bytes(self.ssid, "utf-8"), None)
failure_count = 0 failure_count = 0
self.pixel_status((0, 100, 0)) self.pixel_status((0, 100, 0))
except (ValueError, RuntimeError) as error: except (ValueError, RuntimeError) as error:
@ -162,15 +160,17 @@ class ESPSPI_WiFiManager:
Attempt an enterprise style WiFi connection Attempt an enterprise style WiFi connection
""" """
failure_count = 0 failure_count = 0
self.esp.wifi_set_network(bytes(self.ent_ssid, 'utf-8')) 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_entidentity(bytes(self.ent_ident, "utf-8"))
self.esp.wifi_set_entusername(bytes(self.ent_user, '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_entpassword(bytes(self.ent_password, "utf-8"))
self.esp.wifi_set_entenable() self.esp.wifi_set_entenable()
while not self.esp.is_connected: while not self.esp.is_connected:
try: try:
if self.debug: if self.debug:
print("Waiting for the ESP32 to connect to the WPA2 Enterprise AP...") print(
"Waiting for the ESP32 to connect to the WPA2 Enterprise AP..."
)
self.pixel_status((100, 0, 0)) self.pixel_status((100, 0, 0))
sleep(1) sleep(1)
failure_count = 0 failure_count = 0
@ -312,7 +312,7 @@ class ESPSPI_WiFiManager:
:type value: int or 3-value tuple :type value: int or 3-value tuple
""" """
if self.statuspix: if self.statuspix:
if hasattr(self.statuspix, 'color'): if hasattr(self.statuspix, "color"):
self.statuspix.color = value self.statuspix.color = value
else: else:
self.statuspix.fill(value) self.statuspix.fill(value)

View file

@ -1,24 +1,6 @@
# The MIT License (MIT) # SPDX-FileCopyrightText: Copyright (c) 2019 Matt Costi for Adafruit Industries
# #
# Copyright (c) 2019 Matt Costi for Adafruit Industries # SPDX-License-Identifier: MIT
#
# 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_esp32spi_wsgiserver` `adafruit_esp32spi_wsgiserver`
@ -53,12 +35,15 @@ import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from adafruit_requests import parse_headers from adafruit_requests import parse_headers
_the_interface = None # pylint: disable=invalid-name _the_interface = None # pylint: disable=invalid-name
def set_interface(iface): def set_interface(iface):
"""Helper to set the global internet interface""" """Helper to set the global internet interface"""
global _the_interface # pylint: disable=global-statement, invalid-name global _the_interface # pylint: disable=global-statement, invalid-name
_the_interface = iface _the_interface = iface
socket.set_interface(iface) socket.set_interface(iface)
NO_SOCK_AVAIL = const(255) NO_SOCK_AVAIL = const(255)
# pylint: disable=invalid-name # pylint: disable=invalid-name
@ -88,7 +73,10 @@ class WSGIServer:
if self._debug: if self._debug:
ip = _the_interface.pretty_ip(_the_interface.ip_address) ip = _the_interface.pretty_ip(_the_interface.ip_address)
print("Server available at {0}:{1}".format(ip, self.port)) print("Server available at {0}:{1}".format(ip, self.port))
print("Sever status: ", _the_interface.get_server_state(self._server_sock.socknum)) print(
"Sever status: ",
_the_interface.get_server_state(self._server_sock.socknum),
)
def update_poll(self): def update_poll(self):
""" """
@ -97,7 +85,7 @@ class WSGIServer:
the application callable will be invoked. the application callable will be invoked.
""" """
self.client_available() self.client_available()
if (self._client_sock and self._client_sock.available()): if self._client_sock and self._client_sock.available():
environ = self._get_environ(self._client_sock) environ = self._get_environ(self._client_sock)
result = self.application(environ, self._start_response) result = self.application(environ, self._start_response)
self.finish_response(result) self.finish_response(result)
@ -145,7 +133,9 @@ class WSGIServer:
# check for new client sock # check for new client sock
if self._debug > 2: if self._debug > 2:
print("checking for new client sock") print("checking for new client sock")
client_sock_num = _the_interface.socket_available(self._server_sock.socknum) client_sock_num = _the_interface.socket_available(
self._server_sock.socknum
)
sock = socket.socket(socknum=client_sock_num) sock = socket.socket(socknum=client_sock_num)
else: else:
print("Server has not been started, cannot check for clients!") print("Server has not been started, cannot check for clients!")
@ -210,7 +200,7 @@ class WSGIServer:
body = client.read() body = client.read()
env["wsgi.input"] = io.StringIO(body) env["wsgi.input"] = io.StringIO(body)
for name, value in headers.items(): for name, value in headers.items():
key = "HTTP_" + name.replace('-', '_').upper() key = "HTTP_" + name.replace("-", "_").upper()
if key in env: if key in env:
value = "{0},{1}".format(env[key], value) value = "{0},{1}".format(env[key], value)
env[key] = value env[key] = value

View file

@ -1,24 +1,7 @@
# The MIT License (MIT) # SPDX-FileCopyrightText: Copyright (c) 2019 Brent Rubell for Adafruit Industries
# #
# Copyright (c) 2019 Brent Rubell for Adafruit Industries # SPDX-License-Identifier: MIT
#
# 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.
""" """
`digitalio` `digitalio`
============================== ==============================
@ -31,6 +14,7 @@ https://github.com/adafruit/Adafruit_Blinka/blob/master/src/digitalio.py
""" """
from micropython import const from micropython import const
class Pin: class Pin:
""" """
Implementation of CircuitPython API Pin Handling Implementation of CircuitPython API Pin Handling
@ -42,7 +26,8 @@ class Pin:
NOTE: This class does not currently implement reading digital pins NOTE: This class does not currently implement reading digital pins
or the use of internal pull-up resistors. or the use of internal pull-up resistors.
""" """
#pylint: disable=invalid-name
# pylint: disable=invalid-name
IN = const(0x00) IN = const(0x00)
OUT = const(0x01) OUT = const(0x01)
LOW = const(0x00) LOW = const(0x00)
@ -51,17 +36,15 @@ class Pin:
_mode = IN _mode = IN
pin_id = None pin_id = None
ESP32_GPIO_PINS = set([0, 1, 2, 4, 5, ESP32_GPIO_PINS = set(
12, 13, 14, 15, [0, 1, 2, 4, 5, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 25, 26, 27, 32, 33]
16, 17, 18, 19, )
21, 22, 23, 25,
26, 27, 32, 33])
def __init__(self, esp_pin, esp): def __init__(self, esp_pin, esp):
if esp_pin in self.ESP32_GPIO_PINS: if esp_pin in self.ESP32_GPIO_PINS:
self.pin_id = esp_pin self.pin_id = esp_pin
else: else:
raise AttributeError("Pin %d is not a valid ESP32 GPIO Pin."%esp_pin) raise AttributeError("Pin %d is not a valid ESP32 GPIO Pin." % esp_pin)
self._esp = esp self._esp = esp
def init(self, mode=IN): def init(self, mode=IN):
@ -92,36 +75,46 @@ class Pin:
else: else:
raise RuntimeError("Invalid value for pin") raise RuntimeError("Invalid value for pin")
else: else:
raise NotImplementedError("digitalRead not currently implemented in esp32spi") raise NotImplementedError(
"digitalRead not currently implemented in esp32spi"
)
def __repr__(self): def __repr__(self):
return str(self.pin_id) return str(self.pin_id)
# pylint: disable = too-few-public-methods # pylint: disable = too-few-public-methods
class DriveMode(): class DriveMode:
"""DriveMode Enum.""" """DriveMode Enum."""
PUSH_PULL = None PUSH_PULL = None
OPEN_DRAIN = None OPEN_DRAIN = None
DriveMode.PUSH_PULL = DriveMode() DriveMode.PUSH_PULL = DriveMode()
DriveMode.OPEN_DRAIN = DriveMode() DriveMode.OPEN_DRAIN = DriveMode()
class Direction(): class Direction:
"""DriveMode Enum.""" """DriveMode Enum."""
INPUT = None INPUT = None
OUTPUT = None OUTPUT = None
Direction.INPUT = Direction() Direction.INPUT = Direction()
Direction.OUTPUT = Direction() Direction.OUTPUT = Direction()
class DigitalInOut(): class DigitalInOut:
"""Implementation of DigitalIO module for ESP32SPI. """Implementation of DigitalIO module for ESP32SPI.
:param ESP_SPIcontrol esp: The ESP object we are using. :param ESP_SPIcontrol esp: The ESP object we are using.
:param int pin: Valid ESP32 GPIO Pin, predefined in ESP32_GPIO_PINS. :param int pin: Valid ESP32 GPIO Pin, predefined in ESP32_GPIO_PINS.
""" """
_pin = None _pin = None
#pylint: disable = attribute-defined-outside-init # pylint: disable = attribute-defined-outside-init
def __init__(self, esp, pin): def __init__(self, esp, pin):
self._esp = esp self._esp = esp
self._pin = Pin(pin, self._esp) self._pin = Pin(pin, self._esp)
@ -150,7 +143,9 @@ class DigitalInOut():
"""Sets the pull and then switch to read in digital values. """Sets the pull and then switch to read in digital values.
:param Pull pull: Pull configuration for the input. :param Pull pull: Pull configuration for the input.
""" """
raise NotImplementedError("Digital reads are not currently supported in ESP32SPI.") raise NotImplementedError(
"Digital reads are not currently supported in ESP32SPI."
)
@property @property
def direction(self): def direction(self):
@ -175,7 +170,7 @@ class DigitalInOut():
@property @property
def value(self): def value(self):
"""Returns the digital logic level value of the pin.""" """Returns the digital logic level value of the pin."""
return self._pin.value() is 1 return self._pin.value() == 1
@value.setter @value.setter
def value(self, val): def value(self, val):
@ -204,6 +199,8 @@ class DigitalInOut():
""" """
self.__drive_mode = mode self.__drive_mode = mode
if mode is DriveMode.OPEN_DRAIN: if mode is DriveMode.OPEN_DRAIN:
raise NotImplementedError('Drive mode %s not implemented in ESP32SPI.'%mode) raise NotImplementedError(
elif mode is DriveMode.PUSH_PULL: "Drive mode %s not implemented in ESP32SPI." % mode
)
if mode is DriveMode.PUSH_PULL:
self._pin.init(mode=Pin.OUT) self._pin.init(mode=Pin.OUT)

3
docs/_static/favicon.ico.license vendored Normal file
View file

@ -0,0 +1,3 @@
SPDX-FileCopyrightText: 2018 Phillip Torrone for Adafruit Industries
SPDX-License-Identifier: CC-BY-4.0

3
docs/api.rst.license Normal file
View file

@ -0,0 +1,3 @@
SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
SPDX-License-Identifier: MIT

View file

@ -1,8 +1,13 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
#
# SPDX-License-Identifier: MIT
import os import os
import sys import sys
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath(".."))
# -- General configuration ------------------------------------------------ # -- General configuration ------------------------------------------------
@ -10,10 +15,10 @@ sys.path.insert(0, os.path.abspath('..'))
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones. # ones.
extensions = [ extensions = [
'sphinx.ext.autodoc', "sphinx.ext.autodoc",
'sphinx.ext.intersphinx', "sphinx.ext.intersphinx",
'sphinx.ext.napoleon', "sphinx.ext.napoleon",
'sphinx.ext.todo', "sphinx.ext.todo",
] ]
# TODO: Please Read! # TODO: Please Read!
@ -23,29 +28,36 @@ extensions = [
# autodoc_mock_imports = ["digitalio", "busio"] # autodoc_mock_imports = ["digitalio", "busio"]
intersphinx_mapping = {'python': ('https://docs.python.org/3.4', None),'BusDevice': ('https://circuitpython.readthedocs.io/projects/busdevice/en/latest/', None),'CircuitPython': ('https://circuitpython.readthedocs.io/en/latest/', None)} intersphinx_mapping = {
"python": ("https://docs.python.org/3.4", None),
"BusDevice": (
"https://circuitpython.readthedocs.io/projects/busdevice/en/latest/",
None,
),
"CircuitPython": ("https://circuitpython.readthedocs.io/en/latest/", None),
}
# Add any paths that contain templates here, relative to this directory. # Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates'] templates_path = ["_templates"]
source_suffix = '.rst' source_suffix = ".rst"
# The master toctree document. # The master toctree document.
master_doc = 'index' master_doc = "index"
# General information about the project. # General information about the project.
project = u'Adafruit ESP32SPI Library' project = "Adafruit ESP32SPI Library"
copyright = u'2019 ladyada' copyright = "2019 ladyada"
author = u'ladyada' author = "ladyada"
# The version info for the project you're documenting, acts as replacement for # The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the # |version| and |release|, also used in various other places throughout the
# built documents. # built documents.
# #
# The short X.Y version. # The short X.Y version.
version = u'1.0' version = "1.0"
# The full version, including alpha/beta/rc tags. # The full version, including alpha/beta/rc tags.
release = u'1.0' release = "1.0"
# The language for content autogenerated by Sphinx. Refer to documentation # The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages. # for a list of supported languages.
@ -57,7 +69,7 @@ language = None
# List of patterns, relative to source directory, that match files and # List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files. # directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path # This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store', '.env', 'CODE_OF_CONDUCT.md'] exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", ".env", "CODE_OF_CONDUCT.md"]
# The reST default role (used for this markup: `text`) to use for all # The reST default role (used for this markup: `text`) to use for all
# documents. # documents.
@ -69,7 +81,7 @@ default_role = "any"
add_function_parentheses = True add_function_parentheses = True
# The name of the Pygments (syntax highlighting) style to use. # The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx' pygments_style = "sphinx"
# If true, `todo` and `todoList` produce output, else they produce nothing. # If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False todo_include_todos = False
@ -84,32 +96,33 @@ napoleon_numpy_docstring = False
# The theme to use for HTML and HTML Help pages. See the documentation for # The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes. # a list of builtin themes.
# #
on_rtd = os.environ.get('READTHEDOCS', None) == 'True' on_rtd = os.environ.get("READTHEDOCS", None) == "True"
if not on_rtd: # only import and set the theme if we're building docs locally if not on_rtd: # only import and set the theme if we're building docs locally
try: try:
import sphinx_rtd_theme import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), '.'] html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."]
except: except:
html_theme = 'default' html_theme = "default"
html_theme_path = ['.'] html_theme_path = ["."]
else: else:
html_theme_path = ['.'] html_theme_path = ["."]
# Add any paths that contain custom static files (such as style sheets) here, # Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files, # relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css". # so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static'] html_static_path = ["_static"]
# The name of an image file (relative to this directory) to use as a favicon of # The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large. # pixels large.
# #
html_favicon = '_static/favicon.ico' html_favicon = "_static/favicon.ico"
# Output file base name for HTML help builder. # Output file base name for HTML help builder.
htmlhelp_basename = 'AdafruitEsp32spiLibrarydoc' htmlhelp_basename = "AdafruitEsp32spiLibrarydoc"
# -- Options for LaTeX output --------------------------------------------- # -- Options for LaTeX output ---------------------------------------------
@ -117,15 +130,12 @@ latex_elements = {
# The paper size ('letterpaper' or 'a4paper'). # The paper size ('letterpaper' or 'a4paper').
# #
# 'papersize': 'letterpaper', # 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt'). # The font size ('10pt', '11pt' or '12pt').
# #
# 'pointsize': '10pt', # 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble. # Additional stuff for the LaTeX preamble.
# #
# 'preamble': '', # 'preamble': '',
# Latex figure (float) alignment # Latex figure (float) alignment
# #
# 'figure_align': 'htbp', # 'figure_align': 'htbp',
@ -135,8 +145,13 @@ latex_elements = {
# (source start file, target name, title, # (source start file, target name, title,
# author, documentclass [howto, manual, or own class]). # author, documentclass [howto, manual, or own class]).
latex_documents = [ latex_documents = [
(master_doc, 'AdafruitESP32SPILibrary.tex', u'AdafruitESP32SPI Library Documentation', (
author, 'manual'), master_doc,
"AdafruitESP32SPILibrary.tex",
"AdafruitESP32SPI Library Documentation",
author,
"manual",
),
] ]
# -- Options for manual page output --------------------------------------- # -- Options for manual page output ---------------------------------------
@ -144,8 +159,13 @@ latex_documents = [
# One entry per manual page. List of tuples # One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section). # (source start file, name, description, authors, manual section).
man_pages = [ man_pages = [
(master_doc, 'AdafruitESP32SPIlibrary', u'Adafruit ESP32SPI Library Documentation', (
[author], 1) master_doc,
"AdafruitESP32SPIlibrary",
"Adafruit ESP32SPI Library Documentation",
[author],
1,
)
] ]
# -- Options for Texinfo output ------------------------------------------- # -- Options for Texinfo output -------------------------------------------
@ -154,7 +174,13 @@ man_pages = [
# (source start file, target name, title, author, # (source start file, target name, title, author,
# dir menu entry, description, category) # dir menu entry, description, category)
texinfo_documents = [ texinfo_documents = [
(master_doc, 'AdafruitESP32SPILibrary', u'Adafruit ESP32SPI Library Documentation', (
author, 'AdafruitESP32SPILibrary', 'One line description of project.', master_doc,
'Miscellaneous'), "AdafruitESP32SPILibrary",
"Adafruit ESP32SPI Library Documentation",
author,
"AdafruitESP32SPILibrary",
"One line description of project.",
"Miscellaneous",
),
] ]

View file

@ -0,0 +1,3 @@
SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
SPDX-License-Identifier: MIT

3
docs/index.rst.license Normal file
View file

@ -0,0 +1,3 @@
SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
SPDX-License-Identifier: MIT

View file

@ -1,3 +1,6 @@
# SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
import time import time
import board import board
import busio import busio
@ -28,7 +31,9 @@ esp32_reset = DigitalInOut(board.ESP_RESET)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO) spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
"""Use below for Most Boards""" """Use below for Most Boards"""
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards status_light = neopixel.NeoPixel(
board.NEOPIXEL, 1, brightness=0.2
) # Uncomment for Most Boards
"""Uncomment below for ItsyBitsy M4""" """Uncomment below for ItsyBitsy M4"""
# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
# Uncomment below for an externally defined RGB LED # Uncomment below for an externally defined RGB LED
@ -44,14 +49,19 @@ counter = 0
while True: while True:
try: try:
print("Posting data...", end='') print("Posting data...", end="")
data = counter data = counter
feed = 'test' feed = "test"
payload = {'value':data} payload = {"value": data}
response = wifi.post( response = wifi.post(
"https://io.adafruit.com/api/v2/"+secrets['aio_username']+"/feeds/"+feed+"/data", "https://io.adafruit.com/api/v2/"
+ secrets["aio_username"]
+ "/feeds/"
+ feed
+ "/data",
json=payload, json=payload,
headers={"X-AIO-KEY":secrets['aio_key']}) headers={"X-AIO-KEY": secrets["aio_key"]},
)
print(response.json()) print(response.json())
response.close() response.close()
counter = counter + 1 counter = counter + 1

View file

@ -1,3 +1,6 @@
# SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
import time import time
import board import board
import busio import busio
@ -27,9 +30,11 @@ esp32_reset = DigitalInOut(board.D5)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO) spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
"""Use below for Most Boards""" """Use below for Most Boards"""
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards status_light = neopixel.NeoPixel(
board.NEOPIXEL, 1, brightness=0.2
) # Uncomment for Most Boards
"""Uncomment below for ItsyBitsy M4""" """Uncomment below for ItsyBitsy M4"""
#status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light) wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
# neopixels # neopixels
@ -60,7 +65,7 @@ while True:
color = int(value[1:], 16) color = int(value[1:], 16)
red = color >> 16 & 0xFF red = color >> 16 & 0xFF
green = color >> 8 & 0xFF green = color >> 8 & 0xFF
blue = color& 0xFF blue = color & 0xFF
gamma_corrected = fancy.gamma_adjust(fancy.CRGB(red, green, blue)).pack() gamma_corrected = fancy.gamma_adjust(fancy.CRGB(red, green, blue)).pack()
pixels.fill(gamma_corrected) pixels.fill(gamma_corrected)

View file

@ -1,3 +1,6 @@
# SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
import time import time
import board import board
import busio import busio
@ -24,9 +27,11 @@ esp32_reset = DigitalInOut(board.ESP_RESET)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO) spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
"""Use below for Most Boards""" """Use below for Most Boards"""
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards status_light = neopixel.NeoPixel(
board.NEOPIXEL, 1, brightness=0.2
) # Uncomment for Most Boards
"""Uncomment below for ItsyBitsy M4""" """Uncomment below for ItsyBitsy M4"""
#status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light) wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
the_rtc = rtc.RTC() the_rtc = rtc.RTC()
@ -42,18 +47,20 @@ while True:
continue continue
json = response.json() json = response.json()
current_time = json['datetime'] current_time = json["datetime"]
the_date, the_time = current_time.split('T') the_date, the_time = current_time.split("T")
year, month, mday = [int(x) for x in the_date.split('-')] year, month, mday = [int(x) for x in the_date.split("-")]
the_time = the_time.split('.')[0] the_time = the_time.split(".")[0]
hours, minutes, seconds = [int(x) for x in the_time.split(':')] hours, minutes, seconds = [int(x) for x in the_time.split(":")]
# We can also fill in these extra nice things # We can also fill in these extra nice things
year_day = json['day_of_year'] year_day = json["day_of_year"]
week_day = json['day_of_week'] week_day = json["day_of_week"]
is_dst = json['dst'] is_dst = json["dst"]
now = time.struct_time((year, month, mday, hours, minutes, seconds, week_day, year_day, is_dst)) now = time.struct_time(
(year, month, mday, hours, minutes, seconds, week_day, year_day, is_dst)
)
print(now) print(now)
the_rtc.datetime = now the_rtc.datetime = now

View file

@ -1,10 +1,13 @@
# SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
# This file is where you keep secret settings, passwords, and tokens! # This file is where you keep secret settings, passwords, and tokens!
# If you put them in the code you risk committing that info or sharing it # If you put them in the code you risk committing that info or sharing it
secrets = { secrets = {
'ssid' : 'yourssid', "ssid": "yourssid",
'password' : 'yourpassword', "password": "yourpassword",
'timezone' : "America/New_York", # Check http://worldtimeapi.org/timezones "timezone": "America/New_York", # Check http://worldtimeapi.org/timezones
'aio_username' : 'youraiousername', "aio_username": "youraiousername",
'aio_key' : 'youraiokey', "aio_key": "youraiokey",
} }

View file

@ -1,3 +1,6 @@
# SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
import board import board
import busio import busio
from digitalio import DigitalInOut from digitalio import DigitalInOut
@ -5,6 +8,13 @@ import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from adafruit_esp32spi import adafruit_esp32spi from adafruit_esp32spi import adafruit_esp32spi
import adafruit_requests as requests import adafruit_requests as requests
# Get wifi details and more from a secrets.py file
try:
from secrets import secrets
except ImportError:
print("WiFi secrets are kept in secrets.py, please add them there!")
raise
print("ESP32 SPI webclient test") print("ESP32 SPI webclient test")
TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html" TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html"
@ -16,12 +26,18 @@ esp32_cs = DigitalInOut(board.ESP_CS)
esp32_ready = DigitalInOut(board.ESP_BUSY) esp32_ready = DigitalInOut(board.ESP_BUSY)
esp32_reset = DigitalInOut(board.ESP_RESET) esp32_reset = DigitalInOut(board.ESP_RESET)
# If you have an ItsyBitsy Airlift: # If you have an AirLift Shield:
# esp32_cs = DigitalInOut(board.D10)
# esp32_ready = DigitalInOut(board.D7)
# esp32_reset = DigitalInOut(board.D5)
# If you have an AirLift Featherwing or ItsyBitsy Airlift:
# esp32_cs = DigitalInOut(board.D13) # esp32_cs = DigitalInOut(board.D13)
# esp32_ready = DigitalInOut(board.D11) # esp32_ready = DigitalInOut(board.D11)
# esp32_reset = DigitalInOut(board.D12) # esp32_reset = DigitalInOut(board.D12)
# If you have an externally connected ESP32: # If you have an externally connected ESP32:
# NOTE: You may need to change the pins to reflect your wiring
# esp32_cs = DigitalInOut(board.D9) # esp32_cs = DigitalInOut(board.D9)
# esp32_ready = DigitalInOut(board.D10) # esp32_ready = DigitalInOut(board.D10)
# esp32_reset = DigitalInOut(board.D5) # esp32_reset = DigitalInOut(board.D5)
@ -37,34 +53,36 @@ print("Firmware vers.", esp.firmware_version)
print("MAC addr:", [hex(i) for i in esp.MAC_address]) print("MAC addr:", [hex(i) for i in esp.MAC_address])
for ap in esp.scan_networks(): for ap in esp.scan_networks():
print("\t%s\t\tRSSI: %d" % (str(ap['ssid'], 'utf-8'), ap['rssi'])) print("\t%s\t\tRSSI: %d" % (str(ap["ssid"], "utf-8"), ap["rssi"]))
print("Connecting to AP...") print("Connecting to AP...")
while not esp.is_connected: while not esp.is_connected:
try: try:
esp.connect_AP(b'MY_SSID_NAME', b'MY_SSID_PASSWORD') esp.connect_AP(secrets["ssid"], secrets["password"])
except RuntimeError as e: except RuntimeError as e:
print("could not connect to AP, retrying: ",e) print("could not connect to AP, retrying: ", e)
continue continue
print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi) print("Connected to", str(esp.ssid, "utf-8"), "\tRSSI:", esp.rssi)
print("My IP address is", esp.pretty_ip(esp.ip_address)) print("My IP address is", esp.pretty_ip(esp.ip_address))
print("IP lookup adafruit.com: %s" % esp.pretty_ip(esp.get_host_by_name("adafruit.com"))) print(
"IP lookup adafruit.com: %s" % esp.pretty_ip(esp.get_host_by_name("adafruit.com"))
)
print("Ping google.com: %d ms" % esp.ping("google.com")) print("Ping google.com: %d ms" % esp.ping("google.com"))
#esp._debug = True # esp._debug = True
print("Fetching text from", TEXT_URL) print("Fetching text from", TEXT_URL)
r = requests.get(TEXT_URL) r = requests.get(TEXT_URL)
print('-'*40) print("-" * 40)
print(r.text) print(r.text)
print('-'*40) print("-" * 40)
r.close() r.close()
print() print()
print("Fetching json from", JSON_URL) print("Fetching json from", JSON_URL)
r = requests.get(JSON_URL) r = requests.get(JSON_URL)
print('-'*40) print("-" * 40)
print(r.json()) print(r.json())
print('-'*40) print("-" * 40)
r.close() r.close()
print("Done!") print("Done!")

View file

@ -1,3 +1,6 @@
# SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
import time import time
import board import board
import busio import busio
@ -30,23 +33,32 @@ except AttributeError:
spi = busio.SPI(board.SCK, board.MOSI, board.MISO) spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
"""Use below for Most Boards""" """Use below for Most Boards"""
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards status_light = neopixel.NeoPixel(
board.NEOPIXEL, 1, brightness=0.2
) # Uncomment for Most Boards
"""Uncomment below for ItsyBitsy M4""" """Uncomment below for ItsyBitsy M4"""
#status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2)
wifi = ESPSPI_WiFiManager(esp, secrets, status_light, connection_type=ESPSPI_WiFiManager.ENTERPRISE) wifi = ESPSPI_WiFiManager(
esp, secrets, status_light, connection_type=ESPSPI_WiFiManager.ENTERPRISE
)
counter = 0 counter = 0
while True: while True:
try: try:
print("Posting data...", end='') print("Posting data...", end="")
data = counter data = counter
feed = 'test' feed = "test"
payload = {'value':data} payload = {"value": data}
response = wifi.post( response = wifi.post(
"https://io.adafruit.com/api/v2/"+secrets['aio_username']+"/feeds/"+feed+"/data", "https://io.adafruit.com/api/v2/"
+ secrets["aio_username"]
+ "/feeds/"
+ feed
+ "/data",
json=payload, json=payload,
headers={"X-AIO-KEY":secrets['aio_key']}) headers={"X-AIO-KEY": secrets["aio_key"]},
)
print(response.json()) print(response.json())
response.close() response.close()
counter = counter + 1 counter = counter + 1

View file

@ -1,3 +1,6 @@
# SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT
# Example code implementing WPA2 Enterprise mode # Example code implementing WPA2 Enterprise mode
# #
# This code requires firmware version 1.3.0, or newer, running # This code requires firmware version 1.3.0, or newer, running
@ -21,8 +24,12 @@ import adafruit_requests as requests
# support Python 3.x and thus, CircuitPython # support Python 3.x and thus, CircuitPython
def version_compare(version1, version2): def version_compare(version1, version2):
def normalize(v): def normalize(v):
return [int(x) for x in re.sub(r'(\.0+)*$','', v).split(".")] return [int(x) for x in re.sub(r"(\.0+)*$", "", v).split(".")]
return (normalize(version1) > normalize(version2)) - (normalize(version1) < normalize(version2))
return (normalize(version1) > normalize(version2)) - (
normalize(version1) < normalize(version2)
)
print("ESP32 SPI WPA2 Enterprise test") print("ESP32 SPI WPA2 Enterprise test")
@ -48,30 +55,31 @@ if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
# Get the ESP32 fw version number, remove trailing byte off the returned bytearray # Get the ESP32 fw version number, remove trailing byte off the returned bytearray
# and then convert it to a string for prettier printing and later comparison # and then convert it to a string for prettier printing and later comparison
firmware_version = ''.join([chr(b) for b in esp.firmware_version[:-1]]) firmware_version = "".join([chr(b) for b in esp.firmware_version[:-1]])
print("Firmware vers.", firmware_version) print("Firmware vers.", firmware_version)
print("MAC addr:", [hex(i) for i in esp.MAC_address]) print("MAC addr:", [hex(i) for i in esp.MAC_address])
# WPA2 Enterprise support was added in fw ver 1.3.0. Check that the ESP32 # WPA2 Enterprise support was added in fw ver 1.3.0. Check that the ESP32
# is running at least that version, otherwise, bail out # is running at least that version, otherwise, bail out
assert version_compare(firmware_version, "1.3.0") >= 0, ( assert (
"Incorrect ESP32 firmware version; >= 1.3.0 required.") version_compare(firmware_version, "1.3.0") >= 0
), "Incorrect ESP32 firmware version; >= 1.3.0 required."
# Set up the SSID you would like to connect to # Set up the SSID you would like to connect to
# Note that we need to call wifi_set_network prior # Note that we need to call wifi_set_network prior
# to calling wifi_set_enable. # to calling wifi_set_enable.
esp.wifi_set_network(b'YOUR_SSID_HERE') esp.wifi_set_network(b"YOUR_SSID_HERE")
# If your WPA2 Enterprise network requires an anonymous # If your WPA2 Enterprise network requires an anonymous
# identity to be set, you may set that here # identity to be set, you may set that here
esp.wifi_set_entidentity(b'') esp.wifi_set_entidentity(b"")
# Set the WPA2 Enterprise username you'd like to use # Set the WPA2 Enterprise username you'd like to use
esp.wifi_set_entusername(b'MY_USERNAME') esp.wifi_set_entusername(b"MY_USERNAME")
# Set the WPA2 Enterprise password you'd like to use # Set the WPA2 Enterprise password you'd like to use
esp.wifi_set_entpassword(b'MY_PASSWORD') esp.wifi_set_entpassword(b"MY_PASSWORD")
# Once the network settings have been configured, # Once the network settings have been configured,
# we need to enable WPA2 Enterprise mode on the ESP32 # we need to enable WPA2 Enterprise mode on the ESP32
@ -80,13 +88,15 @@ esp.wifi_set_entenable()
# Wait for the network to come up # Wait for the network to come up
print("Connecting to AP...") print("Connecting to AP...")
while not esp.is_connected: while not esp.is_connected:
print(".", end = "") print(".", end="")
time.sleep(2) time.sleep(2)
print("") print("")
print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi) print("Connected to", str(esp.ssid, "utf-8"), "\tRSSI:", esp.rssi)
print("My IP address is", esp.pretty_ip(esp.ip_address)) print("My IP address is", esp.pretty_ip(esp.ip_address))
print("IP lookup adafruit.com: %s" % esp.pretty_ip(esp.get_host_by_name("adafruit.com"))) print(
"IP lookup adafruit.com: %s" % esp.pretty_ip(esp.get_host_by_name("adafruit.com"))
)
print("Ping google.com: %d ms" % esp.ping("google.com")) print("Ping google.com: %d ms" % esp.ping("google.com"))
print("Done!") print("Done!")

View file

@ -0,0 +1,177 @@
# SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
#
# SPDX-License-Identifier: MIT
import time
import random
import board
from digitalio import DigitalInOut, Direction
import pulseio
from adafruit_esp32spi import adafruit_esp32spi
# ESP32SPI Digital and Analog Pin Reads & Writes
# This example targets a Feather M4 or ItsyBitsy M4 as the CircuitPython MCU,
# along with either an ESP32 Feather or ESP32 Breakout as Wi-Fi co-processor.
# You may need to choose different pins for other targets.
def esp_reset_all():
# esp.reset() will reset the ESP32 using its RST pin
# side effect is re-initializing ESP32 pin modes and debug output
esp.reset()
time.sleep(1)
# (re-)set NINA serial debug on ESP32 TX
esp.set_esp_debug(True) # False, True
# (re-)set digital pin modes
esp_init_pin_modes(ESP_D_R_PIN, ESP_D_W_PIN)
def esp_init_pin_modes(din, dout):
# ESP32 Digital Input
esp.set_pin_mode(din, 0x0)
# ESP32 Digital Output (no output on pins 34-39)
esp.set_pin_mode(dout, 0x1)
# M4 R/W Pin Assignments
M4_D_W_PIN = DigitalInOut(board.A1) # digital write to ESP_D_R_PIN
M4_D_W_PIN.direction = Direction.OUTPUT
M4_A_R_PIN = pulseio.PulseIn(board.A0, maxlen=64) # PWM read from ESP_A_W_PIN
M4_A_R_PIN.pause()
# ESP32 R/W Pin assignments & connections
ESP_D_R_PIN = 12 # digital read from M4_D_W_PIN
ESP_D_W_PIN = 13 # digital write to Red LED on Feather ESP32 and ESP32 Breakout
# ESP32 Analog Input using ADC1
# esp.set_pin_mode(36, 0x0) # Hall Effect Sensor
# esp.set_pin_mode(37, 0x0) # Not Exposed
# esp.set_pin_mode(38, 0x0) # Not Exposed
# esp.set_pin_mode(39, 0x0) # Hall Effect Sensor
# esp.set_pin_mode(32, 0x0) # INPUT OK
# esp.set_pin_mode(33, 0x0) # DO NOT USE: ESP32SPI Busy/!Rdy
# esp.set_pin_mode(34, 0x0) # INPUT OK
# esp.set_pin_mode(35, 0x0) # INPUT OK (1/2 of Battery on ESP32 Feather)
ESP_A_R_PIN = 32 # analog read from 10k potentiometer
# ESP32 Analog (PWM/LEDC) Output (no output on pins 34-39)
ESP_A_W_PIN = 27 # analog (PWM) write to M4_A_R_PIN
spi = board.SPI()
# Airlift FeatherWing & Bitsy Add-On compatible
esp32_cs = DigitalInOut(board.D13) # M4 Red LED
esp32_ready = DigitalInOut(board.D11)
esp32_reset = DigitalInOut(board.D12)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset)
esp_reset_all()
espfirmware = ""
for _ in esp.firmware_version:
if _ != 0:
espfirmware += "{:c}".format(_)
print("ESP32 Firmware:", espfirmware)
print(
"ESP32 MAC: {5:02X}:{4:02X}:{3:02X}:{2:02X}:{1:02X}:{0:02X}".format(
*esp.MAC_address
)
)
# initial digital write values
m4_d_w_val = False
esp_d_w_val = False
while True:
print("\nESP32 DIGITAL:")
# ESP32 digital read
try:
M4_D_W_PIN.value = m4_d_w_val
print("M4 wrote:", m4_d_w_val, end=" ")
# b/c ESP32 might have reset out from under us
esp_init_pin_modes(ESP_D_R_PIN, ESP_D_W_PIN)
esp_d_r_val = esp.set_digital_read(ESP_D_R_PIN)
print("--> ESP read:", esp_d_r_val)
except (RuntimeError, AssertionError) as e:
print("ESP32 Error", e)
esp_reset_all()
# ESP32 digital write
try:
# b/c ESP32 might have reset out from under us
esp_init_pin_modes(ESP_D_R_PIN, ESP_D_W_PIN)
esp.set_digital_write(ESP_D_W_PIN, esp_d_w_val)
print("ESP wrote:", esp_d_w_val, "--> Red LED")
except (RuntimeError) as e:
print("ESP32 Error", e)
esp_reset_all()
print("ESP32 ANALOG:")
# ESP32 analog read
try:
esp_a_r_val = esp.set_analog_read(ESP_A_R_PIN)
print(
"Potentiometer --> ESP read: ",
esp_a_r_val,
" (",
"{:1.1f}".format(esp_a_r_val * 3.3 / 65536),
"v)",
sep="",
)
except (RuntimeError, AssertionError) as e:
print("ESP32 Error", e)
esp_reset_all()
# ESP32 analog write
try:
# don't set the low end to 0 or the M4's pulseio read will stall
esp_a_w_val = random.uniform(0.1, 0.9)
esp.set_analog_write(ESP_A_W_PIN, esp_a_w_val)
print(
"ESP wrote: ",
"{:1.2f}".format(esp_a_w_val),
" (",
"{:d}".format(int(esp_a_w_val * 65536)),
")",
" (",
"{:1.1f}".format(esp_a_w_val * 3.3),
"v)",
sep="",
end=" ",
)
# ESP32 "analog" write is a 1000Hz PWM
# use pulseio to extract the duty cycle
M4_A_R_PIN.clear()
M4_A_R_PIN.resume()
while len(M4_A_R_PIN) < 2:
pass
M4_A_R_PIN.pause()
duty = M4_A_R_PIN[0] / (M4_A_R_PIN[0] + M4_A_R_PIN[1])
print(
"--> M4 read: ",
"{:1.2f}".format(duty),
" (",
"{:d}".format(int(duty * 65536)),
")",
" (",
"{:1.1f}".format(duty * 3.3),
"v)",
" [len=",
len(M4_A_R_PIN),
"]",
sep="",
)
except (RuntimeError) as e:
print("ESP32 Error", e)
esp_reset_all()
# toggle digital write values
m4_d_w_val = not m4_d_w_val
esp_d_w_val = not esp_d_w_val
time.sleep(5)

92
examples/gpio/gpio.md Normal file
View file

@ -0,0 +1,92 @@
<!--
SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
SPDX-License-Identifier: MIT
-->
# Using ESP32 co-processor GPIO pins with CircuitPython ESP32SPI
As of NINA firmware version 1.3.1, the ESP32SPI library can be used to write digital values to many of the ESP32 GPIO pins using CircuitPython. It can also write "analog" signals using a float between 0 and 1 as the duty cycle (which is converted to an 8-bit integer for use by the NINA firmware). Keep in mind that these are 1000Hz PWM signals using the ESP32 LED Control peripheral, not true analog signals using an on-chip DAC. More information can be found here:
<https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/ledc.html>
As of NINA firmware version 1.5.0, the ESP32SPI library can be used to read digital signals from many of the ESP32 GPIO pins using CircuitPython. It can also read analog signals using ESP32 on-chip ADC1. The ESP32 can theoretically be set to use between 8 and 12 bits of resolution for analog reads. For our purposes, it is a 12-bit read within the NINA firmware, but the CircuitPython library converts it to a 16-bit integer consistent with CircuitPython `analogio` `AnalogIn`. There's an optional keyword argument in the `set_analog_read(self, pin, atten=ADC_ATTEN_DB_11)` function that changes the attenuation of the analog read, and therefore also changes the effective voltage range of the read. With the default 11dB attenuation, Espressif recommends keeping input voltages between 150mV to 2450mV for best results. More information can be found here:
<https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/adc.html>
## GPIO Pins available to ESP32SPI
```
# ESP32_GPIO_PINS:
# https://github.com/adafruit/Adafruit_CircuitPython_ESP32SPI/blob/master/adafruit_esp32spi/digitalio.py
# 0, 1, 2, 4, 5, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 25, 26, 27, 32, 33, 34, 35, 36, 39
#
# Pins Used for ESP32SPI
# 5, 14, 18, 23, 33
# Avialable ESP32SPI Outputs (digital or 'analog' PWM) with NINA FW >= 1.3.1
#
# Adafruit ESP32 Breakout
# *, 2, 4, 12, R, 15, 16, 17, 19, 21, 22, 25, 26, 27, 32
# Adafruit ESP32 Feather
# 4, 12, R, 15, 16, 17, 19, 21, 22, 25, 26, 27, 32
# TinyPICO
# 4, 15, 19, 21, 22, 25, 26, 27, 32
# Adafruit ESP32 Airlift Breakout†
# G, R, B
# Adafruit ESP32 Airlift Feather†
# G, R, B
# Adafruit ESP32 Airlift Bitsy Add-On†
# G, R, B
# Avialable ESP32SPI Digital Inputs with NINA FW >= 1.5.0
#
# Adafruit ESP32 Breakout
# *, 2, 4, 12, R, 15, 16, 17, 19, 21, 22, 25, 26, 27, 32, 34, 35, 36, 39
# Adafruit ESP32 Feather
# 4, 12, R, 15, 16, 17, 19, 21, 22, 25, 26, 27, 32, 34, 36, 39
# TinyPICO
# 4, 15, 19, 21, 22, 25, 26, 27, 32 CH
# Avialable ESP32SPI Analog Inputs (ADC1) with NINA FW >= 1.5.0
#
# Adafruit ESP32 Breakout
# *, 32, 34, 35, HE, HE
# Adafruit ESP32 Feather
# *, 32, 34, BA, HE, HE
# TinyPICO
# 32, BA
Notes:
* Used for bootloading
G Green LED
R Red LED
B Blue LED
BA On-board connection to battery via 50:50 voltage divider
CH Battery charging state (digital pin)
HE Hall Effect sensor
```
Note that on the Airlift FeatherWing and the Airlift Bitsy Add-On, the ESP32 SPI Chip Select (CS) pin aligns with M4's D13 Red LED pin:
```
esp32_cs = DigitalInOut(board.D13) # M4 Red LED
esp32_ready = DigitalInOut(board.D11)
esp32_reset = DigitalInOut(board.D12)
```
So the Red LED on the main Feather processor will almost always appear to be ON or slightly flickering when ESP32SPI is active.
## ESP32 Reset
Because the ESP32 may reset without indication to the CircuitPython code, putting ESP32 GPIO pins into input mode, `esp.set_digital_write(pin, val)` should be preceded by `esp.set_pin_mode(pin, 0x1)`, with appropriate error handling. Other non-default `esp` states (e.g., `esp.set_esp_debug()`) will also get re-initialized to default settings upon ESP32 reset, so CircuitPython code should anticipate this.
## GPIO on Airlift add-on boards
It should also be possible to do ESP32SPI reads and writes on the Airlift add-on boards, but other than the SPI pins and the green, blue, and red LEDs, the only pins available are RX (GPIO3), TX (GPIO1), and GPIO0, so function is extremely limited. Analog input is ruled out since none of those pins are on ADC1.
The Airlift Breakout has level-shifting on RX and GPIO0, so those could be digital inputs only. TX could be used as a digital input or as a digital or analog (PWM) output.
The Airlift FeatherWing and Bitsy Add-On have no level-shifting since they're designed to be stacked onto their associated M4 microcontrollers, so theoretically RX, TX, and GPIO0 could be used as digital inputs, or as digital or analog (PWM) outputs. It's hard to find a use case for doing this when stacked since RX, TX, and GPIO0 will be connected to M4 GPIO pins.
The Airlift [Metro / Arduino] Shield has level-shifting on RX and GPIO0, with stacking issues similar to the FeatherWings.
The RX, TX, and GPIO0 pins are used for updating the NINA firmware, and have specific behaviors immediately following reboot that need to be considered if reusing them as GPIO. On the Airlift FeatherWing and Bitsy Add-On, there are pads that need to be soldered to connect the pins. NINA does output messages to TX when connected, depending on the esp debug level set.
Ultimately it makes the most sense by far to use a non-stacked full-pinout ESP32 as co-processor for ESP32SPI pin read and write features.

57
examples/server/esp32spi_wsgiserver.py Normal file → Executable file
View file

@ -1,3 +1,7 @@
# SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
#
# SPDX-License-Identifier: MIT
import os import os
import board import board
import busio import busio
@ -37,11 +41,18 @@ esp32_reset = DigitalInOut(board.ESP_RESET)
# esp32_reset = DigitalInOut(board.D5) # esp32_reset = DigitalInOut(board.D5)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO) spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) # pylint: disable=line-too-long esp = adafruit_esp32spi.ESP_SPIcontrol(
spi, esp32_cs, esp32_ready, esp32_reset
) # pylint: disable=line-too-long
"""Use below for Most Boards""" print("MAC addr:", [hex(i) for i in esp.MAC_address])
status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2) # Uncomment for Most Boards print("MAC addr actual:", [hex(i) for i in esp.MAC_address_actual])
"""Uncomment below for ItsyBitsy M4"""
# Use below for Most Boards
status_light = neopixel.NeoPixel(
board.NEOPIXEL, 1, brightness=0.2
) # Uncomment for Most Boards
# Uncomment below for ItsyBitsy M4
# import adafruit_dotstar as dotstar # import adafruit_dotstar as dotstar
# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=1) # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=1)
@ -59,6 +70,7 @@ wifi.connect()
# wifi = wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light) # wifi = wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light)
# wifi.create_ap() # wifi.create_ap()
class SimpleWSGIApplication: class SimpleWSGIApplication:
""" """
An example of a simple WSGI Application that supports An example of a simple WSGI Application that supports
@ -91,15 +103,21 @@ class SimpleWSGIApplication:
headers = [] headers = []
resp_data = [] resp_data = []
key = self._get_listener_key(environ["REQUEST_METHOD"].lower(), environ["PATH_INFO"]) key = self._get_listener_key(
environ["REQUEST_METHOD"].lower(), environ["PATH_INFO"]
)
if key in self._listeners: if key in self._listeners:
status, headers, resp_data = self._listeners[key](environ) status, headers, resp_data = self._listeners[key](environ)
if environ["REQUEST_METHOD"].lower() == "get" and self._static: if environ["REQUEST_METHOD"].lower() == "get" and self._static:
path = environ["PATH_INFO"] path = environ["PATH_INFO"]
if path in self._static_files: if path in self._static_files:
status, headers, resp_data = self.serve_file(path, directory=self._static) status, headers, resp_data = self.serve_file(
path, directory=self._static
)
elif path == "/" and self.INDEX in self._static_files: elif path == "/" and self.INDEX in self._static_files:
status, headers, resp_data = self.serve_file(self.INDEX, directory=self._static) status, headers, resp_data = self.serve_file(
self.INDEX, directory=self._static
)
self._start_response(status, headers) self._start_response(status, headers)
return resp_data return resp_data
@ -125,8 +143,9 @@ class SimpleWSGIApplication:
headers = [("Content-Type", self._get_content_type(file_path))] headers = [("Content-Type", self._get_content_type(file_path))]
full_path = file_path if not directory else directory + file_path full_path = file_path if not directory else directory + file_path
def resp_iter(): def resp_iter():
with open(full_path, 'rb') as file: with open(full_path, "rb") as file:
while True: while True:
chunk = file.read(self.CHUNK_SIZE) chunk = file.read(self.CHUNK_SIZE)
if chunk: if chunk:
@ -145,7 +164,7 @@ class SimpleWSGIApplication:
return "{0}|{1}".format(method.lower(), path) return "{0}|{1}".format(method.lower(), path)
def _get_content_type(self, file): # pylint: disable=no-self-use def _get_content_type(self, file): # pylint: disable=no-self-use
ext = file.split('.')[-1] ext = file.split(".")[-1]
if ext in ("html", "htm"): if ext in ("html", "htm"):
return "text/html" return "text/html"
if ext == "js": if ext == "js":
@ -158,17 +177,20 @@ class SimpleWSGIApplication:
return "image/png" return "image/png"
return "text/plain" return "text/plain"
# Our HTTP Request handlers # Our HTTP Request handlers
def led_on(environ): # pylint: disable=unused-argument def led_on(environ): # pylint: disable=unused-argument
print("led on!") print("led on!")
status_light.fill((0, 0, 100)) status_light.fill((0, 0, 100))
return web_app.serve_file("static/index.html") return web_app.serve_file("static/index.html")
def led_off(environ): # pylint: disable=unused-argument def led_off(environ): # pylint: disable=unused-argument
print("led off!") print("led off!")
status_light.fill(0) status_light.fill(0)
return web_app.serve_file("static/index.html") return web_app.serve_file("static/index.html")
def led_color(environ): # pylint: disable=unused-argument def led_color(environ): # pylint: disable=unused-argument
json = json_module.loads(environ["wsgi.input"].getvalue()) json = json_module.loads(environ["wsgi.input"].getvalue())
print(json) print(json)
@ -176,6 +198,7 @@ def led_color(environ): # pylint: disable=unused-argument
status_light.fill(rgb_tuple) status_light.fill(rgb_tuple)
return ("200 OK", [], []) return ("200 OK", [], [])
# Here we create our application, setting the static directory location # Here we create our application, setting the static directory location
# and registering the above request_handlers for specific HTTP requests # and registering the above request_handlers for specific HTTP requests
# we want to listen and respond to. # we want to listen and respond to.
@ -183,13 +206,21 @@ static = "/static"
try: try:
static_files = os.listdir(static) static_files = os.listdir(static)
if "index.html" not in static_files: if "index.html" not in static_files:
raise RuntimeError(""" raise RuntimeError(
"""
This example depends on an index.html, but it isn't present. This example depends on an index.html, but it isn't present.
Please add it to the {0} directory""".format(static)) Please add it to the {0} directory""".format(
static
)
)
except (OSError) as e: except (OSError) as e:
raise RuntimeError(""" raise RuntimeError(
"""
This example depends on a static asset directory. This example depends on a static asset directory.
Please create one named {0} in the root of the device filesystem.""".format(static)) Please create one named {0} in the root of the device filesystem.""".format(
static
)
)
web_app = SimpleWSGIApplication(static_dir=static) web_app = SimpleWSGIApplication(static_dir=static)
web_app.on("GET", "/led_on", led_on) web_app.on("GET", "/led_on", led_on)

View file

@ -1,3 +1,9 @@
<!--
SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
SPDX-License-Identifier: MIT
-->
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<head> <head>

View file

@ -1,3 +1,7 @@
// SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
//
// SPDX-License-Identifier: MIT
let canvas = document.getElementById('colorPicker'); let canvas = document.getElementById('colorPicker');
let ctx = canvas.getContext("2d"); let ctx = canvas.getContext("2d");
ctx.width = 300; ctx.width = 300;
@ -123,4 +127,3 @@ function getCursorPosition(canvas, event) {
drawColorPicker(); drawColorPicker();
canvas.addEventListener('mousedown', onColorPick); canvas.addEventListener('mousedown', onColorPick);

6
pyproject.toml Normal file
View file

@ -0,0 +1,6 @@
# SPDX-FileCopyrightText: 2020 Diego Elio Pettenò
#
# SPDX-License-Identifier: Unlicense
[tool.black]
target-version = ['py35']

View file

@ -1,2 +1,6 @@
# SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
#
# SPDX-License-Identifier: Unlicense
Adafruit-Blinka Adafruit-Blinka
adafruit-circuitpython-busdevice adafruit-circuitpython-busdevice

View file

@ -1,3 +1,7 @@
# SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""A setuptools based setup module. """A setuptools based setup module.
See: See:
@ -6,6 +10,7 @@ https://github.com/pypa/sampleproject
""" """
from setuptools import setup, find_packages from setuptools import setup, find_packages
# To use a consistent encoding # To use a consistent encoding
from codecs import open from codecs import open
from os import path from os import path
@ -13,52 +18,40 @@ from os import path
here = path.abspath(path.dirname(__file__)) here = path.abspath(path.dirname(__file__))
# Get the long description from the README file # Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f: with open(path.join(here, "README.rst"), encoding="utf-8") as f:
long_description = f.read() long_description = f.read()
setup( setup(
name='adafruit-circuitpython-esp32spi', name="adafruit-circuitpython-esp32spi",
use_scm_version=True, use_scm_version=True,
setup_requires=['setuptools_scm'], setup_requires=["setuptools_scm"],
description="CircuitPython driver library for using ESP32 as WiFi co-processor using SPI",
description='CircuitPython driver library for using ESP32 as WiFi co-processor using SPI',
long_description=long_description, long_description=long_description,
long_description_content_type='text/x-rst', long_description_content_type="text/x-rst",
# The project's main homepage. # The project's main homepage.
url='https://github.com/adafruit/Adafruit_CircuitPython_ESP32SPI', url="https://github.com/adafruit/Adafruit_CircuitPython_ESP32SPI",
# Author details # Author details
author='Adafruit Industries', author="Adafruit Industries",
author_email='circuitpython@adafruit.com', author_email="circuitpython@adafruit.com",
install_requires=["Adafruit-Blinka", "adafruit-circuitpython-busdevice"],
install_requires=[
'Adafruit-Blinka',
'adafruit-circuitpython-busdevice'
],
# Choose your license # Choose your license
license='MIT', license="MIT",
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[ classifiers=[
'Development Status :: 3 - Alpha', "Development Status :: 3 - Alpha",
'Intended Audience :: Developers', "Intended Audience :: Developers",
'Topic :: Software Development :: Libraries', "Topic :: Software Development :: Libraries",
'Topic :: System :: Hardware', "Topic :: System :: Hardware",
'License :: OSI Approved :: MIT License', "License :: OSI Approved :: MIT License",
'Programming Language :: Python :: 3', "Programming Language :: Python :: 3",
'Programming Language :: Python :: 3.4', "Programming Language :: Python :: 3.4",
'Programming Language :: Python :: 3.5', "Programming Language :: Python :: 3.5",
], ],
# What does your project relate to? # What does your project relate to?
keywords='adafruit blinka circuitpython micropython esp32spi wifi esp32', keywords="adafruit blinka circuitpython micropython esp32spi wifi esp32",
# You can just specify the packages manually here if your project is # You can just specify the packages manually here if your project is
# simple. Or you can use find_packages(). # simple. Or you can use find_packages().
# TODO: IF LIBRARY FILES ARE A PACKAGE FOLDER, # TODO: IF LIBRARY FILES ARE A PACKAGE FOLDER,
# CHANGE `py_modules=['...']` TO `packages=['...']` # CHANGE `py_modules=['...']` TO `packages=['...']`
packages=['adafruit_esp32spi'], packages=["adafruit_esp32spi"],
) )