From 1820bb00d3017a33cf4c7e248efd2cf4794c9d50 Mon Sep 17 00:00:00 2001 From: kevin-tritz Date: Sun, 12 May 2024 16:51:13 -0400 Subject: [PATCH] black format --- .../adafruit_circuitpython_pr.md | 26 +- .github/workflows/build.yml | 28 +- .github/workflows/failure-help-text.yml | 38 +- .github/workflows/release_gh.yml | 38 +- .github/workflows/release_pypi.yml | 38 +- .gitignore | 110 +- .pre-commit-config.yaml | 84 +- .pylintrc | 798 +++--- .readthedocs.yaml | 38 +- CODE_OF_CONDUCT.md | 270 +- LICENSE | 56 +- LICENSES/CC-BY-4.0.txt | 648 ++--- LICENSES/EPL-1.0.txt | 116 +- LICENSES/MIT.txt | 38 +- LICENSES/Unlicense.txt | 40 +- README.rst | 150 +- README.rst.license | 6 +- adafruit_minimqtt/adafruit_minimqtt.py | 2302 +++++++++-------- adafruit_minimqtt/matcher.py | 202 +- docs/_static/favicon.ico.license | 6 +- docs/api.rst | 16 +- docs/api.rst.license | 6 +- docs/conf.py | 362 +-- docs/examples.rst | 16 +- docs/examples.rst.license | 6 +- docs/index.rst | 92 +- docs/index.rst.license | 6 +- docs/requirements.txt | 14 +- .../cellular/minimqtt_adafruitio_cellular.py | 224 +- .../cellular/minimqtt_simpletest_cellular.py | 240 +- .../cpython/minimqtt_adafruitio_cpython.py | 160 +- .../cpython/minimqtt_simpletest_cpython.py | 184 +- examples/cpython/user_data.py | 198 +- .../esp32spi/minimqtt_adafruitio_esp32spi.py | 232 +- .../esp32spi/minimqtt_certificate_esp32spi.py | 290 +-- .../minimqtt_pub_sub_blocking_esp32spi.py | 242 +- ...b_sub_blocking_topic_callbacks_esp32spi.py | 266 +- .../minimqtt_pub_sub_nonblocking_esp32spi.py | 226 +- .../minimqtt_pub_sub_pyportal_esp32spi.py | 172 +- .../esp32spi/minimqtt_simpletest_esp32spi.py | 244 +- examples/ethernet/minimqtt_adafruitio_eth.py | 182 +- examples/ethernet/minimqtt_simpletest_eth.py | 202 +- examples/minimqtt_simpletest.py | 248 +- .../minimqtt_adafruitio_native_networking.py | 198 +- ...mqtt_pub_sub_blocking_native_networking.py | 200 +- ...cking_topic_callbacks_native_networking.py | 224 +- optional_requirements.txt | 6 +- pyproject.toml | 94 +- requirements.txt | 14 +- tests/conftest.py | 34 +- tests/mocket.py | 82 +- tests/test_backoff.py | 112 +- tests/test_loop.py | 524 ++-- tests/test_port_ssl.py | 250 +- tests/test_subscribe.py | 456 ++-- tests/test_unsubscribe.py | 306 +-- tox.ini | 78 +- 57 files changed, 5720 insertions(+), 5718 deletions(-) diff --git a/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md b/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md index 8de294e6..6576f620 100644 --- a/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md +++ b/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md @@ -1,13 +1,13 @@ -# SPDX-FileCopyrightText: 2021 Adafruit Industries -# -# SPDX-License-Identifier: MIT - -Thank you for contributing! Before you submit a pull request, please read the following. - -Make sure any changes you're submitting are in line with the CircuitPython Design Guide, available here: https://docs.circuitpython.org/en/latest/docs/design_guide.html - -If your changes are to documentation, please verify that the documentation builds locally by following the steps found here: https://adafru.it/build-docs - -Before submitting the pull request, make sure you've run Pylint and Black locally on your code. You can do this manually or using pre-commit. Instructions are available here: https://adafru.it/check-your-code - -Please remove all of this text before submitting. Include an explanation or list of changes included in your PR, as well as, if applicable, a link to any related issues. +# SPDX-FileCopyrightText: 2021 Adafruit Industries +# +# SPDX-License-Identifier: MIT + +Thank you for contributing! Before you submit a pull request, please read the following. + +Make sure any changes you're submitting are in line with the CircuitPython Design Guide, available here: https://docs.circuitpython.org/en/latest/docs/design_guide.html + +If your changes are to documentation, please verify that the documentation builds locally by following the steps found here: https://adafru.it/build-docs + +Before submitting the pull request, make sure you've run Pylint and Black locally on your code. You can do this manually or using pre-commit. Instructions are available here: https://adafru.it/check-your-code + +Please remove all of this text before submitting. Include an explanation or list of changes included in your PR, as well as, if applicable, a link to any related issues. diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 041a337c..fbd01e3c 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -1,14 +1,14 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# -# SPDX-License-Identifier: MIT - -name: Build CI - -on: [pull_request, push] - -jobs: - test: - runs-on: ubuntu-latest - steps: - - name: Run Build CI workflow - uses: adafruit/workflows-circuitpython-libs/build@main +# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +name: Build CI + +on: [pull_request, push] + +jobs: + test: + runs-on: ubuntu-latest + steps: + - name: Run Build CI workflow + uses: adafruit/workflows-circuitpython-libs/build@main diff --git a/.github/workflows/failure-help-text.yml b/.github/workflows/failure-help-text.yml index 0b1194f0..17dad74c 100644 --- a/.github/workflows/failure-help-text.yml +++ b/.github/workflows/failure-help-text.yml @@ -1,19 +1,19 @@ -# SPDX-FileCopyrightText: 2021 Scott Shawcroft for Adafruit Industries -# -# SPDX-License-Identifier: MIT - -name: Failure help text - -on: - workflow_run: - workflows: ["Build CI"] - types: - - completed - -jobs: - post-help: - runs-on: ubuntu-latest - if: ${{ github.event.workflow_run.conclusion == 'failure' && github.event.workflow_run.event == 'pull_request' }} - steps: - - name: Post comment to help - uses: adafruit/circuitpython-action-library-ci-failed@v1 +# SPDX-FileCopyrightText: 2021 Scott Shawcroft for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +name: Failure help text + +on: + workflow_run: + workflows: ["Build CI"] + types: + - completed + +jobs: + post-help: + runs-on: ubuntu-latest + if: ${{ github.event.workflow_run.conclusion == 'failure' && github.event.workflow_run.event == 'pull_request' }} + steps: + - name: Post comment to help + uses: adafruit/circuitpython-action-library-ci-failed@v1 diff --git a/.github/workflows/release_gh.yml b/.github/workflows/release_gh.yml index 9acec601..79c5573f 100644 --- a/.github/workflows/release_gh.yml +++ b/.github/workflows/release_gh.yml @@ -1,19 +1,19 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# -# SPDX-License-Identifier: MIT - -name: GitHub Release Actions - -on: - release: - types: [published] - -jobs: - upload-release-assets: - runs-on: ubuntu-latest - steps: - - name: Run GitHub Release CI workflow - uses: adafruit/workflows-circuitpython-libs/release-gh@main - with: - github-token: ${{ secrets.GITHUB_TOKEN }} - upload-url: ${{ github.event.release.upload_url }} +# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +name: GitHub Release Actions + +on: + release: + types: [published] + +jobs: + upload-release-assets: + runs-on: ubuntu-latest + steps: + - name: Run GitHub Release CI workflow + uses: adafruit/workflows-circuitpython-libs/release-gh@main + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + upload-url: ${{ github.event.release.upload_url }} diff --git a/.github/workflows/release_pypi.yml b/.github/workflows/release_pypi.yml index 65775b7b..c16b495a 100644 --- a/.github/workflows/release_pypi.yml +++ b/.github/workflows/release_pypi.yml @@ -1,19 +1,19 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# -# SPDX-License-Identifier: MIT - -name: PyPI Release Actions - -on: - release: - types: [published] - -jobs: - upload-release-assets: - runs-on: ubuntu-latest - steps: - - name: Run PyPI Release CI workflow - uses: adafruit/workflows-circuitpython-libs/release-pypi@main - with: - pypi-username: ${{ secrets.pypi_username }} - pypi-password: ${{ secrets.pypi_password }} +# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +name: PyPI Release Actions + +on: + release: + types: [published] + +jobs: + upload-release-assets: + runs-on: ubuntu-latest + steps: + - name: Run PyPI Release CI workflow + uses: adafruit/workflows-circuitpython-libs/release-pypi@main + with: + pypi-username: ${{ secrets.pypi_username }} + pypi-password: ${{ secrets.pypi_password }} diff --git a/.gitignore b/.gitignore index a06dc67a..988e17fa 100644 --- a/.gitignore +++ b/.gitignore @@ -1,55 +1,55 @@ -# SPDX-FileCopyrightText: 2022 Kattni Rembor, written for Adafruit Industries -# -# SPDX-License-Identifier: MIT - -# Do not include files and directories created by your personal work environment, such as the IDE -# you use, except for those already listed here. Pull requests including changes to this file will -# not be accepted. - -# This .gitignore file contains rules for files generated by working with CircuitPython libraries, -# including building Sphinx, testing with pip, and creating a virual environment, as well as the -# MacOS and IDE-specific files generated by using MacOS in general, or the PyCharm or VSCode IDEs. - -# If you find that there are files being generated on your machine that should not be included in -# your git commit, you should create a .gitignore_global file on your computer to include the -# files created by your personal setup. To do so, follow the two steps below. - -# First, create a file called .gitignore_global somewhere convenient for you, and add rules for -# the files you want to exclude from git commits. - -# Second, configure Git to use the exclude file for all Git repositories by running the -# following via commandline, replacing "path/to/your/" with the actual path to your newly created -# .gitignore_global file: -# git config --global core.excludesfile path/to/your/.gitignore_global - -# CircuitPython-specific files -*.mpy - -# Python-specific files -__pycache__ -*.pyc - -# Sphinx build-specific files -_build - -# This file results from running `pip -e install .` in a local repository -*.egg-info - -# Virtual environment-specific files -.env -.venv - -# MacOS-specific files -*.DS_Store - -# IDE-specific files -.idea -.vscode -*~ - -# tox-specific files -.tox -build - -# coverage-specific files -.coverage +# SPDX-FileCopyrightText: 2022 Kattni Rembor, written for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +# Do not include files and directories created by your personal work environment, such as the IDE +# you use, except for those already listed here. Pull requests including changes to this file will +# not be accepted. + +# This .gitignore file contains rules for files generated by working with CircuitPython libraries, +# including building Sphinx, testing with pip, and creating a virual environment, as well as the +# MacOS and IDE-specific files generated by using MacOS in general, or the PyCharm or VSCode IDEs. + +# If you find that there are files being generated on your machine that should not be included in +# your git commit, you should create a .gitignore_global file on your computer to include the +# files created by your personal setup. To do so, follow the two steps below. + +# First, create a file called .gitignore_global somewhere convenient for you, and add rules for +# the files you want to exclude from git commits. + +# Second, configure Git to use the exclude file for all Git repositories by running the +# following via commandline, replacing "path/to/your/" with the actual path to your newly created +# .gitignore_global file: +# git config --global core.excludesfile path/to/your/.gitignore_global + +# CircuitPython-specific files +*.mpy + +# Python-specific files +__pycache__ +*.pyc + +# Sphinx build-specific files +_build + +# This file results from running `pip -e install .` in a local repository +*.egg-info + +# Virtual environment-specific files +.env +.venv + +# MacOS-specific files +*.DS_Store + +# IDE-specific files +.idea +.vscode +*~ + +# tox-specific files +.tox +build + +# coverage-specific files +.coverage diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 09cc1f1d..fd12dfa0 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,42 +1,42 @@ -# SPDX-FileCopyrightText: 2020 Diego Elio Pettenò -# -# SPDX-License-Identifier: Unlicense - -repos: - - repo: https://github.com/python/black - rev: 24.2.0 - hooks: - - id: black - - repo: https://github.com/fsfe/reuse-tool - rev: v1.1.2 - hooks: - - id: reuse - - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.4.0 - hooks: - - id: check-yaml - - id: end-of-file-fixer - - id: trailing-whitespace - - repo: https://github.com/pycqa/pylint - rev: v2.17.4 - hooks: - - id: pylint - name: pylint (library code) - types: [python] - args: - - --disable=consider-using-f-string - exclude: "^(docs/|examples/|tests/|setup.py$)" - - id: pylint - name: pylint (example code) - description: Run pylint rules on "examples/*.py" files - types: [python] - files: "^examples/" - args: - - --disable=consider-using-f-string,duplicate-code,missing-docstring,invalid-name - - id: pylint - name: pylint (test code) - description: Run pylint rules on "tests/*.py" files - types: [python] - files: "^tests/" - args: - - --disable=consider-using-f-string,duplicate-code,missing-docstring,invalid-name,protected-access +# SPDX-FileCopyrightText: 2020 Diego Elio Pettenò +# +# SPDX-License-Identifier: Unlicense + +repos: + - repo: https://github.com/python/black + rev: 24.2.0 + hooks: + - id: black + - repo: https://github.com/fsfe/reuse-tool + rev: v1.1.2 + hooks: + - id: reuse + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.4.0 + hooks: + - id: check-yaml + - id: end-of-file-fixer + - id: trailing-whitespace + - repo: https://github.com/pycqa/pylint + rev: v2.17.4 + hooks: + - id: pylint + name: pylint (library code) + types: [python] + args: + - --disable=consider-using-f-string + exclude: "^(docs/|examples/|tests/|setup.py$)" + - id: pylint + name: pylint (example code) + description: Run pylint rules on "examples/*.py" files + types: [python] + files: "^examples/" + args: + - --disable=consider-using-f-string,duplicate-code,missing-docstring,invalid-name + - id: pylint + name: pylint (test code) + description: Run pylint rules on "tests/*.py" files + types: [python] + files: "^tests/" + args: + - --disable=consider-using-f-string,duplicate-code,missing-docstring,invalid-name,protected-access diff --git a/.pylintrc b/.pylintrc index f945e920..979f6a75 100644 --- a/.pylintrc +++ b/.pylintrc @@ -1,399 +1,399 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# -# SPDX-License-Identifier: Unlicense - -[MASTER] - -# A comma-separated list of package or module names from where C extensions may -# be loaded. Extensions are loading into the active Python interpreter and may -# run arbitrary code -extension-pkg-whitelist= - -# Add files or directories to the ignore-list. They should be base names, not -# paths. -ignore=CVS - -# Add files or directories matching the regex patterns to the ignore-list. The -# regex matches against base names, not paths. -ignore-patterns= - -# Python code to execute, usually for sys.path manipulation such as -# pygtk.require(). -#init-hook= - -# Use multiple processes to speed up Pylint. -jobs=1 - -# List of plugins (as comma separated values of python modules names) to load, -# usually to register additional checkers. -load-plugins=pylint.extensions.no_self_use - -# Pickle collected data for later comparisons. -persistent=yes - -# Specify a configuration file. -#rcfile= - -# Allow loading of arbitrary C extensions. Extensions are imported into the -# active Python interpreter and may run arbitrary code. -unsafe-load-any-extension=no - - -[MESSAGES CONTROL] - -# Only show warnings with the listed confidence levels. Leave empty to show -# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED -confidence= - -# Disable the message, report, category or checker with the given id(s). You -# can either give multiple identifiers separated by comma (,) or put this -# option multiple times (only on the command line, not in the configuration -# file where it should appear only once).You can also use "--disable=all" to -# disable everything first and then reenable specific checks. For example, if -# you want to run only the similarities checker, you can use "--disable=all -# --enable=similarities". If you want to run only the classes checker, but have -# no Warning level messages displayed, use"--disable=all --enable=classes -# --disable=W" -# disable=import-error,raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,deprecated-str-translate-call -disable=raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,import-error,pointless-string-statement,unspecified-encoding - -# 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 -# multiple time (only on the command line, not in the configuration file where -# it should appear only once). See also the "--disable" option for examples. -enable= - - -[REPORTS] - -# Python expression which should return a note less than 10 (10 is the highest -# note). You have access to the variables errors warning, statement which -# respectively contain the number of errors / warnings messages and the total -# number of statements analyzed. This is used by the global evaluation report -# (RP0004). -evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) - -# Template used to display messages. This is a python new-style format string -# used to format the message information. See doc for all details -#msg-template= - -# Set the output format. Available formats are text, parseable, colorized, json -# and msvs (visual studio).You can also give a reporter class, eg -# mypackage.mymodule.MyReporterClass. -output-format=text - -# Tells whether to display a full report or only the messages -reports=no - -# Activate the evaluation score. -score=yes - - -[REFACTORING] - -# Maximum number of nested blocks for function / method body -max-nested-blocks=5 - - -[LOGGING] - -# Logging modules to check that the string format arguments are in logging -# function parameter format -logging-modules=logging - - -[SPELLING] - -# Spelling dictionary name. Available dictionaries: none. To make it working -# install python-enchant package. -spelling-dict= - -# List of comma separated words that should not be checked. -spelling-ignore-words= - -# A path to a file that contains private dictionary; one word per line. -spelling-private-dict-file= - -# Tells whether to store unknown words to indicated private dictionary in -# --spelling-private-dict-file option instead of raising a message. -spelling-store-unknown-words=no - - -[MISCELLANEOUS] - -# List of note tags to take in consideration, separated by a comma. -# notes=FIXME,XXX,TODO -notes=FIXME,XXX - - -[TYPECHECK] - -# List of decorators that produce context managers, such as -# contextlib.contextmanager. Add to this list to register other decorators that -# produce valid context managers. -contextmanager-decorators=contextlib.contextmanager - -# List of members which are set dynamically and missed by pylint inference -# system, and so shouldn't trigger E1101 when accessed. Python regular -# expressions are accepted. -generated-members= - -# Tells whether missing members accessed in mixin class should be ignored. A -# mixin class is detected if its name ends with "mixin" (case insensitive). -ignore-mixin-members=yes - -# This flag controls whether pylint should warn about no-member and similar -# checks whenever an opaque object is returned when inferring. The inference -# can return multiple potential results while evaluating a Python object, but -# some branches might not be evaluated, which results in partial inference. In -# that case, it might be useful to still emit no-member and other checks for -# the rest of the inferred objects. -ignore-on-opaque-inference=yes - -# List of class names for which member attributes should not be checked (useful -# for classes with dynamically set attributes). This supports the use of -# qualified names. -ignored-classes=optparse.Values,thread._local,_thread._local - -# List of module names for which member attributes should not be checked -# (useful for modules/projects where namespaces are manipulated during runtime -# and thus existing member attributes cannot be deduced by static analysis. It -# supports qualified module names, as well as Unix pattern matching. -ignored-modules=board - -# Show a hint with possible names when a member name was not found. The aspect -# of finding the hint is based on edit distance. -missing-member-hint=yes - -# The minimum edit distance a name should have in order to be considered a -# similar match for a missing member name. -missing-member-hint-distance=1 - -# The total number of similar names that should be taken in consideration when -# showing a hint for a missing member. -missing-member-max-choices=1 - - -[VARIABLES] - -# List of additional names supposed to be defined in builtins. Remember that -# you should avoid to define new builtins when possible. -additional-builtins= - -# Tells whether unused global variables should be treated as a violation. -allow-global-unused-variables=yes - -# List of strings which can identify a callback function by name. A callback -# name must start or end with one of those strings. -callbacks=cb_,_cb - -# A regular expression matching the name of dummy variables (i.e. expectedly -# not used). -dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ - -# Argument names that match this expression will be ignored. Default to name -# with leading underscore -ignored-argument-names=_.*|^ignored_|^unused_ - -# Tells whether we should check for unused import in __init__ files. -init-import=no - -# List of qualified module names which can have objects that can redefine -# builtins. -redefining-builtins-modules=six.moves,future.builtins - - -[FORMAT] - -# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. -# expected-line-ending-format= -expected-line-ending-format=LF - -# Regexp for a line that is allowed to be longer than the limit. -ignore-long-lines=^\s*(# )??$ - -# Number of spaces of indent required inside a hanging or continued line. -indent-after-paren=4 - -# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 -# tab). -indent-string=' ' - -# Maximum number of characters on a single line. -max-line-length=100 - -# Maximum number of lines in a module -max-module-lines=1000 - -# Allow the body of a class to be on the same line as the declaration if body -# contains single statement. -single-line-class-stmt=no - -# Allow the body of an if to be on the same line as the test if there is no -# else. -single-line-if-stmt=no - - -[SIMILARITIES] - -# Ignore comments when computing similarities. -ignore-comments=yes - -# Ignore docstrings when computing similarities. -ignore-docstrings=yes - -# Ignore imports when computing similarities. -ignore-imports=yes - -# Minimum lines number of a similarity. -min-similarity-lines=12 - - -[BASIC] - -# Regular expression matching correct argument names -argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct attribute names -attr-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Bad variable names which should always be refused, separated by a comma -bad-names=foo,bar,baz,toto,tutu,tata - -# Regular expression matching correct class attribute names -class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ - -# Regular expression matching correct class names -# class-rgx=[A-Z_][a-zA-Z0-9]+$ -class-rgx=[A-Z_][a-zA-Z0-9_]+$ - -# Regular expression matching correct constant names -const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ - -# Minimum line length for functions/classes that require docstrings, shorter -# ones are exempt. -docstring-min-length=-1 - -# Regular expression matching correct function names -function-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Good variable names which should always be accepted, separated by a comma -# good-names=i,j,k,ex,Run,_ -good-names=r,g,b,w,i,j,k,n,x,y,z,ex,ok,Run,_ - -# Include a hint for the correct naming format with invalid-name -include-naming-hint=no - -# Regular expression matching correct inline iteration names -inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ - -# Regular expression matching correct method names -method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct module names -module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ - -# Colon-delimited sets of names that determine each other's naming style when -# the name regexes allow several styles. -name-group= - -# Regular expression which should only match function or class names that do -# not require a docstring. -no-docstring-rgx=^_ - -# List of decorators that produce properties, such as abc.abstractproperty. Add -# to this list to register other decorators that produce valid properties. -property-classes=abc.abstractproperty - -# Regular expression matching correct variable names -variable-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - - -[IMPORTS] - -# Allow wildcard imports from modules that define __all__. -allow-wildcard-with-all=no - -# Analyse import fallback blocks. This can be used to support both Python 2 and -# 3 compatible code, which means that the block might have code that exists -# only in one or another interpreter, leading to false positives when analysed. -analyse-fallback-blocks=no - -# Deprecated modules which should not be used, separated by a comma -deprecated-modules=optparse,tkinter.tix - -# Create a graph of external dependencies in the given file (report RP0402 must -# not be disabled) -ext-import-graph= - -# Create a graph of every (i.e. internal and external) dependencies in the -# given file (report RP0402 must not be disabled) -import-graph= - -# Create a graph of internal dependencies in the given file (report RP0402 must -# not be disabled) -int-import-graph= - -# Force import order to recognize a module as part of the standard -# compatibility libraries. -known-standard-library= - -# Force import order to recognize a module as part of a third party library. -known-third-party=enchant - - -[CLASSES] - -# List of method names used to declare (i.e. assign) instance attributes. -defining-attr-methods=__init__,__new__,setUp - -# List of member names, which should be excluded from the protected access -# warning. -exclude-protected=_asdict,_fields,_replace,_source,_make - -# List of valid names for the first argument in a class method. -valid-classmethod-first-arg=cls - -# List of valid names for the first argument in a metaclass class method. -valid-metaclass-classmethod-first-arg=mcs - - -[DESIGN] - -# Maximum number of arguments for function / method -max-args=5 - -# Maximum number of attributes for a class (see R0902). -# max-attributes=7 -max-attributes=11 - -# Maximum number of boolean expressions in a if statement -max-bool-expr=5 - -# Maximum number of branch for function / method body -max-branches=12 - -# Maximum number of locals for function / method body -max-locals=15 - -# Maximum number of parents for a class (see R0901). -max-parents=7 - -# Maximum number of public methods for a class (see R0904). -max-public-methods=20 - -# Maximum number of return / yield for function / method body -max-returns=6 - -# Maximum number of statements in function / method body -max-statements=50 - -# Minimum number of public methods for a class (see R0903). -min-public-methods=1 - - -[EXCEPTIONS] - -# Exceptions that will emit a warning when being caught. Defaults to -# "Exception" -overgeneral-exceptions=builtins.Exception +# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +[MASTER] + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code +extension-pkg-whitelist= + +# Add files or directories to the ignore-list. They should be base names, not +# paths. +ignore=CVS + +# Add files or directories matching the regex patterns to the ignore-list. The +# regex matches against base names, not paths. +ignore-patterns= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Use multiple processes to speed up Pylint. +jobs=1 + +# List of plugins (as comma separated values of python modules names) to load, +# usually to register additional checkers. +load-plugins=pylint.extensions.no_self_use + +# Pickle collected data for later comparisons. +persistent=yes + +# Specify a configuration file. +#rcfile= + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED +confidence= + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once).You can also use "--disable=all" to +# disable everything first and then reenable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use"--disable=all --enable=classes +# --disable=W" +# disable=import-error,raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,deprecated-str-translate-call +disable=raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,import-error,pointless-string-statement,unspecified-encoding + +# 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 +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +enable= + + +[REPORTS] + +# Python expression which should return a note less than 10 (10 is the highest +# note). You have access to the variables errors warning, statement which +# respectively contain the number of errors / warnings messages and the total +# number of statements analyzed. This is used by the global evaluation report +# (RP0004). +evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details +#msg-template= + +# Set the output format. Available formats are text, parseable, colorized, json +# and msvs (visual studio).You can also give a reporter class, eg +# mypackage.mymodule.MyReporterClass. +output-format=text + +# Tells whether to display a full report or only the messages +reports=no + +# Activate the evaluation score. +score=yes + + +[REFACTORING] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + + +[LOGGING] + +# Logging modules to check that the string format arguments are in logging +# function parameter format +logging-modules=logging + + +[SPELLING] + +# Spelling dictionary name. Available dictionaries: none. To make it working +# install python-enchant package. +spelling-dict= + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to indicated private dictionary in +# --spelling-private-dict-file option instead of raising a message. +spelling-store-unknown-words=no + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +# notes=FIXME,XXX,TODO +notes=FIXME,XXX + + +[TYPECHECK] + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# Tells whether missing members accessed in mixin class should be ignored. A +# mixin class is detected if its name ends with "mixin" (case insensitive). +ignore-mixin-members=yes + +# This flag controls whether pylint should warn about no-member and similar +# checks whenever an opaque object is returned when inferring. The inference +# can return multiple potential results while evaluating a Python object, but +# some branches might not be evaluated, which results in partial inference. In +# that case, it might be useful to still emit no-member and other checks for +# the rest of the inferred objects. +ignore-on-opaque-inference=yes + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis. It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules=board + +# Show a hint with possible names when a member name was not found. The aspect +# of finding the hint is based on edit distance. +missing-member-hint=yes + +# The minimum edit distance a name should have in order to be considered a +# similar match for a missing member name. +missing-member-hint-distance=1 + +# The total number of similar names that should be taken in consideration when +# showing a hint for a missing member. +missing-member-max-choices=1 + + +[VARIABLES] + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid to define new builtins when possible. +additional-builtins= + +# Tells whether unused global variables should be treated as a violation. +allow-global-unused-variables=yes + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_,_cb + +# A regular expression matching the name of dummy variables (i.e. expectedly +# not used). +dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ + +# Argument names that match this expression will be ignored. Default to name +# with leading underscore +ignored-argument-names=_.*|^ignored_|^unused_ + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,future.builtins + + +[FORMAT] + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +# expected-line-ending-format= +expected-line-ending-format=LF + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Maximum number of characters on a single line. +max-line-length=100 + +# Maximum number of lines in a module +max-module-lines=1000 + +# Allow the body of a class to be on the same line as the declaration if body +# contains single statement. +single-line-class-stmt=no + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + + +[SIMILARITIES] + +# Ignore comments when computing similarities. +ignore-comments=yes + +# Ignore docstrings when computing similarities. +ignore-docstrings=yes + +# Ignore imports when computing similarities. +ignore-imports=yes + +# Minimum lines number of a similarity. +min-similarity-lines=12 + + +[BASIC] + +# Regular expression matching correct argument names +argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ + +# Regular expression matching correct attribute names +attr-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ + +# Bad variable names which should always be refused, separated by a comma +bad-names=foo,bar,baz,toto,tutu,tata + +# Regular expression matching correct class attribute names +class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ + +# Regular expression matching correct class names +# class-rgx=[A-Z_][a-zA-Z0-9]+$ +class-rgx=[A-Z_][a-zA-Z0-9_]+$ + +# Regular expression matching correct constant names +const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + +# Regular expression matching correct function names +function-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ + +# Good variable names which should always be accepted, separated by a comma +# good-names=i,j,k,ex,Run,_ +good-names=r,g,b,w,i,j,k,n,x,y,z,ex,ok,Run,_ + +# Include a hint for the correct naming format with invalid-name +include-naming-hint=no + +# Regular expression matching correct inline iteration names +inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ + +# Regular expression matching correct method names +method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ + +# Regular expression matching correct module names +module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +property-classes=abc.abstractproperty + +# Regular expression matching correct variable names +variable-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ + + +[IMPORTS] + +# Allow wildcard imports from modules that define __all__. +allow-wildcard-with-all=no + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + +# Deprecated modules which should not be used, separated by a comma +deprecated-modules=optparse,tkinter.tix + +# Create a graph of external dependencies in the given file (report RP0402 must +# not be disabled) +ext-import-graph= + +# Create a graph of every (i.e. internal and external) dependencies in the +# given file (report RP0402 must not be disabled) +import-graph= + +# Create a graph of internal dependencies in the given file (report RP0402 must +# not be disabled) +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + + +[CLASSES] + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__,__new__,setUp + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict,_fields,_replace,_source,_make + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=mcs + + +[DESIGN] + +# Maximum number of arguments for function / method +max-args=5 + +# Maximum number of attributes for a class (see R0902). +# max-attributes=7 +max-attributes=11 + +# Maximum number of boolean expressions in a if statement +max-bool-expr=5 + +# Maximum number of branch for function / method body +max-branches=12 + +# Maximum number of locals for function / method body +max-locals=15 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of return / yield for function / method body +max-returns=6 + +# Maximum number of statements in function / method body +max-statements=50 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=1 + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "Exception" +overgeneral-exceptions=builtins.Exception diff --git a/.readthedocs.yaml b/.readthedocs.yaml index 33c2a610..d01a9db1 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -1,19 +1,19 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# -# SPDX-License-Identifier: Unlicense - -# Read the Docs configuration file -# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details - -# Required -version: 2 - -build: - os: ubuntu-20.04 - tools: - python: "3" - -python: - install: - - requirements: docs/requirements.txt - - requirements: requirements.txt +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +# Read the Docs configuration file +# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details + +# Required +version: 2 + +build: + os: ubuntu-20.04 + tools: + python: "3" + +python: + install: + - requirements: docs/requirements.txt + - requirements: requirements.txt diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 8a55c07c..3115e512 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,135 +1,135 @@ - - -# Adafruit Community Code of Conduct - -## Our Pledge - -In the interest of fostering an open and welcoming environment, we as -contributors and leaders pledge to making participation in our project and -our community a harassment-free experience for everyone, regardless of age, body -size, disability, ethnicity, gender identity and expression, level or type of -experience, education, socio-economic status, nationality, personal appearance, -race, religion, or sexual identity and orientation. - -## Our Standards - -We are committed to providing a friendly, safe and welcoming environment for -all. - -Examples of behavior that contributes to creating a positive environment -include: - -* Be kind and courteous to others -* Using welcoming and inclusive language -* Being respectful of differing viewpoints and experiences -* Collaborating with other community members -* Gracefully accepting constructive criticism -* Focusing on what is best for the community -* Showing empathy towards other community members - -Examples of unacceptable behavior by participants include: - -* The use of sexualized language or imagery and sexual attention or advances -* The use of inappropriate images, including in a community member's avatar -* The use of inappropriate language, including in a community member's nickname -* Any spamming, flaming, baiting or other attention-stealing behavior -* Excessive or unwelcome helping; answering outside the scope of the question - asked -* 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 -* Publishing others' private information, such as a physical or electronic - address, without explicit permission -* Other conduct which could reasonably be considered inappropriate - -The goal of the standards and moderation guidelines outlined here is to build -and maintain a respectful community. We ask that you don’t just aim to be -"technically unimpeachable", but rather try to be your best self. - -We value many things beyond technical expertise, including collaboration and -supporting others within our community. Providing a positive experience for -other community members can have a much more significant impact than simply -providing the correct answer. - -## Our Responsibilities - -Project leaders are responsible for clarifying the standards of acceptable -behavior and are expected to take appropriate and fair corrective action in -response to any instances of unacceptable behavior. - -Project leaders have the right and responsibility to remove, edit, or -reject messages, comments, commits, code, issues, and other contributions -that are not aligned to this Code of Conduct, or to ban temporarily or -permanently any community member for other behaviors that they deem -inappropriate, threatening, offensive, or harmful. - -## Moderation - -Instances of behaviors that violate the Adafruit Community Code of Conduct -may be reported by any member of the community. Community members are -encouraged to report these situations, including situations they witness -involving other community members. - -You may report in the following ways: - -In any situation, you may send an email to . - -On the Adafruit Discord, you may send an open message from any channel -to all Community Moderators by tagging @community moderators. You may -also send an open message from any channel, or a direct message to -@kattni#1507, @tannewt#4653, @Dan Halbert#1614, @cater#2442, -@sommersoft#0222, @Mr. Certainly#0472 or @Andon#8175. - -Email and direct message reports will be kept confidential. - -In situations on Discord where the issue is particularly egregious, possibly -illegal, requires immediate action, or violates the Discord terms of service, -you should also report the message directly to Discord. - -These are the steps for upholding our community’s standards of conduct. - -1. Any member of the community may report any situation that violates the -Adafruit Community Code of Conduct. All reports will be reviewed and -investigated. -2. If the behavior is an egregious violation, the community member who -committed the violation may be banned immediately, without warning. -3. Otherwise, moderators will first respond to such behavior with a warning. -4. Moderators follow a soft "three strikes" policy - the community member may -be given another chance, if they are receptive to the warning and change their -behavior. -5. If the community member is unreceptive or unreasonable when warned by a -moderator, or the warning goes unheeded, they may be banned for a first or -second offense. Repeated offenses will result in the community member being -banned. - -## Scope - -This Code of Conduct and the enforcement policies listed above apply to all -Adafruit Community venues. This includes but is not limited to any community -spaces (both public and private), the entire Adafruit Discord server, and -Adafruit GitHub repositories. Examples of Adafruit Community spaces include -but are not limited to meet-ups, audio chats on the Adafruit Discord, or -interaction at a conference. - -This Code of Conduct applies both within project spaces and in public spaces -when an individual is representing the project or its community. As a community -member, you are representing our community, and are expected to behave -accordingly. - -## Attribution - -This Code of Conduct is adapted from the [Contributor Covenant][homepage], -version 1.4, available at -, -and the [Rust Code of Conduct](https://www.rust-lang.org/en-US/conduct.html). - -For other projects adopting the Adafruit Community Code of -Conduct, please contact the maintainers of those projects for enforcement. -If you wish to use this code of conduct for your own project, consider -explicitly mentioning your moderation policy or making a copy with your -own moderation policy so as to avoid confusion. + + +# Adafruit Community Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and leaders pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level or type of +experience, education, socio-economic status, nationality, personal appearance, +race, religion, or sexual identity and orientation. + +## Our Standards + +We are committed to providing a friendly, safe and welcoming environment for +all. + +Examples of behavior that contributes to creating a positive environment +include: + +* Be kind and courteous to others +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Collaborating with other community members +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and sexual attention or advances +* The use of inappropriate images, including in a community member's avatar +* The use of inappropriate language, including in a community member's nickname +* Any spamming, flaming, baiting or other attention-stealing behavior +* Excessive or unwelcome helping; answering outside the scope of the question + asked +* 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 +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate + +The goal of the standards and moderation guidelines outlined here is to build +and maintain a respectful community. We ask that you don’t just aim to be +"technically unimpeachable", but rather try to be your best self. + +We value many things beyond technical expertise, including collaboration and +supporting others within our community. Providing a positive experience for +other community members can have a much more significant impact than simply +providing the correct answer. + +## Our Responsibilities + +Project leaders are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project leaders have the right and responsibility to remove, edit, or +reject messages, comments, commits, code, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any community member for other behaviors that they deem +inappropriate, threatening, offensive, or harmful. + +## Moderation + +Instances of behaviors that violate the Adafruit Community Code of Conduct +may be reported by any member of the community. Community members are +encouraged to report these situations, including situations they witness +involving other community members. + +You may report in the following ways: + +In any situation, you may send an email to . + +On the Adafruit Discord, you may send an open message from any channel +to all Community Moderators by tagging @community moderators. You may +also send an open message from any channel, or a direct message to +@kattni#1507, @tannewt#4653, @Dan Halbert#1614, @cater#2442, +@sommersoft#0222, @Mr. Certainly#0472 or @Andon#8175. + +Email and direct message reports will be kept confidential. + +In situations on Discord where the issue is particularly egregious, possibly +illegal, requires immediate action, or violates the Discord terms of service, +you should also report the message directly to Discord. + +These are the steps for upholding our community’s standards of conduct. + +1. Any member of the community may report any situation that violates the +Adafruit Community Code of Conduct. All reports will be reviewed and +investigated. +2. If the behavior is an egregious violation, the community member who +committed the violation may be banned immediately, without warning. +3. Otherwise, moderators will first respond to such behavior with a warning. +4. Moderators follow a soft "three strikes" policy - the community member may +be given another chance, if they are receptive to the warning and change their +behavior. +5. If the community member is unreceptive or unreasonable when warned by a +moderator, or the warning goes unheeded, they may be banned for a first or +second offense. Repeated offenses will result in the community member being +banned. + +## Scope + +This Code of Conduct and the enforcement policies listed above apply to all +Adafruit Community venues. This includes but is not limited to any community +spaces (both public and private), the entire Adafruit Discord server, and +Adafruit GitHub repositories. Examples of Adafruit Community spaces include +but are not limited to meet-ups, audio chats on the Adafruit Discord, or +interaction at a conference. + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. As a community +member, you are representing our community, and are expected to behave +accordingly. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 1.4, available at +, +and the [Rust Code of Conduct](https://www.rust-lang.org/en-US/conduct.html). + +For other projects adopting the Adafruit Community Code of +Conduct, please contact the maintainers of those projects for enforcement. +If you wish to use this code of conduct for your own project, consider +explicitly mentioning your moderation policy or making a copy with your +own moderation policy so as to avoid confusion. diff --git a/LICENSE b/LICENSE index 22f6b637..41e76216 100644 --- a/LICENSE +++ b/LICENSE @@ -1,28 +1,28 @@ -The MIT License (MIT) - -Copyright (c) 2019 Brent Rubell for Adafruit Industries - - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - -matcher.py for matching MQTT topics from the Eclipse Paho MQTT Python Client -https://github.com/eclipse/paho.mqtt.python - -Eclipse Paho MQTT Python Client is dual licensed under the Eclipse Public License 1.0 and the -Eclipse Distribution License 1.0 as described in the epl-v10 and edl-v10 files. +The MIT License (MIT) + +Copyright (c) 2019 Brent Rubell for Adafruit Industries + + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +matcher.py for matching MQTT topics from the Eclipse Paho MQTT Python Client +https://github.com/eclipse/paho.mqtt.python + +Eclipse Paho MQTT Python Client is dual licensed under the Eclipse Public License 1.0 and the +Eclipse Distribution License 1.0 as described in the epl-v10 and edl-v10 files. diff --git a/LICENSES/CC-BY-4.0.txt b/LICENSES/CC-BY-4.0.txt index 3f92dfc5..f20d906a 100644 --- a/LICENSES/CC-BY-4.0.txt +++ b/LICENSES/CC-BY-4.0.txt @@ -1,324 +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 -reason–for example, because of any applicable exception or limitation to copyright–then -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. +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 +reason–for example, because of any applicable exception or limitation to copyright–then +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. diff --git a/LICENSES/EPL-1.0.txt b/LICENSES/EPL-1.0.txt index 390b01f7..4623c3de 100644 --- a/LICENSES/EPL-1.0.txt +++ b/LICENSES/EPL-1.0.txt @@ -1,58 +1,58 @@ -Eclipse Public License - v 1.0 - -THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. - -1. DEFINITIONS -"Contribution" means: -a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and -b) in the case of each subsequent Contributor: -i) changes to the Program, and -ii) additions to the Program; -where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program. - -"Contributor" means any person or entity that distributes the Program. - -"Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. - -"Program" means the Contributions distributed in accordance with this Agreement. - -"Recipient" means anyone who receives the Program under this Agreement, including all Contributors. - -2. GRANT OF RIGHTS -a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form. -b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. -c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. -d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. -3. REQUIREMENTS -A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: -a) it complies with the terms and conditions of this Agreement; and -b) its license agreement: -i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; -ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; -iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and -iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. -When the Program is made available in source code form: - -a) it must be made available under this Agreement; and -b) a copy of this Agreement must be included with each copy of the Program. -Contributors may not remove or alter any copyright notices contained within the Program. -Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution. - -4. COMMERCIAL DISTRIBUTION -Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. -For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. - -5. NO WARRANTY -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement, including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. -6. DISCLAIMER OF LIABILITY -EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. -7. GENERAL -If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. - -If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. - -All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. - -Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. - -This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation. +Eclipse Public License - v 1.0 + +THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. + +1. DEFINITIONS +"Contribution" means: +a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and +b) in the case of each subsequent Contributor: +i) changes to the Program, and +ii) additions to the Program; +where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program. + +"Contributor" means any person or entity that distributes the Program. + +"Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. + +"Program" means the Contributions distributed in accordance with this Agreement. + +"Recipient" means anyone who receives the Program under this Agreement, including all Contributors. + +2. GRANT OF RIGHTS +a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form. +b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. +c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. +d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. +3. REQUIREMENTS +A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: +a) it complies with the terms and conditions of this Agreement; and +b) its license agreement: +i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; +ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; +iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and +iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. +When the Program is made available in source code form: + +a) it must be made available under this Agreement; and +b) a copy of this Agreement must be included with each copy of the Program. +Contributors may not remove or alter any copyright notices contained within the Program. +Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution. + +4. COMMERCIAL DISTRIBUTION +Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. +For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. + +5. NO WARRANTY +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement, including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. +6. DISCLAIMER OF LIABILITY +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. +7. GENERAL +If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. + +If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. + +All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. + +Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. + +This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation. diff --git a/LICENSES/MIT.txt b/LICENSES/MIT.txt index 204b93da..ad8c23c8 100644 --- a/LICENSES/MIT.txt +++ b/LICENSES/MIT.txt @@ -1,19 +1,19 @@ -MIT License Copyright (c) - -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. +MIT License Copyright (c) + +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. diff --git a/LICENSES/Unlicense.txt b/LICENSES/Unlicense.txt index 24a8f901..c8a1c8a4 100644 --- a/LICENSES/Unlicense.txt +++ b/LICENSES/Unlicense.txt @@ -1,20 +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 +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 diff --git a/README.rst b/README.rst index f5fcd464..c1df70c4 100644 --- a/README.rst +++ b/README.rst @@ -1,75 +1,75 @@ -Introduction -============ - -.. image:: https://readthedocs.org/projects/adafruit-circuitpython-minimqtt/badge/?version=latest - :target: https://docs.circuitpython.org/projects/minimqtt/en/latest/ - :alt: Documentation Status - -.. image:: https://raw.githubusercontent.com/adafruit/Adafruit_CircuitPython_Bundle/main/badges/adafruit_discord.svg - :target: https://adafru.it/discord - :alt: Discord - -.. image:: https://github.com/adafruit/Adafruit_CircuitPython_MiniMQTT/workflows/Build%20CI/badge.svg - :target: https://github.com/adafruit/Adafruit_CircuitPython_MiniMQTT/actions/ - :alt: Build Status - -.. image:: https://img.shields.io/badge/code%20style-black-000000.svg - :target: https://github.com/psf/black - :alt: Code Style: Black - -MQTT Client library for CircuitPython. - -Dependencies -============= -This driver depends on: - -* `Adafruit CircuitPython `_ -* `Adafruit CircuitPython ConnectionManager `_ - -Please ensure all dependencies are available on the CircuitPython filesystem. -This is easily achieved by downloading -`the Adafruit library and driver bundle `_. - -Installing from PyPI -===================== -On supported GNU/Linux systems like the Raspberry Pi, you can install the driver locally `from -PyPI `_. To install for current user: - -.. code-block:: shell - - pip3 install adafruit-circuitpython-minimqtt - -To install system-wide (this may be required in some cases): - -.. code-block:: shell - - sudo pip3 install adafruit-circuitpython-minimqtt - -To install in a virtual environment in your current project: - -.. code-block:: shell - - mkdir project-name && cd project-name - python3 -m venv .venv - source .venv/bin/activate - pip3 install adafruit-circuitpython-minimqtt - -Usage Example -============= - -Please check the `examples folder `_ -for usage examples for this library. - -Documentation -============= - -API documentation for this library can be found on `Read the Docs `_. - -For information on building library documentation, please check out `this guide `_. - -Contributing -============ - -Contributions are welcome! Please read our `Code of Conduct -`_ -before contributing to help this project stay welcoming. +Introduction +============ + +.. image:: https://readthedocs.org/projects/adafruit-circuitpython-minimqtt/badge/?version=latest + :target: https://docs.circuitpython.org/projects/minimqtt/en/latest/ + :alt: Documentation Status + +.. image:: https://raw.githubusercontent.com/adafruit/Adafruit_CircuitPython_Bundle/main/badges/adafruit_discord.svg + :target: https://adafru.it/discord + :alt: Discord + +.. image:: https://github.com/adafruit/Adafruit_CircuitPython_MiniMQTT/workflows/Build%20CI/badge.svg + :target: https://github.com/adafruit/Adafruit_CircuitPython_MiniMQTT/actions/ + :alt: Build Status + +.. image:: https://img.shields.io/badge/code%20style-black-000000.svg + :target: https://github.com/psf/black + :alt: Code Style: Black + +MQTT Client library for CircuitPython. + +Dependencies +============= +This driver depends on: + +* `Adafruit CircuitPython `_ +* `Adafruit CircuitPython ConnectionManager `_ + +Please ensure all dependencies are available on the CircuitPython filesystem. +This is easily achieved by downloading +`the Adafruit library and driver bundle `_. + +Installing from PyPI +===================== +On supported GNU/Linux systems like the Raspberry Pi, you can install the driver locally `from +PyPI `_. To install for current user: + +.. code-block:: shell + + pip3 install adafruit-circuitpython-minimqtt + +To install system-wide (this may be required in some cases): + +.. code-block:: shell + + sudo pip3 install adafruit-circuitpython-minimqtt + +To install in a virtual environment in your current project: + +.. code-block:: shell + + mkdir project-name && cd project-name + python3 -m venv .venv + source .venv/bin/activate + pip3 install adafruit-circuitpython-minimqtt + +Usage Example +============= + +Please check the `examples folder `_ +for usage examples for this library. + +Documentation +============= + +API documentation for this library can be found on `Read the Docs `_. + +For information on building library documentation, please check out `this guide `_. + +Contributing +============ + +Contributions are welcome! Please read our `Code of Conduct +`_ +before contributing to help this project stay welcoming. diff --git a/README.rst.license b/README.rst.license index 11cd75d3..e68061f9 100644 --- a/README.rst.license +++ b/README.rst.license @@ -1,3 +1,3 @@ -SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries - -SPDX-License-Identifier: MIT +SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries + +SPDX-License-Identifier: MIT diff --git a/adafruit_minimqtt/adafruit_minimqtt.py b/adafruit_minimqtt/adafruit_minimqtt.py index 3bc018d0..7750de7e 100644 --- a/adafruit_minimqtt/adafruit_minimqtt.py +++ b/adafruit_minimqtt/adafruit_minimqtt.py @@ -1,1150 +1,1152 @@ -# SPDX-FileCopyrightText: 2019-2021 Brent Rubell for Adafruit Industries -# -# SPDX-License-Identifier: MIT - -# Original Work Copyright (c) 2016 Paul Sokolovsky, uMQTT -# Modified Work Copyright (c) 2019 Bradley Beach, esp32spi_mqtt -# Modified Work Copyright (c) 2012-2019 Roger Light and others, Paho MQTT Python - -# pylint: disable=too-many-lines - -""" -`adafruit_minimqtt` -================================================================================ - -A minimal MQTT Library for CircuitPython. - -* Author(s): Brent Rubell - -Implementation Notes --------------------- - -Adapted from https://github.com/micropython/micropython-lib/tree/master/umqtt.simple/umqtt - -**Software and Dependencies:** - -* Adafruit CircuitPython firmware for the supported boards: - https://github.com/adafruit/circuitpython/releases - -* Adafruit's Connection Manager library: - https://github.com/adafruit/Adafruit_CircuitPython_ConnectionManager - -""" -import errno -import struct -import time -from random import randint - -from adafruit_connection_manager import get_connection_manager -from adafruit_ticks import ticks_ms, ticks_diff - -try: - from typing import List, Optional, Tuple, Type, Union -except ImportError: - pass - -try: - from types import TracebackType -except ImportError: - pass - -from micropython import const - -from .matcher import MQTTMatcher - -__version__ = "0.0.0+auto.0" -__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_MiniMQTT.git" - -# Client-specific variables -MQTT_MSG_MAX_SZ = const(268435455) -MQTT_MSG_SZ_LIM = const(10000000) -MQTT_TOPIC_LENGTH_LIMIT = const(65535) -MQTT_TCP_PORT = const(1883) -MQTT_TLS_PORT = const(8883) - -# MQTT Commands -MQTT_PINGREQ = b"\xc0\0" -MQTT_PINGRESP = const(0xD0) -MQTT_PUBLISH = const(0x30) -MQTT_SUB = const(0x82) -MQTT_UNSUB = const(0xA2) -MQTT_DISCONNECT = b"\xe0\0" - -MQTT_PKT_TYPE_MASK = const(0xF0) - - -CONNACK_ERRORS = { - const(0x01): "Connection Refused - Incorrect Protocol Version", - const(0x02): "Connection Refused - ID Rejected", - const(0x03): "Connection Refused - Server unavailable", - const(0x04): "Connection Refused - Incorrect username/password", - const(0x05): "Connection Refused - Unauthorized", -} - -_default_sock = None # pylint: disable=invalid-name -_fake_context = None # pylint: disable=invalid-name - - -class MMQTTException(Exception): - """MiniMQTT Exception class.""" - - -class NullLogger: - """Fake logger class that does not do anything""" - - # pylint: disable=unused-argument - def nothing(self, msg: str, *args) -> None: - """no action""" - - def __init__(self) -> None: - for log_level in ["debug", "info", "warning", "error", "critical"]: - setattr(NullLogger, log_level, self.nothing) - - -class MQTT: - """MQTT Client for CircuitPython. - - :param str broker: MQTT Broker URL or IP Address. - :param int port: Optional port definition, defaults to MQTT_TLS_PORT if is_ssl is True, - MQTT_TCP_PORT otherwise. - :param str username: Username for broker authentication. - :param str password: Password for broker authentication. - :param str client_id: Optional client identifier, defaults to a unique, generated string. - :param bool is_ssl: Sets a secure or insecure connection with the broker. - :param int keep_alive: KeepAlive interval between the broker and the MiniMQTT client. - :param int recv_timeout: receive timeout, in seconds. - :param socket socket_pool: A pool of socket resources available for the given radio. - :param ssl_context: SSL context for long-lived SSL connections. - :param bool use_binary_mode: Messages are passed as bytearray instead of string to callbacks. - :param int socket_timeout: How often to check socket state for read/write/connect operations, - in seconds. - :param int connect_retries: How many times to try to connect to the broker before giving up - on connect or reconnect. Exponential backoff will be used for the retries. - :param class user_data: arbitrary data to pass as a second argument to most of the callbacks. - This works with all callbacks but the "on_message" and those added via add_topic_callback(); - for those, to get access to the user_data use the 'user_data' member of the MQTT object - passed as 1st argument. - - """ - - # pylint: disable=too-many-arguments,too-many-instance-attributes,too-many-statements,not-callable,invalid-name,no-member,too-many-locals - def __init__( - self, - *, - broker: str, - port: Optional[int] = None, - username: Optional[str] = None, - password: Optional[str] = None, - client_id: Optional[str] = None, - is_ssl: Optional[bool] = None, - keep_alive: int = 60, - recv_timeout: int = 10, - socket_pool=None, - ssl_context=None, - use_binary_mode: bool = False, - socket_timeout: int = 1, - connect_retries: int = 5, - user_data=None, - ) -> None: - self._connection_manager = get_connection_manager(socket_pool) - self._socket_pool = socket_pool - self._ssl_context = ssl_context - self._sock = None - self._backwards_compatible_sock = False - self._use_binary_mode = use_binary_mode - - if recv_timeout <= socket_timeout: - raise MMQTTException( - "recv_timeout must be strictly greater than socket_timeout" - ) - self._socket_timeout = socket_timeout - self._recv_timeout = recv_timeout - - self.keep_alive = keep_alive - self.user_data = user_data - self._is_connected = False - self._msg_size_lim = MQTT_MSG_SZ_LIM - self._pid = 0 - self._last_msg_sent_timestamp: int = 0 - self.logger = NullLogger() - """An optional logging attribute that can be set with with a Logger - to enable debug logging.""" - - self._reconnect_attempt = 0 - self._reconnect_timeout = float(0) - self._reconnect_maximum_backoff = 32 - if connect_retries <= 0: - raise MMQTTException("connect_retries must be positive") - self._reconnect_attempts_max = connect_retries - - self.broker = broker - self._username = username - self._password = password - if ( - self._password and len(password.encode("utf-8")) > MQTT_TOPIC_LENGTH_LIMIT - ): # [MQTT-3.1.3.5] - raise MMQTTException("Password length is too large.") - - # The connection will be insecure unless is_ssl is set to True. - # If the port is not specified, the security will be set based on the is_ssl parameter. - # If the port is specified, the is_ssl parameter will be honored. - self.port = MQTT_TCP_PORT - if is_ssl is None: - is_ssl = False - self._is_ssl = is_ssl - if self._is_ssl: - self.port = MQTT_TLS_PORT - if port: - self.port = port - - # define client identifier - if client_id: - # user-defined client_id MAY allow client_id's > 23 bytes or - # non-alpha-numeric characters - self.client_id = client_id - else: - # assign a unique client_id - time_int = int(ticks_ms() / 10) % 1000 - self.client_id = f"cpy{randint(0, time_int)}{randint(0, 99)}" - # generated client_id's enforce spec.'s length rules - if len(self.client_id.encode("utf-8")) > 23 or not self.client_id: - raise ValueError("MQTT Client ID must be between 1 and 23 bytes") - - # LWT - self._lw_topic = None - self._lw_qos = 0 - self._lw_msg = None - self._lw_retain = False - - # List of subscribed topics, used for tracking - self._subscribed_topics: List[str] = [] - self._on_message_filtered = MQTTMatcher() - - # Default topic callback methods - self._on_message = None - self.on_connect = None - self.on_disconnect = None - self.on_publish = None - self.on_subscribe = None - self.on_unsubscribe = None - - def __enter__(self): - return self - - def __exit__( - self, - exception_type: Optional[Type[BaseException]], - exception_value: Optional[BaseException], - traceback: Optional[TracebackType], - ) -> None: - self.deinit() - - def deinit(self) -> None: - """De-initializes the MQTT client and disconnects from the mqtt broker.""" - self.disconnect() - - @property - def mqtt_msg(self) -> Tuple[int, int]: - """Returns maximum MQTT payload and topic size.""" - return self._msg_size_lim, MQTT_TOPIC_LENGTH_LIMIT - - @mqtt_msg.setter - def mqtt_msg(self, msg_size: int) -> None: - """Sets the maximum MQTT message payload size. - - :param int msg_size: Maximum MQTT payload size. - """ - if msg_size < MQTT_MSG_MAX_SZ: - self._msg_size_lim = msg_size - - def will_set( - self, - topic: Optional[str] = None, - payload: Optional[Union[int, float, str]] = None, - qos: int = 0, - retain: bool = False, - ) -> None: - """Sets the last will and testament properties. MUST be called before `connect()`. - - :param str topic: MQTT Broker topic. - :param int|float|str payload: Last will disconnection payload. - payloads of type int & float are converted to a string. - :param int qos: Quality of Service level, defaults to - zero. Conventional options are ``0`` (send at most once), ``1`` - (send at least once), or ``2`` (send exactly once). - - .. note:: Only options ``1`` or ``0`` are QoS levels supported by this library. - :param bool retain: Specifies if the payload is to be retained when - it is published. - """ - self.logger.debug("Setting last will properties") - self._valid_qos(qos) - if self._is_connected: - raise MMQTTException("Last Will should only be called before connect().") - if payload is None: - payload = "" - if isinstance(payload, (int, float, str)): - payload = str(payload).encode() - else: - raise MMQTTException("Invalid message data type.") - self._lw_qos = qos - self._lw_topic = topic - self._lw_msg = payload - self._lw_retain = retain - - def add_topic_callback(self, mqtt_topic: str, callback_method) -> None: - """Registers a callback_method for a specific MQTT topic. - - :param str mqtt_topic: MQTT topic identifier. - :param function callback_method: The callback method. - - Expected method signature is ``on_message(client, topic, message)`` - To get access to the user_data, use the client argument. - - If a callback is called for the topic, then any "on_message" callback will not be called. - """ - if mqtt_topic is None or callback_method is None: - raise ValueError("MQTT topic and callback method must both be defined.") - self._on_message_filtered[mqtt_topic] = callback_method - - def remove_topic_callback(self, mqtt_topic: str) -> None: - """Removes a registered callback method. - - :param str mqtt_topic: MQTT topic identifier string. - """ - if mqtt_topic is None: - raise ValueError("MQTT Topic must be defined.") - try: - del self._on_message_filtered[mqtt_topic] - except KeyError: - raise KeyError( - "MQTT topic callback not added with add_topic_callback." - ) from None - - @property - def on_message(self): - """Called when a new message has been received on a subscribed topic. - - Expected method signature is ``on_message(client, topic, message)`` - To get access to the user_data, use the client argument. - """ - return self._on_message - - @on_message.setter - def on_message(self, method) -> None: - self._on_message = method - - def _handle_on_message(self, topic: str, message: str): - matched = False - if topic is not None: - for callback in self._on_message_filtered.iter_match(topic): - callback(self, topic, message) # on_msg with callback - matched = True - - if not matched and self.on_message: # regular on_message - self.on_message(self, topic, message) - - def username_pw_set(self, username: str, password: Optional[str] = None) -> None: - """Set client's username and an optional password. - - :param str username: Username to use with your MQTT broker. - :param str password: Password to use with your MQTT broker. - - """ - if self._is_connected: - raise MMQTTException("This method must be called before connect().") - self._username = username - if password is not None: - self._password = password - - def connect( - self, - clean_session: bool = True, - host: Optional[str] = None, - port: Optional[int] = None, - keep_alive: Optional[int] = None, - ) -> int: - """Initiates connection with the MQTT Broker. Will perform exponential back-off - on connect failures. - - :param bool clean_session: Establishes a persistent session. - :param str host: Hostname or IP address of the remote broker. - :param int port: Network port of the remote broker. - :param int keep_alive: Maximum period allowed for communication - within single connection attempt, in seconds. - - """ - - last_exception = None - backoff = False - for i in range(0, self._reconnect_attempts_max): - if i > 0: - if backoff: - self._recompute_reconnect_backoff() - else: - self._reset_reconnect_backoff() - - self.logger.debug( - f"Attempting to connect to MQTT broker (attempt #{self._reconnect_attempt})" - ) - - try: - ret = self._connect( - clean_session=clean_session, - host=host, - port=port, - keep_alive=keep_alive, - ) - self._reset_reconnect_backoff() - return ret - except RuntimeError as e: - self.logger.warning(f"Socket error when connecting: {e}") - backoff = False - except MMQTTException as e: - last_exception = e - self.logger.info(f"MMQT error: {e}") - backoff = True - - if self._reconnect_attempts_max > 1: - exc_msg = "Repeated connect failures" - else: - exc_msg = "Connect failure" - if last_exception: - raise MMQTTException(exc_msg) from last_exception - - raise MMQTTException(exc_msg) - - # pylint: disable=too-many-branches, too-many-statements, too-many-locals - def _connect( - self, - clean_session: bool = True, - host: Optional[str] = None, - port: Optional[int] = None, - keep_alive: Optional[int] = None, - ) -> int: - """Initiates connection with the MQTT Broker. - - :param bool clean_session: Establishes a persistent session. - :param str host: Hostname or IP address of the remote broker. - :param int port: Network port of the remote broker. - :param int keep_alive: Maximum period allowed for communication, in seconds. - - """ - if host: - self.broker = host - if port: - self.port = port - if keep_alive: - self.keep_alive = keep_alive - - self.logger.debug("Attempting to establish MQTT connection...") - - if self._reconnect_attempt > 0: - self.logger.debug( - f"Sleeping for {self._reconnect_timeout:.3} seconds due to connect back-off" - ) - time.sleep(self._reconnect_timeout) - - # Get a new socket - self._sock = self._connection_manager.get_socket( - self.broker, - self.port, - proto="mqtt:", - timeout=self._socket_timeout, - is_ssl=self._is_ssl, - ssl_context=self._ssl_context, - ) - self._backwards_compatible_sock = not hasattr(self._sock, "recv_into") - - fixed_header = bytearray([0x10]) - - # Variable CONNECT header [MQTT 3.1.2] - # The byte array is used as a template. - var_header = bytearray(b"\x00\x04MQTT\x04\x02\0\0") - var_header[7] = clean_session << 1 - - # Set up variable header and remaining_length - remaining_length = 12 + len(self.client_id.encode("utf-8")) - if self._username is not None: - remaining_length += ( - 2 - + len(self._username.encode("utf-8")) - + 2 - + len(self._password.encode("utf-8")) - ) - var_header[7] |= 0xC0 - if self.keep_alive: - assert self.keep_alive < MQTT_TOPIC_LENGTH_LIMIT - var_header[8] |= self.keep_alive >> 8 - var_header[9] |= self.keep_alive & 0x00FF - if self._lw_topic: - remaining_length += ( - 2 + len(self._lw_topic.encode("utf-8")) + 2 + len(self._lw_msg) - ) - var_header[7] |= 0x4 | (self._lw_qos & 0x1) << 3 | (self._lw_qos & 0x2) << 3 - var_header[7] |= self._lw_retain << 5 - - self._encode_remaining_length(fixed_header, remaining_length) - self.logger.debug("Sending CONNECT to broker...") - self.logger.debug(f"Fixed Header: {fixed_header}") - self.logger.debug(f"Variable Header: {var_header}") - self._sock.send(fixed_header) - self._sock.send(var_header) - # [MQTT-3.1.3-4] - self._send_str(self.client_id) - if self._lw_topic: - # [MQTT-3.1.3-11] - self._send_str(self._lw_topic) - self._send_str(self._lw_msg) - if self._username is not None: - self._send_str(self._username) - self._send_str(self._password) - self._last_msg_sent_timestamp = ticks_ms() - self.logger.debug("Receiving CONNACK packet from broker") - stamp = ticks_ms() - while True: - op = self._wait_for_msg() - if op == 32: - rc = self._sock_exact_recv(3) - assert rc[0] == 0x02 - if rc[2] != 0x00: - raise MMQTTException(CONNACK_ERRORS[rc[2]]) - self._is_connected = True - result = rc[0] & 1 - if self.on_connect is not None: - self.on_connect(self, self.user_data, result, rc[2]) - - return result - - if op is None: - if ticks_diff(ticks_ms(), stamp) / 1000 > self._recv_timeout: - raise MMQTTException( - f"No data received from broker for {self._recv_timeout} seconds." - ) - - # pylint: disable=no-self-use - def _encode_remaining_length( - self, fixed_header: bytearray, remaining_length: int - ) -> None: - """Encode Remaining Length [2.2.3]""" - if remaining_length > 268_435_455: - raise MMQTTException("invalid remaining length") - - # Remaining length calculation - if remaining_length > 0x7F: - while remaining_length > 0: - encoded_byte = remaining_length % 0x80 - remaining_length = remaining_length // 0x80 - # if there is more data to encode, set the top bit of the byte - if remaining_length > 0: - encoded_byte |= 0x80 - fixed_header.append(encoded_byte) - else: - fixed_header.append(remaining_length) - - def disconnect(self) -> None: - """Disconnects the MiniMQTT client from the MQTT broker.""" - self._connected() - self.logger.debug("Sending DISCONNECT packet to broker") - try: - self._sock.send(MQTT_DISCONNECT) - except RuntimeError as e: - self.logger.warning(f"Unable to send DISCONNECT packet: {e}") - self.logger.debug("Closing socket") - self._connection_manager.close_socket(self._sock) - self._is_connected = False - self._subscribed_topics = [] - self._last_msg_sent_timestamp = 0 - if self.on_disconnect is not None: - self.on_disconnect(self, self.user_data, 0) - - def ping(self) -> list[int]: - """Pings the MQTT Broker to confirm if the broker is alive or if - there is an active network connection. - Returns packet types of any messages received while waiting for PINGRESP. - """ - self._connected() - self.logger.debug("Sending PINGREQ") - self._sock.send(MQTT_PINGREQ) - ping_timeout = self.keep_alive - stamp = ticks_ms() - self._last_msg_sent_timestamp = stamp - rc, rcs = None, [] - while rc != MQTT_PINGRESP: - rc = self._wait_for_msg() - if rc: - rcs.append(rc) - if ticks_diff(ticks_ms(), stamp) / 1000 > ping_timeout: - raise MMQTTException(f"PINGRESP not returned from broker within {ping_timeout} seconds.") - return rcs - - # pylint: disable=too-many-branches, too-many-statements - def publish( - self, - topic: str, - msg: Union[str, int, float, bytes], - retain: bool = False, - qos: int = 0, - ) -> None: - """Publishes a message to a topic provided. - - :param str topic: Unique topic identifier. - :param str|int|float|bytes msg: Data to send to the broker. - :param bool retain: Whether the message is saved by the broker. - :param int qos: Quality of Service level for the message, defaults to zero. - - """ - self._connected() - self._valid_topic(topic) - if "+" in topic or "#" in topic: - raise MMQTTException("Publish topic can not contain wildcards.") - # check msg/qos kwargs - if msg is None: - raise MMQTTException("Message can not be None.") - if isinstance(msg, (int, float)): - msg = str(msg).encode("ascii") - elif isinstance(msg, str): - msg = str(msg).encode("utf-8") - elif isinstance(msg, bytes): - pass - else: - raise MMQTTException("Invalid message data type.") - if len(msg) > MQTT_MSG_MAX_SZ: - raise MMQTTException(f"Message size larger than {MQTT_MSG_MAX_SZ} bytes.") - assert ( - 0 <= qos <= 1 - ), "Quality of Service Level 2 is unsupported by this library." - - # fixed header. [3.3.1.2], [3.3.1.3] - pub_hdr_fixed = bytearray([MQTT_PUBLISH | retain | qos << 1]) - - # variable header = 2-byte Topic length (big endian) - pub_hdr_var = bytearray(struct.pack(">H", len(topic.encode("utf-8")))) - pub_hdr_var.extend(topic.encode("utf-8")) # Topic name - - remaining_length = 2 + len(msg) + len(topic.encode("utf-8")) - if qos > 0: - # packet identifier where QoS level is 1 or 2. [3.3.2.2] - remaining_length += 2 - self._pid = self._pid + 1 if self._pid < 0xFFFF else 1 - pub_hdr_var.append(self._pid >> 8) - pub_hdr_var.append(self._pid & 0xFF) - - self._encode_remaining_length(pub_hdr_fixed, remaining_length) - - self.logger.debug( - "Sending PUBLISH\nTopic: %s\nMsg: %s\ - \nQoS: %d\nRetain? %r", - topic, - msg, - qos, - retain, - ) - self._sock.send(pub_hdr_fixed) - self._sock.send(pub_hdr_var) - self._sock.send(msg) - self._last_msg_sent_timestamp = ticks_ms() - if qos == 0 and self.on_publish is not None: - self.on_publish(self, self.user_data, topic, self._pid) - if qos == 1: - stamp = ticks_ms() - while True: - op = self._wait_for_msg() - if op == 0x40: - sz = self._sock_exact_recv(1) - assert sz == b"\x02" - rcv_pid_buf = self._sock_exact_recv(2) - rcv_pid = rcv_pid_buf[0] << 0x08 | rcv_pid_buf[1] - if self._pid == rcv_pid: - if self.on_publish is not None: - self.on_publish(self, self.user_data, topic, rcv_pid) - return - - if op is None: - if ticks_diff(ticks_ms(), stamp) / 1000 > self._recv_timeout: - raise MMQTTException( - f"No data received from broker for {self._recv_timeout} seconds." - ) - - def subscribe(self, topic: Optional[Union[tuple, str, list]], qos: int = 0) -> None: - """Subscribes to a topic on the MQTT Broker. - This method can subscribe to one topic or multiple topics. - - :param str|tuple|list topic: Unique MQTT topic identifier string. If - this is a `tuple`, then the tuple should - contain topic identifier string and qos - level integer. If this is a `list`, then - each list element should be a tuple containing - a topic identifier string and qos level integer. - :param int qos: Quality of Service level for the topic, defaults to - zero. Conventional options are ``0`` (send at most once), ``1`` - (send at least once), or ``2`` (send exactly once). - - """ - self._connected() - topics = None - if isinstance(topic, tuple): - topic, qos = topic - self._valid_topic(topic) - self._valid_qos(qos) - if isinstance(topic, str): - self._valid_topic(topic) - self._valid_qos(qos) - topics = [(topic, qos)] - if isinstance(topic, list): - topics = [] - for t, q in topic: - self._valid_qos(q) - self._valid_topic(t) - topics.append((t, q)) - # Assemble packet - self.logger.debug("Sending SUBSCRIBE to broker...") - fixed_header = bytearray([MQTT_SUB]) - packet_length = 2 + (2 * len(topics)) + (1 * len(topics)) - packet_length += sum(len(topic.encode("utf-8")) for topic, qos in topics) - self._encode_remaining_length(fixed_header, remaining_length=packet_length) - self.logger.debug(f"Fixed Header: {fixed_header}") - self._sock.send(fixed_header) - self._pid = self._pid + 1 if self._pid < 0xFFFF else 1 - packet_id_bytes = self._pid.to_bytes(2, "big") - var_header = packet_id_bytes - self.logger.debug(f"Variable Header: {var_header}") - self._sock.send(var_header) - # attaching topic and QOS level to the packet - payload = bytes() - for t, q in topics: - topic_size = len(t.encode("utf-8")).to_bytes(2, "big") - qos_byte = q.to_bytes(1, "big") - payload += topic_size + t.encode() + qos_byte - for t, q in topics: - self.logger.debug(f"SUBSCRIBING to topic {t} with QoS {q}") - self.logger.debug(f"payload: {payload}") - self._sock.send(payload) - stamp = ticks_ms() - self._last_msg_sent_timestamp = stamp - while True: - op = self._wait_for_msg() - if op is None: - if ticks_diff(ticks_ms(), stamp) / 1000 > self._recv_timeout: - raise MMQTTException( - f"No data received from broker for {self._recv_timeout} seconds." - ) - else: - if op == 0x90: - remaining_len = self._decode_remaining_length() - assert remaining_len > 0 - rc = self._sock_exact_recv(2) - # Check packet identifier. - assert rc[0] == var_header[0] and rc[1] == var_header[1] - rc = self._sock_exact_recv(remaining_len - 2) - for i in range(0, remaining_len - 2): - if rc[i] not in [0, 1, 2]: - raise MMQTTException( - f"SUBACK Failure for topic {topics[i][0]}: {hex(rc[i])}" - ) - - for t, q in topics: - if self.on_subscribe is not None: - self.on_subscribe(self, self.user_data, t, q) - self._subscribed_topics.append(t) - - return - - if op != MQTT_PUBLISH: - # [3.8.4] The Server is permitted to start sending PUBLISH packets - # matching the Subscription before the Server sends the SUBACK Packet. - raise MMQTTException( - f"invalid message received as response to SUBSCRIBE: {hex(op)}" - ) - - def unsubscribe(self, topic: Optional[Union[str, list]]) -> None: - """Unsubscribes from a MQTT topic. - - :param str|list topic: Unique MQTT topic identifier string or list. - - """ - topics = None - if isinstance(topic, str): - self._valid_topic(topic) - topics = [(topic)] - if isinstance(topic, list): - topics = [] - for t in topic: - self._valid_topic(t) - topics.append((t)) - for t in topics: - if t not in self._subscribed_topics: - raise MMQTTException( - "Topic must be subscribed to before attempting unsubscribe." - ) - # Assemble packet - self.logger.debug("Sending UNSUBSCRIBE to broker...") - fixed_header = bytearray([MQTT_UNSUB]) - packet_length = 2 + (2 * len(topics)) - packet_length += sum(len(topic.encode("utf-8")) for topic in topics) - self._encode_remaining_length(fixed_header, remaining_length=packet_length) - self.logger.debug(f"Fixed Header: {fixed_header}") - self._sock.send(fixed_header) - self._pid = self._pid + 1 if self._pid < 0xFFFF else 1 - packet_id_bytes = self._pid.to_bytes(2, "big") - var_header = packet_id_bytes - self.logger.debug(f"Variable Header: {var_header}") - self._sock.send(var_header) - payload = bytes() - for t in topics: - topic_size = len(t.encode("utf-8")).to_bytes(2, "big") - payload += topic_size + t.encode() - for t in topics: - self.logger.debug(f"UNSUBSCRIBING from topic {t}") - self._sock.send(payload) - self._last_msg_sent_timestamp = ticks_ms() - self.logger.debug("Waiting for UNSUBACK...") - while True: - stamp = ticks_ms() - op = self._wait_for_msg() - if op is None: - if ticks_diff(ticks_ms(), stamp) / 1000 > self._recv_timeout: - raise MMQTTException( - f"No data received from broker for {self._recv_timeout} seconds." - ) - else: - if op == 176: - rc = self._sock_exact_recv(3) - assert rc[0] == 0x02 - # [MQTT-3.32] - assert rc[1] == packet_id_bytes[0] and rc[2] == packet_id_bytes[1] - for t in topics: - if self.on_unsubscribe is not None: - self.on_unsubscribe(self, self.user_data, t, self._pid) - self._subscribed_topics.remove(t) - return - - raise MMQTTException( - f"invalid message received as response to UNSUBSCRIBE: {hex(op)}" - ) - - def _recompute_reconnect_backoff(self) -> None: - """ - Recompute the reconnection timeout. The self._reconnect_timeout will be used - in self._connect() to perform the actual sleep. - - """ - self._reconnect_attempt = self._reconnect_attempt + 1 - self._reconnect_timeout = 2**self._reconnect_attempt - # pylint: disable=consider-using-f-string - self.logger.debug( - "Reconnect timeout computed to {:.2f}".format(self._reconnect_timeout) - ) - - if self._reconnect_timeout > self._reconnect_maximum_backoff: - self.logger.debug( - f"Truncating reconnect timeout to {self._reconnect_maximum_backoff} seconds" - ) - self._reconnect_timeout = float(self._reconnect_maximum_backoff) - - # Add a sub-second jitter. - # Even truncated timeout should have jitter added to it. This is why it is added here. - jitter = randint(0, 1000) / 1000 - # pylint: disable=consider-using-f-string - self.logger.debug( - "adding jitter {:.2f} to {:.2f} seconds".format( - jitter, self._reconnect_timeout - ) - ) - self._reconnect_timeout += jitter - - def _reset_reconnect_backoff(self) -> None: - """ - Reset reconnect back-off to the initial state. - - """ - self.logger.debug("Resetting reconnect backoff") - self._reconnect_attempt = 0 - self._reconnect_timeout = float(0) - - def reconnect(self, resub_topics: bool = True) -> int: - """Attempts to reconnect to the MQTT broker. - Return the value from connect() if successful. Will disconnect first if already connected. - Will perform exponential back-off on connect failures. - - :param bool resub_topics: Whether to resubscribe to previously subscribed topics. - - """ - - self.logger.debug("Attempting to reconnect with MQTT broker") - ret = self.connect() - self.logger.debug("Reconnected with broker") - if resub_topics: - self.logger.debug( - "Attempting to resubscribe to previously subscribed topics." - ) - subscribed_topics = self._subscribed_topics.copy() - self._subscribed_topics = [] - while subscribed_topics: - feed = subscribed_topics.pop() - self.subscribe(feed) - - return ret - - def loop(self, timeout: float = 0) -> Optional[list[int]]: - """Non-blocking message loop. Use this method to check for incoming messages. - Returns list of packet types of any messages received or None. - - :param float timeout: return after this timeout, in seconds. - - """ - if timeout < self._socket_timeout: - raise MMQTTException( - # pylint: disable=consider-using-f-string - "loop timeout ({}) must be bigger ".format(timeout) - + "than socket timeout ({}))".format(self._socket_timeout) - ) - - self._connected() - self.logger.debug(f"waiting for messages for {timeout} seconds") - - stamp = ticks_ms() - rcs = [] - - while True: - if ( - ticks_diff(ticks_ms(), self._last_msg_sent_timestamp) / 1000 - >= self.keep_alive - ): - # Handle KeepAlive by expecting a PINGREQ/PINGRESP from the server - self.logger.debug( - "KeepAlive period elapsed - requesting a PINGRESP from the server..." - ) - rcs.extend(self.ping()) - # ping() itself contains a _wait_for_msg() loop which might have taken a while, - # so check here as well. - if ticks_diff(ticks_ms(), stamp) / 1000 > timeout: - self.logger.debug(f"Loop timed out after {timeout} seconds") - break - - rc = self._wait_for_msg() - if rc is not None: - rcs.append(rc) - if ticks_diff(ticks_ms(), stamp) / 1000 > timeout: - self.logger.debug(f"Loop timed out after {timeout} seconds") - break - - return rcs if rcs else None - - def _wait_for_msg(self, timeout: Optional[float] = None) -> Optional[int]: - # pylint: disable = too-many-return-statements - """Reads and processes network events. - Return the packet type or None if there is nothing to be received. - - :param float timeout: return after this timeout, in seconds. - """ - # CPython socket module contains a timeout attribute - if hasattr(self._socket_pool, "timeout"): - try: - res = self._sock_exact_recv(1) - except self._socket_pool.timeout: - return None - else: # socketpool, esp32spi - try: - res = self._sock_exact_recv(1, timeout=timeout) - except OSError as error: - if error.errno in (errno.ETIMEDOUT, errno.EAGAIN): - # raised by a socket timeout if 0 bytes were present - return None - raise MMQTTException from error - - if res in [None, b"", b"\x00"]: - # If we get here, it means that there is nothing to be received - return None - pkt_type = res[0] & MQTT_PKT_TYPE_MASK - self.logger.debug(f"Got message type: {hex(pkt_type)} pkt: {hex(res[0])}") - if pkt_type == MQTT_PINGRESP: - self.logger.debug("Got PINGRESP") - sz = self._sock_exact_recv(1)[0] - if sz != 0x00: - raise MMQTTException(f"Unexpected PINGRESP returned from broker: {sz}.") - return pkt_type - - if pkt_type != MQTT_PUBLISH: - return pkt_type - - # Handle only the PUBLISH packet type from now on. - sz = self._decode_remaining_length() - # topic length MSB & LSB - topic_len_buf = self._sock_exact_recv(2) - topic_len = int((topic_len_buf[0] << 8) | topic_len_buf[1]) - - if topic_len > sz - 2: - raise MMQTTException( - f"Topic length {topic_len} in PUBLISH packet exceeds remaining length {sz} - 2" - ) - - topic_buf = self._sock_exact_recv(topic_len) - topic = str(topic_buf, "utf-8") - sz -= topic_len + 2 - pid = 0 - if res[0] & 0x06: - pid_buf = self._sock_exact_recv(2) - pid = pid_buf[0] << 0x08 | pid_buf[1] - sz -= 0x02 - - # read message contents - raw_msg = self._sock_exact_recv(sz) - msg = raw_msg if self._use_binary_mode else str(raw_msg, "utf-8") - self.logger.debug("Receiving PUBLISH \nTopic: %s\nMsg: %s\n", topic, raw_msg) - self._handle_on_message(topic, msg) - if res[0] & 0x06 == 0x02: - pkt = bytearray(b"\x40\x02\0\0") - struct.pack_into("!H", pkt, 2, pid) - self._sock.send(pkt) - elif res[0] & 6 == 4: - assert 0 - - return pkt_type - - def _decode_remaining_length(self) -> int: - """Decode Remaining Length [2.2.3]""" - n = 0 - sh = 0 - while True: - if sh > 28: - raise MMQTTException("invalid remaining length encoding") - b = self._sock_exact_recv(1)[0] - n |= (b & 0x7F) << sh - if not b & 0x80: - return n - sh += 7 - - def _sock_exact_recv( - self, bufsize: int, timeout: Optional[float] = None - ) -> bytearray: - """Reads _exact_ number of bytes from the connected socket. Will only return - bytearray with the exact number of bytes requested. - - The semantics of native socket receive is that it returns no more than the - specified number of bytes (i.e. max size). However, it makes no guarantees in - terms of the minimum size of the buffer, which could be 1 byte. This is a - wrapper for socket recv() to ensure that no less than the expected number of - bytes is returned or trigger a timeout exception. - - :param int bufsize: number of bytes to receive - :param float timeout: timeout, in seconds. Defaults to keep_alive - :return: byte array - """ - stamp = ticks_ms() - if not self._backwards_compatible_sock: - # CPython/Socketpool Impl. - rc = bytearray(bufsize) - mv = memoryview(rc) - recv_len = self._sock.recv_into(rc, bufsize) - to_read = bufsize - recv_len - if to_read < 0: - raise MMQTTException(f"negative number of bytes to read: {to_read}") - read_timeout = timeout if timeout is not None else self.keep_alive - mv = mv[recv_len:] - while to_read > 0: - recv_len = self._sock.recv_into(mv, to_read) - to_read -= recv_len - mv = mv[recv_len:] - if ticks_diff(ticks_ms(), stamp) / 1000 > read_timeout: - raise MMQTTException( - f"Unable to receive {to_read} bytes within {read_timeout} seconds." - ) - else: # ESP32SPI Impl. - # This will timeout with socket timeout (not keepalive timeout) - rc = self._sock.recv(bufsize) - if not rc: - self.logger.debug("_sock_exact_recv timeout") - # If no bytes waiting, raise same exception as socketpool - raise OSError(errno.ETIMEDOUT) - # If any bytes waiting, try to read them all, - # or raise exception if wait longer than read_timeout - to_read = bufsize - len(rc) - assert to_read >= 0 - read_timeout = self.keep_alive - while to_read > 0: - recv = self._sock.recv(to_read) - to_read -= len(recv) - rc += recv - if ticks_diff(ticks_ms(), stamp) / 1000 > read_timeout: - raise MMQTTException( - f"Unable to receive {to_read} bytes within {read_timeout} seconds." - ) - return rc - - def _send_str(self, string: str) -> None: - """Encodes a string and sends it to a socket. - - :param str string: String to write to the socket. - - """ - if isinstance(string, str): - self._sock.send(struct.pack("!H", len(string.encode("utf-8")))) - self._sock.send(str.encode(string, "utf-8")) - else: - self._sock.send(struct.pack("!H", len(string))) - self._sock.send(string) - - @staticmethod - def _valid_topic(topic: str) -> None: - """Validates if topic provided is proper MQTT topic format. - - :param str topic: Topic identifier - - """ - if topic is None: - raise MMQTTException("Topic may not be NoneType") - # [MQTT-4.7.3-1] - if not topic: - raise MMQTTException("Topic may not be empty.") - # [MQTT-4.7.3-3] - if len(topic.encode("utf-8")) > MQTT_TOPIC_LENGTH_LIMIT: - raise MMQTTException("Topic length is too large.") - - @staticmethod - def _valid_qos(qos_level: int) -> None: - """Validates if the QoS level is supported by this library - - :param int qos_level: Desired QoS level. - - """ - if isinstance(qos_level, int): - if qos_level < 0 or qos_level > 2: - raise MMQTTException("QoS must be between 1 and 2.") - else: - raise MMQTTException("QoS must be an integer.") - - def _connected(self) -> None: - """Returns MQTT client session status as True if connected, raises - a `MMQTTException` if `False`. - """ - if not self.is_connected(): - raise MMQTTException("MiniMQTT is not connected") - - def is_connected(self) -> bool: - """Returns MQTT client session status as True if connected, False - if not. - """ - return self._is_connected and self._sock is not None - - # Logging - def enable_logger(self, log_pkg, log_level: int = 20, logger_name: str = "log"): - """Enables library logging by getting logger from the specified logging package - and setting its log level. - - :param log_pkg: A Python logging package. - :param log_level: Numeric value of a logging level, defaults to INFO. - :param logger_name: name of the logger, defaults to "log". - - :return logger object - - """ - # pylint: disable=attribute-defined-outside-init - self.logger = log_pkg.getLogger(logger_name) - self.logger.setLevel(log_level) - - return self.logger - - def disable_logger(self) -> None: - """Disables logging.""" - self.logger = NullLogger() +# SPDX-FileCopyrightText: 2019-2021 Brent Rubell for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +# Original Work Copyright (c) 2016 Paul Sokolovsky, uMQTT +# Modified Work Copyright (c) 2019 Bradley Beach, esp32spi_mqtt +# Modified Work Copyright (c) 2012-2019 Roger Light and others, Paho MQTT Python + +# pylint: disable=too-many-lines + +""" +`adafruit_minimqtt` +================================================================================ + +A minimal MQTT Library for CircuitPython. + +* Author(s): Brent Rubell + +Implementation Notes +-------------------- + +Adapted from https://github.com/micropython/micropython-lib/tree/master/umqtt.simple/umqtt + +**Software and Dependencies:** + +* Adafruit CircuitPython firmware for the supported boards: + https://github.com/adafruit/circuitpython/releases + +* Adafruit's Connection Manager library: + https://github.com/adafruit/Adafruit_CircuitPython_ConnectionManager + +""" +import errno +import struct +import time +from random import randint + +from adafruit_connection_manager import get_connection_manager +from adafruit_ticks import ticks_ms, ticks_diff + +try: + from typing import List, Optional, Tuple, Type, Union +except ImportError: + pass + +try: + from types import TracebackType +except ImportError: + pass + +from micropython import const + +from .matcher import MQTTMatcher + +__version__ = "0.0.0+auto.0" +__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_MiniMQTT.git" + +# Client-specific variables +MQTT_MSG_MAX_SZ = const(268435455) +MQTT_MSG_SZ_LIM = const(10000000) +MQTT_TOPIC_LENGTH_LIMIT = const(65535) +MQTT_TCP_PORT = const(1883) +MQTT_TLS_PORT = const(8883) + +# MQTT Commands +MQTT_PINGREQ = b"\xc0\0" +MQTT_PINGRESP = const(0xD0) +MQTT_PUBLISH = const(0x30) +MQTT_SUB = const(0x82) +MQTT_UNSUB = const(0xA2) +MQTT_DISCONNECT = b"\xe0\0" + +MQTT_PKT_TYPE_MASK = const(0xF0) + + +CONNACK_ERRORS = { + const(0x01): "Connection Refused - Incorrect Protocol Version", + const(0x02): "Connection Refused - ID Rejected", + const(0x03): "Connection Refused - Server unavailable", + const(0x04): "Connection Refused - Incorrect username/password", + const(0x05): "Connection Refused - Unauthorized", +} + +_default_sock = None # pylint: disable=invalid-name +_fake_context = None # pylint: disable=invalid-name + + +class MMQTTException(Exception): + """MiniMQTT Exception class.""" + + +class NullLogger: + """Fake logger class that does not do anything""" + + # pylint: disable=unused-argument + def nothing(self, msg: str, *args) -> None: + """no action""" + + def __init__(self) -> None: + for log_level in ["debug", "info", "warning", "error", "critical"]: + setattr(NullLogger, log_level, self.nothing) + + +class MQTT: + """MQTT Client for CircuitPython. + + :param str broker: MQTT Broker URL or IP Address. + :param int port: Optional port definition, defaults to MQTT_TLS_PORT if is_ssl is True, + MQTT_TCP_PORT otherwise. + :param str username: Username for broker authentication. + :param str password: Password for broker authentication. + :param str client_id: Optional client identifier, defaults to a unique, generated string. + :param bool is_ssl: Sets a secure or insecure connection with the broker. + :param int keep_alive: KeepAlive interval between the broker and the MiniMQTT client. + :param int recv_timeout: receive timeout, in seconds. + :param socket socket_pool: A pool of socket resources available for the given radio. + :param ssl_context: SSL context for long-lived SSL connections. + :param bool use_binary_mode: Messages are passed as bytearray instead of string to callbacks. + :param int socket_timeout: How often to check socket state for read/write/connect operations, + in seconds. + :param int connect_retries: How many times to try to connect to the broker before giving up + on connect or reconnect. Exponential backoff will be used for the retries. + :param class user_data: arbitrary data to pass as a second argument to most of the callbacks. + This works with all callbacks but the "on_message" and those added via add_topic_callback(); + for those, to get access to the user_data use the 'user_data' member of the MQTT object + passed as 1st argument. + + """ + + # pylint: disable=too-many-arguments,too-many-instance-attributes,too-many-statements,not-callable,invalid-name,no-member,too-many-locals + def __init__( + self, + *, + broker: str, + port: Optional[int] = None, + username: Optional[str] = None, + password: Optional[str] = None, + client_id: Optional[str] = None, + is_ssl: Optional[bool] = None, + keep_alive: int = 60, + recv_timeout: int = 10, + socket_pool=None, + ssl_context=None, + use_binary_mode: bool = False, + socket_timeout: int = 1, + connect_retries: int = 5, + user_data=None, + ) -> None: + self._connection_manager = get_connection_manager(socket_pool) + self._socket_pool = socket_pool + self._ssl_context = ssl_context + self._sock = None + self._backwards_compatible_sock = False + self._use_binary_mode = use_binary_mode + + if recv_timeout <= socket_timeout: + raise MMQTTException( + "recv_timeout must be strictly greater than socket_timeout" + ) + self._socket_timeout = socket_timeout + self._recv_timeout = recv_timeout + + self.keep_alive = keep_alive + self.user_data = user_data + self._is_connected = False + self._msg_size_lim = MQTT_MSG_SZ_LIM + self._pid = 0 + self._last_msg_sent_timestamp: int = 0 + self.logger = NullLogger() + """An optional logging attribute that can be set with with a Logger + to enable debug logging.""" + + self._reconnect_attempt = 0 + self._reconnect_timeout = float(0) + self._reconnect_maximum_backoff = 32 + if connect_retries <= 0: + raise MMQTTException("connect_retries must be positive") + self._reconnect_attempts_max = connect_retries + + self.broker = broker + self._username = username + self._password = password + if ( + self._password and len(password.encode("utf-8")) > MQTT_TOPIC_LENGTH_LIMIT + ): # [MQTT-3.1.3.5] + raise MMQTTException("Password length is too large.") + + # The connection will be insecure unless is_ssl is set to True. + # If the port is not specified, the security will be set based on the is_ssl parameter. + # If the port is specified, the is_ssl parameter will be honored. + self.port = MQTT_TCP_PORT + if is_ssl is None: + is_ssl = False + self._is_ssl = is_ssl + if self._is_ssl: + self.port = MQTT_TLS_PORT + if port: + self.port = port + + # define client identifier + if client_id: + # user-defined client_id MAY allow client_id's > 23 bytes or + # non-alpha-numeric characters + self.client_id = client_id + else: + # assign a unique client_id + time_int = int(ticks_ms() / 10) % 1000 + self.client_id = f"cpy{randint(0, time_int)}{randint(0, 99)}" + # generated client_id's enforce spec.'s length rules + if len(self.client_id.encode("utf-8")) > 23 or not self.client_id: + raise ValueError("MQTT Client ID must be between 1 and 23 bytes") + + # LWT + self._lw_topic = None + self._lw_qos = 0 + self._lw_msg = None + self._lw_retain = False + + # List of subscribed topics, used for tracking + self._subscribed_topics: List[str] = [] + self._on_message_filtered = MQTTMatcher() + + # Default topic callback methods + self._on_message = None + self.on_connect = None + self.on_disconnect = None + self.on_publish = None + self.on_subscribe = None + self.on_unsubscribe = None + + def __enter__(self): + return self + + def __exit__( + self, + exception_type: Optional[Type[BaseException]], + exception_value: Optional[BaseException], + traceback: Optional[TracebackType], + ) -> None: + self.deinit() + + def deinit(self) -> None: + """De-initializes the MQTT client and disconnects from the mqtt broker.""" + self.disconnect() + + @property + def mqtt_msg(self) -> Tuple[int, int]: + """Returns maximum MQTT payload and topic size.""" + return self._msg_size_lim, MQTT_TOPIC_LENGTH_LIMIT + + @mqtt_msg.setter + def mqtt_msg(self, msg_size: int) -> None: + """Sets the maximum MQTT message payload size. + + :param int msg_size: Maximum MQTT payload size. + """ + if msg_size < MQTT_MSG_MAX_SZ: + self._msg_size_lim = msg_size + + def will_set( + self, + topic: Optional[str] = None, + payload: Optional[Union[int, float, str]] = None, + qos: int = 0, + retain: bool = False, + ) -> None: + """Sets the last will and testament properties. MUST be called before `connect()`. + + :param str topic: MQTT Broker topic. + :param int|float|str payload: Last will disconnection payload. + payloads of type int & float are converted to a string. + :param int qos: Quality of Service level, defaults to + zero. Conventional options are ``0`` (send at most once), ``1`` + (send at least once), or ``2`` (send exactly once). + + .. note:: Only options ``1`` or ``0`` are QoS levels supported by this library. + :param bool retain: Specifies if the payload is to be retained when + it is published. + """ + self.logger.debug("Setting last will properties") + self._valid_qos(qos) + if self._is_connected: + raise MMQTTException("Last Will should only be called before connect().") + if payload is None: + payload = "" + if isinstance(payload, (int, float, str)): + payload = str(payload).encode() + else: + raise MMQTTException("Invalid message data type.") + self._lw_qos = qos + self._lw_topic = topic + self._lw_msg = payload + self._lw_retain = retain + + def add_topic_callback(self, mqtt_topic: str, callback_method) -> None: + """Registers a callback_method for a specific MQTT topic. + + :param str mqtt_topic: MQTT topic identifier. + :param function callback_method: The callback method. + + Expected method signature is ``on_message(client, topic, message)`` + To get access to the user_data, use the client argument. + + If a callback is called for the topic, then any "on_message" callback will not be called. + """ + if mqtt_topic is None or callback_method is None: + raise ValueError("MQTT topic and callback method must both be defined.") + self._on_message_filtered[mqtt_topic] = callback_method + + def remove_topic_callback(self, mqtt_topic: str) -> None: + """Removes a registered callback method. + + :param str mqtt_topic: MQTT topic identifier string. + """ + if mqtt_topic is None: + raise ValueError("MQTT Topic must be defined.") + try: + del self._on_message_filtered[mqtt_topic] + except KeyError: + raise KeyError( + "MQTT topic callback not added with add_topic_callback." + ) from None + + @property + def on_message(self): + """Called when a new message has been received on a subscribed topic. + + Expected method signature is ``on_message(client, topic, message)`` + To get access to the user_data, use the client argument. + """ + return self._on_message + + @on_message.setter + def on_message(self, method) -> None: + self._on_message = method + + def _handle_on_message(self, topic: str, message: str): + matched = False + if topic is not None: + for callback in self._on_message_filtered.iter_match(topic): + callback(self, topic, message) # on_msg with callback + matched = True + + if not matched and self.on_message: # regular on_message + self.on_message(self, topic, message) + + def username_pw_set(self, username: str, password: Optional[str] = None) -> None: + """Set client's username and an optional password. + + :param str username: Username to use with your MQTT broker. + :param str password: Password to use with your MQTT broker. + + """ + if self._is_connected: + raise MMQTTException("This method must be called before connect().") + self._username = username + if password is not None: + self._password = password + + def connect( + self, + clean_session: bool = True, + host: Optional[str] = None, + port: Optional[int] = None, + keep_alive: Optional[int] = None, + ) -> int: + """Initiates connection with the MQTT Broker. Will perform exponential back-off + on connect failures. + + :param bool clean_session: Establishes a persistent session. + :param str host: Hostname or IP address of the remote broker. + :param int port: Network port of the remote broker. + :param int keep_alive: Maximum period allowed for communication + within single connection attempt, in seconds. + + """ + + last_exception = None + backoff = False + for i in range(0, self._reconnect_attempts_max): + if i > 0: + if backoff: + self._recompute_reconnect_backoff() + else: + self._reset_reconnect_backoff() + + self.logger.debug( + f"Attempting to connect to MQTT broker (attempt #{self._reconnect_attempt})" + ) + + try: + ret = self._connect( + clean_session=clean_session, + host=host, + port=port, + keep_alive=keep_alive, + ) + self._reset_reconnect_backoff() + return ret + except RuntimeError as e: + self.logger.warning(f"Socket error when connecting: {e}") + backoff = False + except MMQTTException as e: + last_exception = e + self.logger.info(f"MMQT error: {e}") + backoff = True + + if self._reconnect_attempts_max > 1: + exc_msg = "Repeated connect failures" + else: + exc_msg = "Connect failure" + if last_exception: + raise MMQTTException(exc_msg) from last_exception + + raise MMQTTException(exc_msg) + + # pylint: disable=too-many-branches, too-many-statements, too-many-locals + def _connect( + self, + clean_session: bool = True, + host: Optional[str] = None, + port: Optional[int] = None, + keep_alive: Optional[int] = None, + ) -> int: + """Initiates connection with the MQTT Broker. + + :param bool clean_session: Establishes a persistent session. + :param str host: Hostname or IP address of the remote broker. + :param int port: Network port of the remote broker. + :param int keep_alive: Maximum period allowed for communication, in seconds. + + """ + if host: + self.broker = host + if port: + self.port = port + if keep_alive: + self.keep_alive = keep_alive + + self.logger.debug("Attempting to establish MQTT connection...") + + if self._reconnect_attempt > 0: + self.logger.debug( + f"Sleeping for {self._reconnect_timeout:.3} seconds due to connect back-off" + ) + time.sleep(self._reconnect_timeout) + + # Get a new socket + self._sock = self._connection_manager.get_socket( + self.broker, + self.port, + proto="mqtt:", + timeout=self._socket_timeout, + is_ssl=self._is_ssl, + ssl_context=self._ssl_context, + ) + self._backwards_compatible_sock = not hasattr(self._sock, "recv_into") + + fixed_header = bytearray([0x10]) + + # Variable CONNECT header [MQTT 3.1.2] + # The byte array is used as a template. + var_header = bytearray(b"\x00\x04MQTT\x04\x02\0\0") + var_header[7] = clean_session << 1 + + # Set up variable header and remaining_length + remaining_length = 12 + len(self.client_id.encode("utf-8")) + if self._username is not None: + remaining_length += ( + 2 + + len(self._username.encode("utf-8")) + + 2 + + len(self._password.encode("utf-8")) + ) + var_header[7] |= 0xC0 + if self.keep_alive: + assert self.keep_alive < MQTT_TOPIC_LENGTH_LIMIT + var_header[8] |= self.keep_alive >> 8 + var_header[9] |= self.keep_alive & 0x00FF + if self._lw_topic: + remaining_length += ( + 2 + len(self._lw_topic.encode("utf-8")) + 2 + len(self._lw_msg) + ) + var_header[7] |= 0x4 | (self._lw_qos & 0x1) << 3 | (self._lw_qos & 0x2) << 3 + var_header[7] |= self._lw_retain << 5 + + self._encode_remaining_length(fixed_header, remaining_length) + self.logger.debug("Sending CONNECT to broker...") + self.logger.debug(f"Fixed Header: {fixed_header}") + self.logger.debug(f"Variable Header: {var_header}") + self._sock.send(fixed_header) + self._sock.send(var_header) + # [MQTT-3.1.3-4] + self._send_str(self.client_id) + if self._lw_topic: + # [MQTT-3.1.3-11] + self._send_str(self._lw_topic) + self._send_str(self._lw_msg) + if self._username is not None: + self._send_str(self._username) + self._send_str(self._password) + self._last_msg_sent_timestamp = ticks_ms() + self.logger.debug("Receiving CONNACK packet from broker") + stamp = ticks_ms() + while True: + op = self._wait_for_msg() + if op == 32: + rc = self._sock_exact_recv(3) + assert rc[0] == 0x02 + if rc[2] != 0x00: + raise MMQTTException(CONNACK_ERRORS[rc[2]]) + self._is_connected = True + result = rc[0] & 1 + if self.on_connect is not None: + self.on_connect(self, self.user_data, result, rc[2]) + + return result + + if op is None: + if ticks_diff(ticks_ms(), stamp) / 1000 > self._recv_timeout: + raise MMQTTException( + f"No data received from broker for {self._recv_timeout} seconds." + ) + + # pylint: disable=no-self-use + def _encode_remaining_length( + self, fixed_header: bytearray, remaining_length: int + ) -> None: + """Encode Remaining Length [2.2.3]""" + if remaining_length > 268_435_455: + raise MMQTTException("invalid remaining length") + + # Remaining length calculation + if remaining_length > 0x7F: + while remaining_length > 0: + encoded_byte = remaining_length % 0x80 + remaining_length = remaining_length // 0x80 + # if there is more data to encode, set the top bit of the byte + if remaining_length > 0: + encoded_byte |= 0x80 + fixed_header.append(encoded_byte) + else: + fixed_header.append(remaining_length) + + def disconnect(self) -> None: + """Disconnects the MiniMQTT client from the MQTT broker.""" + self._connected() + self.logger.debug("Sending DISCONNECT packet to broker") + try: + self._sock.send(MQTT_DISCONNECT) + except RuntimeError as e: + self.logger.warning(f"Unable to send DISCONNECT packet: {e}") + self.logger.debug("Closing socket") + self._connection_manager.close_socket(self._sock) + self._is_connected = False + self._subscribed_topics = [] + self._last_msg_sent_timestamp = 0 + if self.on_disconnect is not None: + self.on_disconnect(self, self.user_data, 0) + + def ping(self) -> list[int]: + """Pings the MQTT Broker to confirm if the broker is alive or if + there is an active network connection. + Returns packet types of any messages received while waiting for PINGRESP. + """ + self._connected() + self.logger.debug("Sending PINGREQ") + self._sock.send(MQTT_PINGREQ) + ping_timeout = self.keep_alive + stamp = ticks_ms() + self._last_msg_sent_timestamp = stamp + rc, rcs = None, [] + while rc != MQTT_PINGRESP: + rc = self._wait_for_msg() + if rc: + rcs.append(rc) + if ticks_diff(ticks_ms(), stamp) / 1000 > ping_timeout: + raise MMQTTException( + f"PINGRESP not returned from broker within {ping_timeout} seconds." + ) + return rcs + + # pylint: disable=too-many-branches, too-many-statements + def publish( + self, + topic: str, + msg: Union[str, int, float, bytes], + retain: bool = False, + qos: int = 0, + ) -> None: + """Publishes a message to a topic provided. + + :param str topic: Unique topic identifier. + :param str|int|float|bytes msg: Data to send to the broker. + :param bool retain: Whether the message is saved by the broker. + :param int qos: Quality of Service level for the message, defaults to zero. + + """ + self._connected() + self._valid_topic(topic) + if "+" in topic or "#" in topic: + raise MMQTTException("Publish topic can not contain wildcards.") + # check msg/qos kwargs + if msg is None: + raise MMQTTException("Message can not be None.") + if isinstance(msg, (int, float)): + msg = str(msg).encode("ascii") + elif isinstance(msg, str): + msg = str(msg).encode("utf-8") + elif isinstance(msg, bytes): + pass + else: + raise MMQTTException("Invalid message data type.") + if len(msg) > MQTT_MSG_MAX_SZ: + raise MMQTTException(f"Message size larger than {MQTT_MSG_MAX_SZ} bytes.") + assert ( + 0 <= qos <= 1 + ), "Quality of Service Level 2 is unsupported by this library." + + # fixed header. [3.3.1.2], [3.3.1.3] + pub_hdr_fixed = bytearray([MQTT_PUBLISH | retain | qos << 1]) + + # variable header = 2-byte Topic length (big endian) + pub_hdr_var = bytearray(struct.pack(">H", len(topic.encode("utf-8")))) + pub_hdr_var.extend(topic.encode("utf-8")) # Topic name + + remaining_length = 2 + len(msg) + len(topic.encode("utf-8")) + if qos > 0: + # packet identifier where QoS level is 1 or 2. [3.3.2.2] + remaining_length += 2 + self._pid = self._pid + 1 if self._pid < 0xFFFF else 1 + pub_hdr_var.append(self._pid >> 8) + pub_hdr_var.append(self._pid & 0xFF) + + self._encode_remaining_length(pub_hdr_fixed, remaining_length) + + self.logger.debug( + "Sending PUBLISH\nTopic: %s\nMsg: %s\ + \nQoS: %d\nRetain? %r", + topic, + msg, + qos, + retain, + ) + self._sock.send(pub_hdr_fixed) + self._sock.send(pub_hdr_var) + self._sock.send(msg) + self._last_msg_sent_timestamp = ticks_ms() + if qos == 0 and self.on_publish is not None: + self.on_publish(self, self.user_data, topic, self._pid) + if qos == 1: + stamp = ticks_ms() + while True: + op = self._wait_for_msg() + if op == 0x40: + sz = self._sock_exact_recv(1) + assert sz == b"\x02" + rcv_pid_buf = self._sock_exact_recv(2) + rcv_pid = rcv_pid_buf[0] << 0x08 | rcv_pid_buf[1] + if self._pid == rcv_pid: + if self.on_publish is not None: + self.on_publish(self, self.user_data, topic, rcv_pid) + return + + if op is None: + if ticks_diff(ticks_ms(), stamp) / 1000 > self._recv_timeout: + raise MMQTTException( + f"No data received from broker for {self._recv_timeout} seconds." + ) + + def subscribe(self, topic: Optional[Union[tuple, str, list]], qos: int = 0) -> None: + """Subscribes to a topic on the MQTT Broker. + This method can subscribe to one topic or multiple topics. + + :param str|tuple|list topic: Unique MQTT topic identifier string. If + this is a `tuple`, then the tuple should + contain topic identifier string and qos + level integer. If this is a `list`, then + each list element should be a tuple containing + a topic identifier string and qos level integer. + :param int qos: Quality of Service level for the topic, defaults to + zero. Conventional options are ``0`` (send at most once), ``1`` + (send at least once), or ``2`` (send exactly once). + + """ + self._connected() + topics = None + if isinstance(topic, tuple): + topic, qos = topic + self._valid_topic(topic) + self._valid_qos(qos) + if isinstance(topic, str): + self._valid_topic(topic) + self._valid_qos(qos) + topics = [(topic, qos)] + if isinstance(topic, list): + topics = [] + for t, q in topic: + self._valid_qos(q) + self._valid_topic(t) + topics.append((t, q)) + # Assemble packet + self.logger.debug("Sending SUBSCRIBE to broker...") + fixed_header = bytearray([MQTT_SUB]) + packet_length = 2 + (2 * len(topics)) + (1 * len(topics)) + packet_length += sum(len(topic.encode("utf-8")) for topic, qos in topics) + self._encode_remaining_length(fixed_header, remaining_length=packet_length) + self.logger.debug(f"Fixed Header: {fixed_header}") + self._sock.send(fixed_header) + self._pid = self._pid + 1 if self._pid < 0xFFFF else 1 + packet_id_bytes = self._pid.to_bytes(2, "big") + var_header = packet_id_bytes + self.logger.debug(f"Variable Header: {var_header}") + self._sock.send(var_header) + # attaching topic and QOS level to the packet + payload = bytes() + for t, q in topics: + topic_size = len(t.encode("utf-8")).to_bytes(2, "big") + qos_byte = q.to_bytes(1, "big") + payload += topic_size + t.encode() + qos_byte + for t, q in topics: + self.logger.debug(f"SUBSCRIBING to topic {t} with QoS {q}") + self.logger.debug(f"payload: {payload}") + self._sock.send(payload) + stamp = ticks_ms() + self._last_msg_sent_timestamp = stamp + while True: + op = self._wait_for_msg() + if op is None: + if ticks_diff(ticks_ms(), stamp) / 1000 > self._recv_timeout: + raise MMQTTException( + f"No data received from broker for {self._recv_timeout} seconds." + ) + else: + if op == 0x90: + remaining_len = self._decode_remaining_length() + assert remaining_len > 0 + rc = self._sock_exact_recv(2) + # Check packet identifier. + assert rc[0] == var_header[0] and rc[1] == var_header[1] + rc = self._sock_exact_recv(remaining_len - 2) + for i in range(0, remaining_len - 2): + if rc[i] not in [0, 1, 2]: + raise MMQTTException( + f"SUBACK Failure for topic {topics[i][0]}: {hex(rc[i])}" + ) + + for t, q in topics: + if self.on_subscribe is not None: + self.on_subscribe(self, self.user_data, t, q) + self._subscribed_topics.append(t) + + return + + if op != MQTT_PUBLISH: + # [3.8.4] The Server is permitted to start sending PUBLISH packets + # matching the Subscription before the Server sends the SUBACK Packet. + raise MMQTTException( + f"invalid message received as response to SUBSCRIBE: {hex(op)}" + ) + + def unsubscribe(self, topic: Optional[Union[str, list]]) -> None: + """Unsubscribes from a MQTT topic. + + :param str|list topic: Unique MQTT topic identifier string or list. + + """ + topics = None + if isinstance(topic, str): + self._valid_topic(topic) + topics = [(topic)] + if isinstance(topic, list): + topics = [] + for t in topic: + self._valid_topic(t) + topics.append((t)) + for t in topics: + if t not in self._subscribed_topics: + raise MMQTTException( + "Topic must be subscribed to before attempting unsubscribe." + ) + # Assemble packet + self.logger.debug("Sending UNSUBSCRIBE to broker...") + fixed_header = bytearray([MQTT_UNSUB]) + packet_length = 2 + (2 * len(topics)) + packet_length += sum(len(topic.encode("utf-8")) for topic in topics) + self._encode_remaining_length(fixed_header, remaining_length=packet_length) + self.logger.debug(f"Fixed Header: {fixed_header}") + self._sock.send(fixed_header) + self._pid = self._pid + 1 if self._pid < 0xFFFF else 1 + packet_id_bytes = self._pid.to_bytes(2, "big") + var_header = packet_id_bytes + self.logger.debug(f"Variable Header: {var_header}") + self._sock.send(var_header) + payload = bytes() + for t in topics: + topic_size = len(t.encode("utf-8")).to_bytes(2, "big") + payload += topic_size + t.encode() + for t in topics: + self.logger.debug(f"UNSUBSCRIBING from topic {t}") + self._sock.send(payload) + self._last_msg_sent_timestamp = ticks_ms() + self.logger.debug("Waiting for UNSUBACK...") + while True: + stamp = ticks_ms() + op = self._wait_for_msg() + if op is None: + if ticks_diff(ticks_ms(), stamp) / 1000 > self._recv_timeout: + raise MMQTTException( + f"No data received from broker for {self._recv_timeout} seconds." + ) + else: + if op == 176: + rc = self._sock_exact_recv(3) + assert rc[0] == 0x02 + # [MQTT-3.32] + assert rc[1] == packet_id_bytes[0] and rc[2] == packet_id_bytes[1] + for t in topics: + if self.on_unsubscribe is not None: + self.on_unsubscribe(self, self.user_data, t, self._pid) + self._subscribed_topics.remove(t) + return + + raise MMQTTException( + f"invalid message received as response to UNSUBSCRIBE: {hex(op)}" + ) + + def _recompute_reconnect_backoff(self) -> None: + """ + Recompute the reconnection timeout. The self._reconnect_timeout will be used + in self._connect() to perform the actual sleep. + + """ + self._reconnect_attempt = self._reconnect_attempt + 1 + self._reconnect_timeout = 2**self._reconnect_attempt + # pylint: disable=consider-using-f-string + self.logger.debug( + "Reconnect timeout computed to {:.2f}".format(self._reconnect_timeout) + ) + + if self._reconnect_timeout > self._reconnect_maximum_backoff: + self.logger.debug( + f"Truncating reconnect timeout to {self._reconnect_maximum_backoff} seconds" + ) + self._reconnect_timeout = float(self._reconnect_maximum_backoff) + + # Add a sub-second jitter. + # Even truncated timeout should have jitter added to it. This is why it is added here. + jitter = randint(0, 1000) / 1000 + # pylint: disable=consider-using-f-string + self.logger.debug( + "adding jitter {:.2f} to {:.2f} seconds".format( + jitter, self._reconnect_timeout + ) + ) + self._reconnect_timeout += jitter + + def _reset_reconnect_backoff(self) -> None: + """ + Reset reconnect back-off to the initial state. + + """ + self.logger.debug("Resetting reconnect backoff") + self._reconnect_attempt = 0 + self._reconnect_timeout = float(0) + + def reconnect(self, resub_topics: bool = True) -> int: + """Attempts to reconnect to the MQTT broker. + Return the value from connect() if successful. Will disconnect first if already connected. + Will perform exponential back-off on connect failures. + + :param bool resub_topics: Whether to resubscribe to previously subscribed topics. + + """ + + self.logger.debug("Attempting to reconnect with MQTT broker") + ret = self.connect() + self.logger.debug("Reconnected with broker") + if resub_topics: + self.logger.debug( + "Attempting to resubscribe to previously subscribed topics." + ) + subscribed_topics = self._subscribed_topics.copy() + self._subscribed_topics = [] + while subscribed_topics: + feed = subscribed_topics.pop() + self.subscribe(feed) + + return ret + + def loop(self, timeout: float = 0) -> Optional[list[int]]: + """Non-blocking message loop. Use this method to check for incoming messages. + Returns list of packet types of any messages received or None. + + :param float timeout: return after this timeout, in seconds. + + """ + if timeout < self._socket_timeout: + raise MMQTTException( + # pylint: disable=consider-using-f-string + "loop timeout ({}) must be bigger ".format(timeout) + + "than socket timeout ({}))".format(self._socket_timeout) + ) + + self._connected() + self.logger.debug(f"waiting for messages for {timeout} seconds") + + stamp = ticks_ms() + rcs = [] + + while True: + if ( + ticks_diff(ticks_ms(), self._last_msg_sent_timestamp) / 1000 + >= self.keep_alive + ): + # Handle KeepAlive by expecting a PINGREQ/PINGRESP from the server + self.logger.debug( + "KeepAlive period elapsed - requesting a PINGRESP from the server..." + ) + rcs.extend(self.ping()) + # ping() itself contains a _wait_for_msg() loop which might have taken a while, + # so check here as well. + if ticks_diff(ticks_ms(), stamp) / 1000 > timeout: + self.logger.debug(f"Loop timed out after {timeout} seconds") + break + + rc = self._wait_for_msg() + if rc is not None: + rcs.append(rc) + if ticks_diff(ticks_ms(), stamp) / 1000 > timeout: + self.logger.debug(f"Loop timed out after {timeout} seconds") + break + + return rcs if rcs else None + + def _wait_for_msg(self, timeout: Optional[float] = None) -> Optional[int]: + # pylint: disable = too-many-return-statements + """Reads and processes network events. + Return the packet type or None if there is nothing to be received. + + :param float timeout: return after this timeout, in seconds. + """ + # CPython socket module contains a timeout attribute + if hasattr(self._socket_pool, "timeout"): + try: + res = self._sock_exact_recv(1) + except self._socket_pool.timeout: + return None + else: # socketpool, esp32spi + try: + res = self._sock_exact_recv(1, timeout=timeout) + except OSError as error: + if error.errno in (errno.ETIMEDOUT, errno.EAGAIN): + # raised by a socket timeout if 0 bytes were present + return None + raise MMQTTException from error + + if res in [None, b"", b"\x00"]: + # If we get here, it means that there is nothing to be received + return None + pkt_type = res[0] & MQTT_PKT_TYPE_MASK + self.logger.debug(f"Got message type: {hex(pkt_type)} pkt: {hex(res[0])}") + if pkt_type == MQTT_PINGRESP: + self.logger.debug("Got PINGRESP") + sz = self._sock_exact_recv(1)[0] + if sz != 0x00: + raise MMQTTException(f"Unexpected PINGRESP returned from broker: {sz}.") + return pkt_type + + if pkt_type != MQTT_PUBLISH: + return pkt_type + + # Handle only the PUBLISH packet type from now on. + sz = self._decode_remaining_length() + # topic length MSB & LSB + topic_len_buf = self._sock_exact_recv(2) + topic_len = int((topic_len_buf[0] << 8) | topic_len_buf[1]) + + if topic_len > sz - 2: + raise MMQTTException( + f"Topic length {topic_len} in PUBLISH packet exceeds remaining length {sz} - 2" + ) + + topic_buf = self._sock_exact_recv(topic_len) + topic = str(topic_buf, "utf-8") + sz -= topic_len + 2 + pid = 0 + if res[0] & 0x06: + pid_buf = self._sock_exact_recv(2) + pid = pid_buf[0] << 0x08 | pid_buf[1] + sz -= 0x02 + + # read message contents + raw_msg = self._sock_exact_recv(sz) + msg = raw_msg if self._use_binary_mode else str(raw_msg, "utf-8") + self.logger.debug("Receiving PUBLISH \nTopic: %s\nMsg: %s\n", topic, raw_msg) + self._handle_on_message(topic, msg) + if res[0] & 0x06 == 0x02: + pkt = bytearray(b"\x40\x02\0\0") + struct.pack_into("!H", pkt, 2, pid) + self._sock.send(pkt) + elif res[0] & 6 == 4: + assert 0 + + return pkt_type + + def _decode_remaining_length(self) -> int: + """Decode Remaining Length [2.2.3]""" + n = 0 + sh = 0 + while True: + if sh > 28: + raise MMQTTException("invalid remaining length encoding") + b = self._sock_exact_recv(1)[0] + n |= (b & 0x7F) << sh + if not b & 0x80: + return n + sh += 7 + + def _sock_exact_recv( + self, bufsize: int, timeout: Optional[float] = None + ) -> bytearray: + """Reads _exact_ number of bytes from the connected socket. Will only return + bytearray with the exact number of bytes requested. + + The semantics of native socket receive is that it returns no more than the + specified number of bytes (i.e. max size). However, it makes no guarantees in + terms of the minimum size of the buffer, which could be 1 byte. This is a + wrapper for socket recv() to ensure that no less than the expected number of + bytes is returned or trigger a timeout exception. + + :param int bufsize: number of bytes to receive + :param float timeout: timeout, in seconds. Defaults to keep_alive + :return: byte array + """ + stamp = ticks_ms() + if not self._backwards_compatible_sock: + # CPython/Socketpool Impl. + rc = bytearray(bufsize) + mv = memoryview(rc) + recv_len = self._sock.recv_into(rc, bufsize) + to_read = bufsize - recv_len + if to_read < 0: + raise MMQTTException(f"negative number of bytes to read: {to_read}") + read_timeout = timeout if timeout is not None else self.keep_alive + mv = mv[recv_len:] + while to_read > 0: + recv_len = self._sock.recv_into(mv, to_read) + to_read -= recv_len + mv = mv[recv_len:] + if ticks_diff(ticks_ms(), stamp) / 1000 > read_timeout: + raise MMQTTException( + f"Unable to receive {to_read} bytes within {read_timeout} seconds." + ) + else: # ESP32SPI Impl. + # This will timeout with socket timeout (not keepalive timeout) + rc = self._sock.recv(bufsize) + if not rc: + self.logger.debug("_sock_exact_recv timeout") + # If no bytes waiting, raise same exception as socketpool + raise OSError(errno.ETIMEDOUT) + # If any bytes waiting, try to read them all, + # or raise exception if wait longer than read_timeout + to_read = bufsize - len(rc) + assert to_read >= 0 + read_timeout = self.keep_alive + while to_read > 0: + recv = self._sock.recv(to_read) + to_read -= len(recv) + rc += recv + if ticks_diff(ticks_ms(), stamp) / 1000 > read_timeout: + raise MMQTTException( + f"Unable to receive {to_read} bytes within {read_timeout} seconds." + ) + return rc + + def _send_str(self, string: str) -> None: + """Encodes a string and sends it to a socket. + + :param str string: String to write to the socket. + + """ + if isinstance(string, str): + self._sock.send(struct.pack("!H", len(string.encode("utf-8")))) + self._sock.send(str.encode(string, "utf-8")) + else: + self._sock.send(struct.pack("!H", len(string))) + self._sock.send(string) + + @staticmethod + def _valid_topic(topic: str) -> None: + """Validates if topic provided is proper MQTT topic format. + + :param str topic: Topic identifier + + """ + if topic is None: + raise MMQTTException("Topic may not be NoneType") + # [MQTT-4.7.3-1] + if not topic: + raise MMQTTException("Topic may not be empty.") + # [MQTT-4.7.3-3] + if len(topic.encode("utf-8")) > MQTT_TOPIC_LENGTH_LIMIT: + raise MMQTTException("Topic length is too large.") + + @staticmethod + def _valid_qos(qos_level: int) -> None: + """Validates if the QoS level is supported by this library + + :param int qos_level: Desired QoS level. + + """ + if isinstance(qos_level, int): + if qos_level < 0 or qos_level > 2: + raise MMQTTException("QoS must be between 1 and 2.") + else: + raise MMQTTException("QoS must be an integer.") + + def _connected(self) -> None: + """Returns MQTT client session status as True if connected, raises + a `MMQTTException` if `False`. + """ + if not self.is_connected(): + raise MMQTTException("MiniMQTT is not connected") + + def is_connected(self) -> bool: + """Returns MQTT client session status as True if connected, False + if not. + """ + return self._is_connected and self._sock is not None + + # Logging + def enable_logger(self, log_pkg, log_level: int = 20, logger_name: str = "log"): + """Enables library logging by getting logger from the specified logging package + and setting its log level. + + :param log_pkg: A Python logging package. + :param log_level: Numeric value of a logging level, defaults to INFO. + :param logger_name: name of the logger, defaults to "log". + + :return logger object + + """ + # pylint: disable=attribute-defined-outside-init + self.logger = log_pkg.getLogger(logger_name) + self.logger.setLevel(log_level) + + return self.logger + + def disable_logger(self) -> None: + """Disables logging.""" + self.logger = NullLogger() diff --git a/adafruit_minimqtt/matcher.py b/adafruit_minimqtt/matcher.py index c14a3514..94ee9a47 100644 --- a/adafruit_minimqtt/matcher.py +++ b/adafruit_minimqtt/matcher.py @@ -1,101 +1,101 @@ -# SPDX-FileCopyrightText: 2017 Yoch -# -# SPDX-License-Identifier: EPL-1.0 - -""" -`matcher` -==================================================================================== - -MQTT topic filter matcher from the Eclipse Project's Paho.MQTT.Python -https://github.com/eclipse/paho.mqtt.python/blob/master/src/paho/mqtt/matcher.py -* Author(s): Yoch (https://github.com/yoch) -""" - -try: - from typing import Dict -except ImportError: - pass - - -class MQTTMatcher: - """Intended to manage topic filters including wildcards. - - Internally, MQTTMatcher use a prefix tree (trie) to store - values associated with filters, and has an iter_match() - method to iterate efficiently over all filters that match - some topic name. - """ - - # pylint: disable=too-few-public-methods - class Node: - """Individual node on the MQTT prefix tree.""" - - __slots__ = "children", "content" - - def __init__(self) -> None: - self.children: Dict[str, MQTTMatcher.Node] = {} - self.content = None - - def __init__(self) -> None: - self._root = self.Node() - - def __setitem__(self, key: str, value) -> None: - """Add a topic filter :key to the prefix tree - and associate it to :value""" - node = self._root - for sym in key.split("/"): - node = node.children.setdefault(sym, self.Node()) - node.content = value - - def __getitem__(self, key: str): - """Retrieve the value associated with some topic filter :key""" - try: - node = self._root - for sym in key.split("/"): - node = node.children[sym] - if node.content is None: - raise KeyError(key) - return node.content - except KeyError: - raise KeyError(key) from None - - def __delitem__(self, key: str) -> None: - """Delete the value associated with some topic filter :key""" - lst = [] - try: - parent, node = None, self._root - for k in key.split("/"): - parent, node = node, node.children[k] - lst.append((parent, k, node)) - node.content = None - except KeyError: - raise KeyError(key) from None - for parent, k, node in reversed(lst): - if node.children or node.content is not None: - break - del parent.children[k] - - def iter_match(self, topic: str): - """Return an iterator on all values associated with filters - that match the :topic""" - lst = topic.split("/") - normal = not topic.startswith("$") - - def rec(node: MQTTMatcher.Node, i: int = 0): - if i == len(lst): - if node.content is not None: - yield node.content - else: - part = lst[i] - if part in node.children: - for content in rec(node.children[part], i + 1): - yield content - if "+" in node.children and (normal or i > 0): - for content in rec(node.children["+"], i + 1): - yield content - if "#" in node.children and (normal or i > 0): - content = node.children["#"].content - if content is not None: - yield content - - return rec(self._root) +# SPDX-FileCopyrightText: 2017 Yoch +# +# SPDX-License-Identifier: EPL-1.0 + +""" +`matcher` +==================================================================================== + +MQTT topic filter matcher from the Eclipse Project's Paho.MQTT.Python +https://github.com/eclipse/paho.mqtt.python/blob/master/src/paho/mqtt/matcher.py +* Author(s): Yoch (https://github.com/yoch) +""" + +try: + from typing import Dict +except ImportError: + pass + + +class MQTTMatcher: + """Intended to manage topic filters including wildcards. + + Internally, MQTTMatcher use a prefix tree (trie) to store + values associated with filters, and has an iter_match() + method to iterate efficiently over all filters that match + some topic name. + """ + + # pylint: disable=too-few-public-methods + class Node: + """Individual node on the MQTT prefix tree.""" + + __slots__ = "children", "content" + + def __init__(self) -> None: + self.children: Dict[str, MQTTMatcher.Node] = {} + self.content = None + + def __init__(self) -> None: + self._root = self.Node() + + def __setitem__(self, key: str, value) -> None: + """Add a topic filter :key to the prefix tree + and associate it to :value""" + node = self._root + for sym in key.split("/"): + node = node.children.setdefault(sym, self.Node()) + node.content = value + + def __getitem__(self, key: str): + """Retrieve the value associated with some topic filter :key""" + try: + node = self._root + for sym in key.split("/"): + node = node.children[sym] + if node.content is None: + raise KeyError(key) + return node.content + except KeyError: + raise KeyError(key) from None + + def __delitem__(self, key: str) -> None: + """Delete the value associated with some topic filter :key""" + lst = [] + try: + parent, node = None, self._root + for k in key.split("/"): + parent, node = node, node.children[k] + lst.append((parent, k, node)) + node.content = None + except KeyError: + raise KeyError(key) from None + for parent, k, node in reversed(lst): + if node.children or node.content is not None: + break + del parent.children[k] + + def iter_match(self, topic: str): + """Return an iterator on all values associated with filters + that match the :topic""" + lst = topic.split("/") + normal = not topic.startswith("$") + + def rec(node: MQTTMatcher.Node, i: int = 0): + if i == len(lst): + if node.content is not None: + yield node.content + else: + part = lst[i] + if part in node.children: + for content in rec(node.children[part], i + 1): + yield content + if "+" in node.children and (normal or i > 0): + for content in rec(node.children["+"], i + 1): + yield content + if "#" in node.children and (normal or i > 0): + content = node.children["#"].content + if content is not None: + yield content + + return rec(self._root) diff --git a/docs/_static/favicon.ico.license b/docs/_static/favicon.ico.license index 86a3fbfe..836354a4 100644 --- a/docs/_static/favicon.ico.license +++ b/docs/_static/favicon.ico.license @@ -1,3 +1,3 @@ -SPDX-FileCopyrightText: 2018 Phillip Torrone for Adafruit Industries - -SPDX-License-Identifier: CC-BY-4.0 +SPDX-FileCopyrightText: 2018 Phillip Torrone for Adafruit Industries + +SPDX-License-Identifier: CC-BY-4.0 diff --git a/docs/api.rst b/docs/api.rst index 5ebceac6..18867e82 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -1,8 +1,8 @@ - -.. If you created a package, create one automodule per module in the package. - -.. If your library file(s) are nested in a directory (e.g. /adafruit_foo/foo.py) -.. use this format as the module name: "adafruit_foo.foo" - -.. automodule:: adafruit_minimqtt.adafruit_minimqtt - :members: + +.. If you created a package, create one automodule per module in the package. + +.. If your library file(s) are nested in a directory (e.g. /adafruit_foo/foo.py) +.. use this format as the module name: "adafruit_foo.foo" + +.. automodule:: adafruit_minimqtt.adafruit_minimqtt + :members: diff --git a/docs/api.rst.license b/docs/api.rst.license index 9aae48de..474ed05f 100644 --- a/docs/api.rst.license +++ b/docs/api.rst.license @@ -1,3 +1,3 @@ -# SPDX-FileCopyrightText: 2020 ladyada for Adafruit Industries -# -# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: 2020 ladyada for Adafruit Industries +# +# SPDX-License-Identifier: MIT diff --git a/docs/conf.py b/docs/conf.py index 3b989959..8de48b1b 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,181 +1,181 @@ -# -*- coding: utf-8 -*- - -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# -# SPDX-License-Identifier: MIT - -import os -import sys -import datetime - -sys.path.insert(0, os.path.abspath("..")) - -# -- General configuration ------------------------------------------------ - -# Add any Sphinx extension module names here, as strings. They can be -# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom -# ones. -extensions = [ - "sphinx.ext.autodoc", - "sphinxcontrib.jquery", - "sphinx.ext.intersphinx", - "sphinx.ext.napoleon", - "sphinx.ext.todo", -] - -# Uncomment the below if you use native CircuitPython modules such as -# digitalio, micropython and busio. List the modules you use. Without it, the -# autodoc module docs will fail to generate with a warning. -autodoc_mock_imports = ["microcontroller", "random"] - - -intersphinx_mapping = { - "python": ("https://docs.python.org/3", None), - "CircuitPython": ("https://docs.circuitpython.org/en/latest/", None), -} - -# Add any paths that contain templates here, relative to this directory. -templates_path = ["_templates"] - -source_suffix = ".rst" - -# The master toctree document. -master_doc = "index" - -# General information about the project. -project = "Adafruit MiniMQTT Library" -creation_year = "2019" -current_year = str(datetime.datetime.now().year) -year_duration = ( - current_year - if current_year == creation_year - else creation_year + " - " + current_year -) -copyright = year_duration + " Brent Rubell" -author = "Brent Rubell" - -# The version info for the project you're documenting, acts as replacement for -# |version| and |release|, also used in various other places throughout the -# built documents. -# -# The short X.Y version. -version = "1.0" -# The full version, including alpha/beta/rc tags. -release = "1.0" - -# The language for content autogenerated by Sphinx. Refer to documentation -# for a list of supported languages. -# -# This is also used if you do content translation via gettext catalogs. -# Usually you set "language" from the command line for these cases. -language = "en" - -# List of patterns, relative to source directory, that match files and -# directories to ignore when looking for source files. -# This patterns also effect to html_static_path and html_extra_path -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 -# documents. -# -default_role = "any" - -# If true, '()' will be appended to :func: etc. cross-reference text. -# -add_function_parentheses = True - -# The name of the Pygments (syntax highlighting) style to use. -pygments_style = "sphinx" - -# If true, `todo` and `todoList` produce output, else they produce nothing. -todo_include_todos = False - -# If this is True, todo emits a warning for each TODO entries. The default is False. -todo_emit_warnings = True - -napoleon_numpy_docstring = False - -# -- Options for HTML output ---------------------------------------------- - -# The theme to use for HTML and HTML Help pages. See the documentation for -# a list of builtin themes. -# -import sphinx_rtd_theme - -html_theme = "sphinx_rtd_theme" -html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."] - -# 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, -# so a file named "default.css" will overwrite the builtin "default.css". -html_static_path = ["_static"] - -# 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 -# pixels large. -# -html_favicon = "_static/favicon.ico" - -# Output file base name for HTML help builder. -htmlhelp_basename = "AdafruitMinimqttLibrarydoc" - -# -- Options for LaTeX output --------------------------------------------- - -latex_elements = { - # The paper size ('letterpaper' or 'a4paper'). - # - # 'papersize': 'letterpaper', - # The font size ('10pt', '11pt' or '12pt'). - # - # 'pointsize': '10pt', - # Additional stuff for the LaTeX preamble. - # - # 'preamble': '', - # Latex figure (float) alignment - # - # 'figure_align': 'htbp', -} - -# Grouping the document tree into LaTeX files. List of tuples -# (source start file, target name, title, -# author, documentclass [howto, manual, or own class]). -latex_documents = [ - ( - master_doc, - "AdafruitMiniMQTTLibrary.tex", - "AdafruitMiniMQTT Library Documentation", - author, - "manual", - ), -] - -# -- Options for manual page output --------------------------------------- - -# One entry per manual page. List of tuples -# (source start file, name, description, authors, manual section). -man_pages = [ - ( - master_doc, - "AdafruitMiniMQTTlibrary", - "Adafruit MiniMQTT Library Documentation", - [author], - 1, - ) -] - -# -- Options for Texinfo output ------------------------------------------- - -# Grouping the document tree into Texinfo files. List of tuples -# (source start file, target name, title, author, -# dir menu entry, description, category) -texinfo_documents = [ - ( - master_doc, - "AdafruitMiniMQTTLibrary", - "Adafruit MiniMQTT Library Documentation", - author, - "AdafruitMiniMQTTLibrary", - "One line description of project.", - "Miscellaneous", - ), -] +# -*- coding: utf-8 -*- + +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +import os +import sys +import datetime + +sys.path.insert(0, os.path.abspath("..")) + +# -- General configuration ------------------------------------------------ + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinxcontrib.jquery", + "sphinx.ext.intersphinx", + "sphinx.ext.napoleon", + "sphinx.ext.todo", +] + +# Uncomment the below if you use native CircuitPython modules such as +# digitalio, micropython and busio. List the modules you use. Without it, the +# autodoc module docs will fail to generate with a warning. +autodoc_mock_imports = ["microcontroller", "random"] + + +intersphinx_mapping = { + "python": ("https://docs.python.org/3", None), + "CircuitPython": ("https://docs.circuitpython.org/en/latest/", None), +} + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +source_suffix = ".rst" + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = "Adafruit MiniMQTT Library" +creation_year = "2019" +current_year = str(datetime.datetime.now().year) +year_duration = ( + current_year + if current_year == creation_year + else creation_year + " - " + current_year +) +copyright = year_duration + " Brent Rubell" +author = "Brent Rubell" + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = "1.0" +# The full version, including alpha/beta/rc tags. +release = "1.0" + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = "en" + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +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 +# documents. +# +default_role = "any" + +# If true, '()' will be appended to :func: etc. cross-reference text. +# +add_function_parentheses = True + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + +# If this is True, todo emits a warning for each TODO entries. The default is False. +todo_emit_warnings = True + +napoleon_numpy_docstring = False + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +import sphinx_rtd_theme + +html_theme = "sphinx_rtd_theme" +html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."] + +# 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, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# 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 +# pixels large. +# +html_favicon = "_static/favicon.ico" + +# Output file base name for HTML help builder. +htmlhelp_basename = "AdafruitMinimqttLibrarydoc" + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + master_doc, + "AdafruitMiniMQTTLibrary.tex", + "AdafruitMiniMQTT Library Documentation", + author, + "manual", + ), +] + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + master_doc, + "AdafruitMiniMQTTlibrary", + "Adafruit MiniMQTT Library Documentation", + [author], + 1, + ) +] + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "AdafruitMiniMQTTLibrary", + "Adafruit MiniMQTT Library Documentation", + author, + "AdafruitMiniMQTTLibrary", + "One line description of project.", + "Miscellaneous", + ), +] diff --git a/docs/examples.rst b/docs/examples.rst index 847e6bb1..2fb883dc 100644 --- a/docs/examples.rst +++ b/docs/examples.rst @@ -1,8 +1,8 @@ -Simple test ------------- - -Ensure your device works with this simple test. - -.. literalinclude:: ../examples/minimqtt_simpletest.py - :caption: examples/minimqtt_simpletest.py - :linenos: +Simple test +------------ + +Ensure your device works with this simple test. + +.. literalinclude:: ../examples/minimqtt_simpletest.py + :caption: examples/minimqtt_simpletest.py + :linenos: diff --git a/docs/examples.rst.license b/docs/examples.rst.license index 9aae48de..474ed05f 100644 --- a/docs/examples.rst.license +++ b/docs/examples.rst.license @@ -1,3 +1,3 @@ -# SPDX-FileCopyrightText: 2020 ladyada for Adafruit Industries -# -# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: 2020 ladyada for Adafruit Industries +# +# SPDX-License-Identifier: MIT diff --git a/docs/index.rst b/docs/index.rst index eb6a361a..e383849d 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -1,46 +1,46 @@ -.. include:: ../README.rst - -Table of Contents -================= - -.. toctree:: - :maxdepth: 4 - :hidden: - - self - -.. toctree:: - :caption: Examples - - examples - -.. toctree:: - :caption: API Reference - :maxdepth: 3 - - api - -.. toctree:: - :caption: Tutorials - -.. toctree:: - :caption: Related Products - -.. toctree:: - :caption: Other Links - - Download from GitHub - Download Library Bundle - CircuitPython Reference Documentation - CircuitPython Support Forum - Discord Chat - Adafruit Learning System - Adafruit Blog - Adafruit Store - -Indices and tables -================== - -* :ref:`genindex` -* :ref:`modindex` -* :ref:`search` +.. include:: ../README.rst + +Table of Contents +================= + +.. toctree:: + :maxdepth: 4 + :hidden: + + self + +.. toctree:: + :caption: Examples + + examples + +.. toctree:: + :caption: API Reference + :maxdepth: 3 + + api + +.. toctree:: + :caption: Tutorials + +.. toctree:: + :caption: Related Products + +.. toctree:: + :caption: Other Links + + Download from GitHub + Download Library Bundle + CircuitPython Reference Documentation + CircuitPython Support Forum + Discord Chat + Adafruit Learning System + Adafruit Blog + Adafruit Store + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/docs/index.rst.license b/docs/index.rst.license index 9aae48de..474ed05f 100644 --- a/docs/index.rst.license +++ b/docs/index.rst.license @@ -1,3 +1,3 @@ -# SPDX-FileCopyrightText: 2020 ladyada for Adafruit Industries -# -# SPDX-License-Identifier: MIT +# SPDX-FileCopyrightText: 2020 ladyada for Adafruit Industries +# +# SPDX-License-Identifier: MIT diff --git a/docs/requirements.txt b/docs/requirements.txt index 979f5681..204ed85a 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -1,7 +1,7 @@ -# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries -# -# SPDX-License-Identifier: Unlicense - -sphinx -sphinxcontrib-jquery -sphinx-rtd-theme +# SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +sphinx +sphinxcontrib-jquery +sphinx-rtd-theme diff --git a/examples/cellular/minimqtt_adafruitio_cellular.py b/examples/cellular/minimqtt_adafruitio_cellular.py index 88fa317b..02e7cdcb 100755 --- a/examples/cellular/minimqtt_adafruitio_cellular.py +++ b/examples/cellular/minimqtt_adafruitio_cellular.py @@ -1,112 +1,112 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# SPDX-License-Identifier: MIT - -import os -import time -import board -import busio -import digitalio -import adafruit_connection_manager -from adafruit_fona.adafruit_fona import FONA -import adafruit_fona.adafruit_fona_network as network -import adafruit_fona.adafruit_fona_socket as pool - -import adafruit_minimqtt.adafruit_minimqtt as MQTT - -# Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys -# with your GPRS credentials. Add your Adafruit IO username and key as well. -# DO NOT share that file or commit it into Git or other source control. - -aio_username = os.getenv("aio_username") -aio_key = os.getenv("aio_key") - -### Cellular ### - -# Create a serial connection for the FONA connection -uart = busio.UART(board.TX, board.RX) -rst = digitalio.DigitalInOut(board.D4) -# Initialize FONA -fona = FONA(uart, rst) - -### Feeds ### - -# Setup a feed named 'photocell' for publishing to a feed -photocell_feed = aio_username + "/feeds/photocell" - -# Setup a feed named 'onoff' for subscribing to changes -onoff_feed = aio_username + "/feeds/onoff" - -### Code ### - - -# Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name -def connected(client, userdata, flags, rc): - # This function will be called when the client is connected - # successfully to the broker. - print("Connected to Adafruit IO! Listening for topic changes on %s" % onoff_feed) - # Subscribe to all changes on the onoff_feed. - client.subscribe(onoff_feed) - - -def disconnected(client, userdata, rc): - # This method is called when the client is disconnected - print("Disconnected from Adafruit IO!") - - -def message(client, topic, message): - # This method is called when a topic the client is subscribed to - # has a new message. - print("New message on topic {0}: {1}".format(topic, message)) - - -# Initialize cellular data network -network = network.CELLULAR( - fona, (os.getenv("apn"), os.getenv("apn_username"), os.getenv("apn_password")) -) - -while not network.is_attached: - print("Attaching to network...") - time.sleep(0.5) -print("Attached!") - -while not network.is_connected: - print("Connecting to network...") - network.connect() - time.sleep(0.5) -print("Network Connected!") - -ssl_context = adafruit_connection_manager.create_fake_ssl_context(pool, fona) - -# Set up a MiniMQTT Client -# NOTE: We'll need to connect insecurely for ethernet configurations. -mqtt_client = MQTT.MQTT( - broker="io.adafruit.com", - username=aio_username, - password=aio_key, - is_ssl=False, - socket_pool=pool, - ssl_context=ssl_context, -) - -# Setup the callback methods above -mqtt_client.on_connect = connected -mqtt_client.on_disconnect = disconnected -mqtt_client.on_message = message - - -# Connect the client to the MQTT broker. -print("Connecting to Adafruit IO...") -mqtt_client.connect() - -photocell_val = 0 -while True: - # Poll the message queue - mqtt_client.loop() - - # Send a new message - print("Sending photocell value: %d..." % photocell_val) - mqtt_client.publish(photocell_feed, photocell_val) - print("Sent!") - photocell_val += 1 - time.sleep(5) +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + +import os +import time +import board +import busio +import digitalio +import adafruit_connection_manager +from adafruit_fona.adafruit_fona import FONA +import adafruit_fona.adafruit_fona_network as network +import adafruit_fona.adafruit_fona_socket as pool + +import adafruit_minimqtt.adafruit_minimqtt as MQTT + +# Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys +# with your GPRS credentials. Add your Adafruit IO username and key as well. +# DO NOT share that file or commit it into Git or other source control. + +aio_username = os.getenv("aio_username") +aio_key = os.getenv("aio_key") + +### Cellular ### + +# Create a serial connection for the FONA connection +uart = busio.UART(board.TX, board.RX) +rst = digitalio.DigitalInOut(board.D4) +# Initialize FONA +fona = FONA(uart, rst) + +### Feeds ### + +# Setup a feed named 'photocell' for publishing to a feed +photocell_feed = aio_username + "/feeds/photocell" + +# Setup a feed named 'onoff' for subscribing to changes +onoff_feed = aio_username + "/feeds/onoff" + +### Code ### + + +# Define callback methods which are called when events occur +# pylint: disable=unused-argument, redefined-outer-name +def connected(client, userdata, flags, rc): + # This function will be called when the client is connected + # successfully to the broker. + print("Connected to Adafruit IO! Listening for topic changes on %s" % onoff_feed) + # Subscribe to all changes on the onoff_feed. + client.subscribe(onoff_feed) + + +def disconnected(client, userdata, rc): + # This method is called when the client is disconnected + print("Disconnected from Adafruit IO!") + + +def message(client, topic, message): + # This method is called when a topic the client is subscribed to + # has a new message. + print("New message on topic {0}: {1}".format(topic, message)) + + +# Initialize cellular data network +network = network.CELLULAR( + fona, (os.getenv("apn"), os.getenv("apn_username"), os.getenv("apn_password")) +) + +while not network.is_attached: + print("Attaching to network...") + time.sleep(0.5) +print("Attached!") + +while not network.is_connected: + print("Connecting to network...") + network.connect() + time.sleep(0.5) +print("Network Connected!") + +ssl_context = adafruit_connection_manager.create_fake_ssl_context(pool, fona) + +# Set up a MiniMQTT Client +# NOTE: We'll need to connect insecurely for ethernet configurations. +mqtt_client = MQTT.MQTT( + broker="io.adafruit.com", + username=aio_username, + password=aio_key, + is_ssl=False, + socket_pool=pool, + ssl_context=ssl_context, +) + +# Setup the callback methods above +mqtt_client.on_connect = connected +mqtt_client.on_disconnect = disconnected +mqtt_client.on_message = message + + +# Connect the client to the MQTT broker. +print("Connecting to Adafruit IO...") +mqtt_client.connect() + +photocell_val = 0 +while True: + # Poll the message queue + mqtt_client.loop() + + # Send a new message + print("Sending photocell value: %d..." % photocell_val) + mqtt_client.publish(photocell_feed, photocell_val) + print("Sent!") + photocell_val += 1 + time.sleep(5) diff --git a/examples/cellular/minimqtt_simpletest_cellular.py b/examples/cellular/minimqtt_simpletest_cellular.py index 09e7350d..bdd1e027 100644 --- a/examples/cellular/minimqtt_simpletest_cellular.py +++ b/examples/cellular/minimqtt_simpletest_cellular.py @@ -1,120 +1,120 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# SPDX-License-Identifier: MIT - -import os -import time -import board -import busio -import digitalio -import adafruit_connection_manager -from adafruit_fona.adafruit_fona import FONA -import adafruit_fona.adafruit_fona_network as network -import adafruit_fona.adafruit_fona_socket as pool - -import adafruit_minimqtt.adafruit_minimqtt as MQTT - -# Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys -# with your GPRS credentials. Add your Adafruit IO username and key as well. -# DO NOT share that file or commit it into Git or other source control. - -aio_username = os.getenv("aio_username") -aio_key = os.getenv("aio_key") - -# Create a serial connection for the FONA connection -uart = busio.UART(board.TX, board.RX) -rst = digitalio.DigitalInOut(board.D4) -# Initialize FONA -fona = FONA(uart, rst) - -### Topic Setup ### - -# MQTT Topic -# Use this topic if you'd like to connect to a standard MQTT broker -mqtt_topic = "test/topic" - -# Adafruit IO-style Topic -# Use this topic if you'd like to connect to io.adafruit.com -# mqtt_topic = 'aio_user/feeds/temperature' - -### Code ### - - -# Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name -def connect(client, userdata, flags, rc): - # This function will be called when the client is connected - # successfully to the broker. - print("Connected to MQTT Broker!") - print("Flags: {0}\n RC: {1}".format(flags, rc)) - - -def disconnect(client, userdata, rc): - # This method is called when the client disconnects - # from the broker. - print("Disconnected from MQTT Broker!") - - -def subscribe(client, userdata, topic, granted_qos): - # This method is called when the client subscribes to a new feed. - print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) - - -def unsubscribe(client, userdata, topic, pid): - # This method is called when the client unsubscribes from a feed. - print("Unsubscribed from {0} with PID {1}".format(topic, pid)) - - -def publish(client, userdata, topic, pid): - # This method is called when the client publishes data to a feed. - print("Published to {0} with PID {1}".format(topic, pid)) - - -# Initialize cellular data network -network = network.CELLULAR( - fona, (os.getenv("apn"), os.getenv("apn_username"), os.getenv("apn_password")) -) - -while not network.is_attached: - print("Attaching to network...") - time.sleep(0.5) -print("Attached!") - -while not network.is_connected: - print("Connecting to network...") - network.connect() - time.sleep(0.5) -print("Network Connected!") - -ssl_context = adafruit_connection_manager.create_fake_ssl_context(pool, fona) - -# Set up a MiniMQTT Client -client = MQTT.MQTT( - broker=os.getenv("broker"), - username=os.getenv("username"), - password=os.getenv("password"), - is_ssl=False, - socket_pool=pool, - ssl_context=ssl_context, -) - -# Connect callback handlers to client -client.on_connect = connect -client.on_disconnect = disconnect -client.on_subscribe = subscribe -client.on_unsubscribe = unsubscribe -client.on_publish = publish - -print("Attempting to connect to %s" % client.broker) -client.connect() - -print("Subscribing to %s" % mqtt_topic) -client.subscribe(mqtt_topic) - -print("Publishing to %s" % mqtt_topic) -client.publish(mqtt_topic, "Hello Broker!") - -print("Unsubscribing from %s" % mqtt_topic) -client.unsubscribe(mqtt_topic) - -print("Disconnecting from %s" % client.broker) -client.disconnect() +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + +import os +import time +import board +import busio +import digitalio +import adafruit_connection_manager +from adafruit_fona.adafruit_fona import FONA +import adafruit_fona.adafruit_fona_network as network +import adafruit_fona.adafruit_fona_socket as pool + +import adafruit_minimqtt.adafruit_minimqtt as MQTT + +# Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys +# with your GPRS credentials. Add your Adafruit IO username and key as well. +# DO NOT share that file or commit it into Git or other source control. + +aio_username = os.getenv("aio_username") +aio_key = os.getenv("aio_key") + +# Create a serial connection for the FONA connection +uart = busio.UART(board.TX, board.RX) +rst = digitalio.DigitalInOut(board.D4) +# Initialize FONA +fona = FONA(uart, rst) + +### Topic Setup ### + +# MQTT Topic +# Use this topic if you'd like to connect to a standard MQTT broker +mqtt_topic = "test/topic" + +# Adafruit IO-style Topic +# Use this topic if you'd like to connect to io.adafruit.com +# mqtt_topic = 'aio_user/feeds/temperature' + +### Code ### + + +# Define callback methods which are called when events occur +# pylint: disable=unused-argument, redefined-outer-name +def connect(client, userdata, flags, rc): + # This function will be called when the client is connected + # successfully to the broker. + print("Connected to MQTT Broker!") + print("Flags: {0}\n RC: {1}".format(flags, rc)) + + +def disconnect(client, userdata, rc): + # This method is called when the client disconnects + # from the broker. + print("Disconnected from MQTT Broker!") + + +def subscribe(client, userdata, topic, granted_qos): + # This method is called when the client subscribes to a new feed. + print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) + + +def unsubscribe(client, userdata, topic, pid): + # This method is called when the client unsubscribes from a feed. + print("Unsubscribed from {0} with PID {1}".format(topic, pid)) + + +def publish(client, userdata, topic, pid): + # This method is called when the client publishes data to a feed. + print("Published to {0} with PID {1}".format(topic, pid)) + + +# Initialize cellular data network +network = network.CELLULAR( + fona, (os.getenv("apn"), os.getenv("apn_username"), os.getenv("apn_password")) +) + +while not network.is_attached: + print("Attaching to network...") + time.sleep(0.5) +print("Attached!") + +while not network.is_connected: + print("Connecting to network...") + network.connect() + time.sleep(0.5) +print("Network Connected!") + +ssl_context = adafruit_connection_manager.create_fake_ssl_context(pool, fona) + +# Set up a MiniMQTT Client +client = MQTT.MQTT( + broker=os.getenv("broker"), + username=os.getenv("username"), + password=os.getenv("password"), + is_ssl=False, + socket_pool=pool, + ssl_context=ssl_context, +) + +# Connect callback handlers to client +client.on_connect = connect +client.on_disconnect = disconnect +client.on_subscribe = subscribe +client.on_unsubscribe = unsubscribe +client.on_publish = publish + +print("Attempting to connect to %s" % client.broker) +client.connect() + +print("Subscribing to %s" % mqtt_topic) +client.subscribe(mqtt_topic) + +print("Publishing to %s" % mqtt_topic) +client.publish(mqtt_topic, "Hello Broker!") + +print("Unsubscribing from %s" % mqtt_topic) +client.unsubscribe(mqtt_topic) + +print("Disconnecting from %s" % client.broker) +client.disconnect() diff --git a/examples/cpython/minimqtt_adafruitio_cpython.py b/examples/cpython/minimqtt_adafruitio_cpython.py index 1440ebad..319b009d 100644 --- a/examples/cpython/minimqtt_adafruitio_cpython.py +++ b/examples/cpython/minimqtt_adafruitio_cpython.py @@ -1,80 +1,80 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# SPDX-License-Identifier: MIT - -import os -import socket -import ssl -import time - -import adafruit_minimqtt.adafruit_minimqtt as MQTT - -### Secrets File Setup ### - -# Add settings.toml to your filesystem. Add your Adafruit IO username and key as well. -# DO NOT share that file or commit it into Git or other source control. - -aio_username = os.getenv("aio_username") -aio_key = os.getenv("aio_key") - -### Feeds ### - -# Setup a feed named 'photocell' for publishing to a feed -photocell_feed = aio_username + "/feeds/photocell" - -# Setup a feed named 'onoff' for subscribing to changes -onoff_feed = aio_username + "/feeds/onoff" - -### Code ### - - -# Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name -def connected(client, userdata, flags, rc): - # This function will be called when the client is connected - # successfully to the broker. - print("Connected to Adafruit IO! Listening for topic changes on %s" % onoff_feed) - # Subscribe to all changes on the onoff_feed. - client.subscribe(onoff_feed) - - -def disconnected(client, userdata, rc): - # This method is called when the client is disconnected - print("Disconnected from Adafruit IO!") - - -def message(client, topic, message): - # This method is called when a topic the client is subscribed to - # has a new message. - print("New message on topic {0}: {1}".format(topic, message)) - - -# Set up a MiniMQTT Client -mqtt_client = MQTT.MQTT( - broker="io.adafruit.com", - username=aio_username, - password=aio_key, - socket_pool=socket, - is_ssl=True, - ssl_context=ssl.create_default_context(), -) - -# Setup the callback methods above -mqtt_client.on_connect = connected -mqtt_client.on_disconnect = disconnected -mqtt_client.on_message = message - -# Connect the client to the MQTT broker. -print("Connecting to Adafruit IO...") -mqtt_client.connect() - -photocell_val = 0 -while True: - # Poll the message queue - mqtt_client.loop() - - # Send a new message - print("Sending photocell value: %d..." % photocell_val) - mqtt_client.publish(photocell_feed, photocell_val) - print("Sent!") - photocell_val += 1 - time.sleep(1) +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + +import os +import socket +import ssl +import time + +import adafruit_minimqtt.adafruit_minimqtt as MQTT + +### Secrets File Setup ### + +# Add settings.toml to your filesystem. Add your Adafruit IO username and key as well. +# DO NOT share that file or commit it into Git or other source control. + +aio_username = os.getenv("aio_username") +aio_key = os.getenv("aio_key") + +### Feeds ### + +# Setup a feed named 'photocell' for publishing to a feed +photocell_feed = aio_username + "/feeds/photocell" + +# Setup a feed named 'onoff' for subscribing to changes +onoff_feed = aio_username + "/feeds/onoff" + +### Code ### + + +# Define callback methods which are called when events occur +# pylint: disable=unused-argument, redefined-outer-name +def connected(client, userdata, flags, rc): + # This function will be called when the client is connected + # successfully to the broker. + print("Connected to Adafruit IO! Listening for topic changes on %s" % onoff_feed) + # Subscribe to all changes on the onoff_feed. + client.subscribe(onoff_feed) + + +def disconnected(client, userdata, rc): + # This method is called when the client is disconnected + print("Disconnected from Adafruit IO!") + + +def message(client, topic, message): + # This method is called when a topic the client is subscribed to + # has a new message. + print("New message on topic {0}: {1}".format(topic, message)) + + +# Set up a MiniMQTT Client +mqtt_client = MQTT.MQTT( + broker="io.adafruit.com", + username=aio_username, + password=aio_key, + socket_pool=socket, + is_ssl=True, + ssl_context=ssl.create_default_context(), +) + +# Setup the callback methods above +mqtt_client.on_connect = connected +mqtt_client.on_disconnect = disconnected +mqtt_client.on_message = message + +# Connect the client to the MQTT broker. +print("Connecting to Adafruit IO...") +mqtt_client.connect() + +photocell_val = 0 +while True: + # Poll the message queue + mqtt_client.loop() + + # Send a new message + print("Sending photocell value: %d..." % photocell_val) + mqtt_client.publish(photocell_feed, photocell_val) + print("Sent!") + photocell_val += 1 + time.sleep(1) diff --git a/examples/cpython/minimqtt_simpletest_cpython.py b/examples/cpython/minimqtt_simpletest_cpython.py index 2a6e3a97..959339fe 100644 --- a/examples/cpython/minimqtt_simpletest_cpython.py +++ b/examples/cpython/minimqtt_simpletest_cpython.py @@ -1,92 +1,92 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# SPDX-License-Identifier: MIT - -import os -import ssl -import socket -import adafruit_minimqtt.adafruit_minimqtt as MQTT - -# Add settings.toml to your filesystems. Add your Adafruit IO username and key as well. -# DO NOT share that file or commit it into Git or other source control. - -aio_username = os.getenv("aio_username") -aio_key = os.getenv("aio_key") - -### Topic Setup ### - -# MQTT Topic -# Use this topic if you'd like to connect to a standard MQTT broker -mqtt_topic = "test/topic" - -# Adafruit IO-style Topic -# Use this topic if you'd like to connect to io.adafruit.com -# mqtt_topic = aio_username + "/feeds/temperature" - - -### Code ### -# Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name -def connect(mqtt_client, userdata, flags, rc): - # This function will be called when the mqtt_client is connected - # successfully to the broker. - print("Connected to MQTT Broker!") - print("Flags: {0}\n RC: {1}".format(flags, rc)) - - -def disconnect(mqtt_client, userdata, rc): - # This method is called when the mqtt_client disconnects - # from the broker. - print("Disconnected from MQTT Broker!") - - -def subscribe(mqtt_client, userdata, topic, granted_qos): - # This method is called when the mqtt_client subscribes to a new feed. - print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) - - -def unsubscribe(mqtt_client, userdata, topic, pid): - # This method is called when the mqtt_client unsubscribes from a feed. - print("Unsubscribed from {0} with PID {1}".format(topic, pid)) - - -def publish(mqtt_client, userdata, topic, pid): - # This method is called when the mqtt_client publishes data to a feed. - print("Published to {0} with PID {1}".format(topic, pid)) - - -def message(client, topic, message): - # Method callled when a client's subscribed feed has a new value. - print("New message on topic {0}: {1}".format(topic, message)) - - -# Set up a MiniMQTT Client -mqtt_client = MQTT.MQTT( - broker=os.getenv("broker"), - username=aio_username, - password=aio_key, - socket_pool=socket, - ssl_context=ssl.create_default_context(), -) - -# Connect callback handlers to mqtt_client -mqtt_client.on_connect = connect -mqtt_client.on_disconnect = disconnect -mqtt_client.on_subscribe = subscribe -mqtt_client.on_unsubscribe = unsubscribe -mqtt_client.on_publish = publish -mqtt_client.on_message = message - -print("Attempting to connect to %s" % mqtt_client.broker) -mqtt_client.connect() - -print("Subscribing to %s" % mqtt_topic) -mqtt_client.subscribe(mqtt_topic) - -print("Publishing to %s" % mqtt_topic) -mqtt_client.publish(mqtt_topic, "Hello Broker!") - -print("Unsubscribing from %s" % mqtt_topic) -mqtt_client.unsubscribe(mqtt_topic) - -print("Disconnecting from %s" % mqtt_client.broker) -mqtt_client.disconnect() +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + +import os +import ssl +import socket +import adafruit_minimqtt.adafruit_minimqtt as MQTT + +# Add settings.toml to your filesystems. Add your Adafruit IO username and key as well. +# DO NOT share that file or commit it into Git or other source control. + +aio_username = os.getenv("aio_username") +aio_key = os.getenv("aio_key") + +### Topic Setup ### + +# MQTT Topic +# Use this topic if you'd like to connect to a standard MQTT broker +mqtt_topic = "test/topic" + +# Adafruit IO-style Topic +# Use this topic if you'd like to connect to io.adafruit.com +# mqtt_topic = aio_username + "/feeds/temperature" + + +### Code ### +# Define callback methods which are called when events occur +# pylint: disable=unused-argument, redefined-outer-name +def connect(mqtt_client, userdata, flags, rc): + # This function will be called when the mqtt_client is connected + # successfully to the broker. + print("Connected to MQTT Broker!") + print("Flags: {0}\n RC: {1}".format(flags, rc)) + + +def disconnect(mqtt_client, userdata, rc): + # This method is called when the mqtt_client disconnects + # from the broker. + print("Disconnected from MQTT Broker!") + + +def subscribe(mqtt_client, userdata, topic, granted_qos): + # This method is called when the mqtt_client subscribes to a new feed. + print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) + + +def unsubscribe(mqtt_client, userdata, topic, pid): + # This method is called when the mqtt_client unsubscribes from a feed. + print("Unsubscribed from {0} with PID {1}".format(topic, pid)) + + +def publish(mqtt_client, userdata, topic, pid): + # This method is called when the mqtt_client publishes data to a feed. + print("Published to {0} with PID {1}".format(topic, pid)) + + +def message(client, topic, message): + # Method callled when a client's subscribed feed has a new value. + print("New message on topic {0}: {1}".format(topic, message)) + + +# Set up a MiniMQTT Client +mqtt_client = MQTT.MQTT( + broker=os.getenv("broker"), + username=aio_username, + password=aio_key, + socket_pool=socket, + ssl_context=ssl.create_default_context(), +) + +# Connect callback handlers to mqtt_client +mqtt_client.on_connect = connect +mqtt_client.on_disconnect = disconnect +mqtt_client.on_subscribe = subscribe +mqtt_client.on_unsubscribe = unsubscribe +mqtt_client.on_publish = publish +mqtt_client.on_message = message + +print("Attempting to connect to %s" % mqtt_client.broker) +mqtt_client.connect() + +print("Subscribing to %s" % mqtt_topic) +mqtt_client.subscribe(mqtt_topic) + +print("Publishing to %s" % mqtt_topic) +mqtt_client.publish(mqtt_topic, "Hello Broker!") + +print("Unsubscribing from %s" % mqtt_topic) +mqtt_client.unsubscribe(mqtt_topic) + +print("Disconnecting from %s" % mqtt_client.broker) +mqtt_client.disconnect() diff --git a/examples/cpython/user_data.py b/examples/cpython/user_data.py index dd19c275..68692929 100644 --- a/examples/cpython/user_data.py +++ b/examples/cpython/user_data.py @@ -1,99 +1,99 @@ -# SPDX-FileCopyrightText: 2023 Vladimír Kotal -# SPDX-License-Identifier: Unlicense - -# pylint: disable=logging-fstring-interpolation - -""" -Demonstrate on how to use user_data for various callbacks. -""" - -import logging -import socket -import ssl -import sys - -import adafruit_minimqtt.adafruit_minimqtt as MQTT - - -# pylint: disable=unused-argument -def on_connect(mqtt_client, user_data, flags, ret_code): - """ - connect callback - """ - logger = logging.getLogger(__name__) - logger.debug("Connected to MQTT Broker!") - logger.debug(f"Flags: {flags}\n RC: {ret_code}") - - -# pylint: disable=unused-argument -def on_subscribe(mqtt_client, user_data, topic, granted_qos): - """ - subscribe callback - """ - logger = logging.getLogger(__name__) - logger.debug(f"Subscribed to {topic} with QOS level {granted_qos}") - - -def on_message(client, topic, message): - """ - received message callback - """ - logger = logging.getLogger(__name__) - logger.debug(f"New message on topic {topic}: {message}") - - messages = client.user_data - if not messages.get(topic): - messages[topic] = [] - messages[topic].append(message) - - -# pylint: disable=too-many-statements,too-many-locals -def main(): - """ - Main loop. - """ - - logging.basicConfig() - logger = logging.getLogger(__name__) - logger.setLevel(logging.DEBUG) - - # dictionary/map of topic to list of messages - messages = {} - - # connect to MQTT broker - mqtt = MQTT.MQTT( - broker="172.40.0.3", - port=1883, - socket_pool=socket, - ssl_context=ssl.create_default_context(), - user_data=messages, - ) - - mqtt.on_connect = on_connect - mqtt.on_subscribe = on_subscribe - mqtt.on_message = on_message - - logger.info("Connecting to MQTT broker") - mqtt.connect() - logger.info("Subscribing") - mqtt.subscribe("foo/#", qos=0) - mqtt.add_topic_callback("foo/bar", on_message) - - i = 0 - while True: - i += 1 - logger.debug(f"Loop {i}") - # Make sure to stay connected to the broker e.g. in case of keep alive. - mqtt.loop(1) - - for topic, msg_list in messages.items(): - logger.info(f"Got {len(msg_list)} messages from topic {topic}") - for msg_cnt, msg in enumerate(msg_list): - logger.debug(f"#{msg_cnt}: {msg}") - - -if __name__ == "__main__": - try: - main() - except KeyboardInterrupt: - sys.exit(0) +# SPDX-FileCopyrightText: 2023 Vladimír Kotal +# SPDX-License-Identifier: Unlicense + +# pylint: disable=logging-fstring-interpolation + +""" +Demonstrate on how to use user_data for various callbacks. +""" + +import logging +import socket +import ssl +import sys + +import adafruit_minimqtt.adafruit_minimqtt as MQTT + + +# pylint: disable=unused-argument +def on_connect(mqtt_client, user_data, flags, ret_code): + """ + connect callback + """ + logger = logging.getLogger(__name__) + logger.debug("Connected to MQTT Broker!") + logger.debug(f"Flags: {flags}\n RC: {ret_code}") + + +# pylint: disable=unused-argument +def on_subscribe(mqtt_client, user_data, topic, granted_qos): + """ + subscribe callback + """ + logger = logging.getLogger(__name__) + logger.debug(f"Subscribed to {topic} with QOS level {granted_qos}") + + +def on_message(client, topic, message): + """ + received message callback + """ + logger = logging.getLogger(__name__) + logger.debug(f"New message on topic {topic}: {message}") + + messages = client.user_data + if not messages.get(topic): + messages[topic] = [] + messages[topic].append(message) + + +# pylint: disable=too-many-statements,too-many-locals +def main(): + """ + Main loop. + """ + + logging.basicConfig() + logger = logging.getLogger(__name__) + logger.setLevel(logging.DEBUG) + + # dictionary/map of topic to list of messages + messages = {} + + # connect to MQTT broker + mqtt = MQTT.MQTT( + broker="172.40.0.3", + port=1883, + socket_pool=socket, + ssl_context=ssl.create_default_context(), + user_data=messages, + ) + + mqtt.on_connect = on_connect + mqtt.on_subscribe = on_subscribe + mqtt.on_message = on_message + + logger.info("Connecting to MQTT broker") + mqtt.connect() + logger.info("Subscribing") + mqtt.subscribe("foo/#", qos=0) + mqtt.add_topic_callback("foo/bar", on_message) + + i = 0 + while True: + i += 1 + logger.debug(f"Loop {i}") + # Make sure to stay connected to the broker e.g. in case of keep alive. + mqtt.loop(1) + + for topic, msg_list in messages.items(): + logger.info(f"Got {len(msg_list)} messages from topic {topic}") + for msg_cnt, msg in enumerate(msg_list): + logger.debug(f"#{msg_cnt}: {msg}") + + +if __name__ == "__main__": + try: + main() + except KeyboardInterrupt: + sys.exit(0) diff --git a/examples/esp32spi/minimqtt_adafruitio_esp32spi.py b/examples/esp32spi/minimqtt_adafruitio_esp32spi.py index d944157e..76726669 100644 --- a/examples/esp32spi/minimqtt_adafruitio_esp32spi.py +++ b/examples/esp32spi/minimqtt_adafruitio_esp32spi.py @@ -1,116 +1,116 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# SPDX-License-Identifier: MIT - -import os -import time -import board -import busio -from digitalio import DigitalInOut -import neopixel -import adafruit_connection_manager -from adafruit_esp32spi import adafruit_esp32spi - -import adafruit_minimqtt.adafruit_minimqtt as MQTT - -# Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys -# with your WiFi credentials. Add your Adafruit IO username and key as well. -# DO NOT share that file or commit it into Git or other source control. - -aio_username = os.getenv("aio_username") -aio_key = os.getenv("aio_key") - -# If you are using a board with pre-defined ESP32 Pins: -esp32_cs = DigitalInOut(board.ESP_CS) -esp32_ready = DigitalInOut(board.ESP_BUSY) -esp32_reset = DigitalInOut(board.ESP_RESET) - -# If you have an externally connected ESP32: -# esp32_cs = DigitalInOut(board.D9) -# esp32_ready = DigitalInOut(board.D10) -# esp32_reset = DigitalInOut(board.D5) - -spi = busio.SPI(board.SCK, board.MOSI, board.MISO) -esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) -"""Use below for Most Boards""" -status_light = neopixel.NeoPixel( - board.NEOPIXEL, 1, brightness=0.2 -) # Uncomment for Most Boards -"""Uncomment below for ItsyBitsy M4""" -# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) -# Uncomment below for an externally defined RGB LED -# import adafruit_rgbled -# from adafruit_esp32spi import PWMOut -# RED_LED = PWMOut.PWMOut(esp, 26) -# GREEN_LED = PWMOut.PWMOut(esp, 27) -# BLUE_LED = PWMOut.PWMOut(esp, 25) -# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED) - -### Feeds ### - -# Setup a feed named 'photocell' for publishing to a feed -photocell_feed = aio_username + "/feeds/photocell" - -# Setup a feed named 'onoff' for subscribing to changes -onoff_feed = aio_username + "/feeds/onoff" - -### Code ### - - -# Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name -def connected(client, userdata, flags, rc): - # This function will be called when the client is connected - # successfully to the broker. - print("Connected to Adafruit IO! Listening for topic changes on %s" % onoff_feed) - # Subscribe to all changes on the onoff_feed. - client.subscribe(onoff_feed) - - -def disconnected(client, userdata, rc): - # This method is called when the client is disconnected - print("Disconnected from Adafruit IO!") - - -def message(client, topic, message): - # This method is called when a topic the client is subscribed to - # has a new message. - print("New message on topic {0}: {1}".format(topic, message)) - - -# Connect to WiFi -print("Connecting to WiFi...") -esp.connect_AP(os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD")) -print("Connected!") - -pool = adafruit_connection_manager.get_radio_socketpool(esp) -ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp) - -# Set up a MiniMQTT Client -mqtt_client = MQTT.MQTT( - broker="io.adafruit.com", - username=aio_username, - password=aio_key, - socket_pool=pool, - ssl_context=ssl_context, -) - -# Setup the callback methods above -mqtt_client.on_connect = connected -mqtt_client.on_disconnect = disconnected -mqtt_client.on_message = message - -# Connect the client to the MQTT broker. -print("Connecting to Adafruit IO...") -mqtt_client.connect() - -photocell_val = 0 -while True: - # Poll the message queue - mqtt_client.loop() - - # Send a new message - print("Sending photocell value: %d..." % photocell_val) - mqtt_client.publish(photocell_feed, photocell_val) - print("Sent!") - photocell_val += 1 - time.sleep(5) +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + +import os +import time +import board +import busio +from digitalio import DigitalInOut +import neopixel +import adafruit_connection_manager +from adafruit_esp32spi import adafruit_esp32spi + +import adafruit_minimqtt.adafruit_minimqtt as MQTT + +# Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys +# with your WiFi credentials. Add your Adafruit IO username and key as well. +# DO NOT share that file or commit it into Git or other source control. + +aio_username = os.getenv("aio_username") +aio_key = os.getenv("aio_key") + +# If you are using a board with pre-defined ESP32 Pins: +esp32_cs = DigitalInOut(board.ESP_CS) +esp32_ready = DigitalInOut(board.ESP_BUSY) +esp32_reset = DigitalInOut(board.ESP_RESET) + +# If you have an externally connected ESP32: +# esp32_cs = DigitalInOut(board.D9) +# esp32_ready = DigitalInOut(board.D10) +# esp32_reset = DigitalInOut(board.D5) + +spi = busio.SPI(board.SCK, board.MOSI, board.MISO) +esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) +"""Use below for Most Boards""" +status_light = neopixel.NeoPixel( + board.NEOPIXEL, 1, brightness=0.2 +) # Uncomment for Most Boards +"""Uncomment below for ItsyBitsy M4""" +# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) +# Uncomment below for an externally defined RGB LED +# import adafruit_rgbled +# from adafruit_esp32spi import PWMOut +# RED_LED = PWMOut.PWMOut(esp, 26) +# GREEN_LED = PWMOut.PWMOut(esp, 27) +# BLUE_LED = PWMOut.PWMOut(esp, 25) +# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED) + +### Feeds ### + +# Setup a feed named 'photocell' for publishing to a feed +photocell_feed = aio_username + "/feeds/photocell" + +# Setup a feed named 'onoff' for subscribing to changes +onoff_feed = aio_username + "/feeds/onoff" + +### Code ### + + +# Define callback methods which are called when events occur +# pylint: disable=unused-argument, redefined-outer-name +def connected(client, userdata, flags, rc): + # This function will be called when the client is connected + # successfully to the broker. + print("Connected to Adafruit IO! Listening for topic changes on %s" % onoff_feed) + # Subscribe to all changes on the onoff_feed. + client.subscribe(onoff_feed) + + +def disconnected(client, userdata, rc): + # This method is called when the client is disconnected + print("Disconnected from Adafruit IO!") + + +def message(client, topic, message): + # This method is called when a topic the client is subscribed to + # has a new message. + print("New message on topic {0}: {1}".format(topic, message)) + + +# Connect to WiFi +print("Connecting to WiFi...") +esp.connect_AP(os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD")) +print("Connected!") + +pool = adafruit_connection_manager.get_radio_socketpool(esp) +ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp) + +# Set up a MiniMQTT Client +mqtt_client = MQTT.MQTT( + broker="io.adafruit.com", + username=aio_username, + password=aio_key, + socket_pool=pool, + ssl_context=ssl_context, +) + +# Setup the callback methods above +mqtt_client.on_connect = connected +mqtt_client.on_disconnect = disconnected +mqtt_client.on_message = message + +# Connect the client to the MQTT broker. +print("Connecting to Adafruit IO...") +mqtt_client.connect() + +photocell_val = 0 +while True: + # Poll the message queue + mqtt_client.loop() + + # Send a new message + print("Sending photocell value: %d..." % photocell_val) + mqtt_client.publish(photocell_feed, photocell_val) + print("Sent!") + photocell_val += 1 + time.sleep(5) diff --git a/examples/esp32spi/minimqtt_certificate_esp32spi.py b/examples/esp32spi/minimqtt_certificate_esp32spi.py index 4467f8df..9ef019a9 100644 --- a/examples/esp32spi/minimqtt_certificate_esp32spi.py +++ b/examples/esp32spi/minimqtt_certificate_esp32spi.py @@ -1,145 +1,145 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# SPDX-License-Identifier: MIT - -import board -import busio -from digitalio import DigitalInOut -import neopixel -import adafruit_connection_manager -from adafruit_esp32spi import adafruit_esp32spi -from adafruit_esp32spi import adafruit_esp32spi_wifimanager - -import adafruit_minimqtt.adafruit_minimqtt as MQTT - -### WiFi ### - -# 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 - -# If you are using a board with pre-defined ESP32 Pins: -esp32_cs = DigitalInOut(board.ESP_CS) -esp32_ready = DigitalInOut(board.ESP_BUSY) -esp32_reset = DigitalInOut(board.ESP_RESET) - -# If you have an externally connected ESP32: -# esp32_cs = DigitalInOut(board.D9) -# esp32_ready = DigitalInOut(board.D10) -# esp32_reset = DigitalInOut(board.D5) - -spi = busio.SPI(board.SCK, board.MOSI, board.MISO) -esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) -"""Use below for Most Boards""" -status_light = neopixel.NeoPixel( - board.NEOPIXEL, 1, brightness=0.2 -) # Uncomment for Most Boards -"""Uncomment below for ItsyBitsy M4""" -# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) -# Uncomment below for an externally defined RGB LED -# import adafruit_rgbled -# from adafruit_esp32spi import PWMOut -# RED_LED = PWMOut.PWMOut(esp, 26) -# GREEN_LED = PWMOut.PWMOut(esp, 27) -# BLUE_LED = PWMOut.PWMOut(esp, 25) -# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED) -wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light) - -### Topic Setup ### - -# MQTT Topic -# Use this topic if you'd like to connect to a standard MQTT broker -mqtt_topic = "test/topic" - -# Adafruit IO-style Topic -# Use this topic if you'd like to connect to io.adafruit.com -# mqtt_topic = 'aio_user/feeds/temperature' - -### Code ### - - -# Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name -def connect(client, userdata, flags, rc): - # This function will be called when the client is connected - # successfully to the broker. - print("Connected to MQTT Broker!") - print("Flags: {0}\n RC: {1}".format(flags, rc)) - - -def disconnect(client, userdata, rc): - # This method is called when the client disconnects - # from the broker. - print("Disconnected from MQTT Broker!") - - -def subscribe(client, userdata, topic, granted_qos): - # This method is called when the client subscribes to a new feed. - print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) - - -def unsubscribe(client, userdata, topic, pid): - # This method is called when the client unsubscribes from a feed. - print("Unsubscribed from {0} with PID {1}".format(topic, pid)) - - -def publish(client, userdata, topic, pid): - # This method is called when the client publishes data to a feed. - print("Published to {0} with PID {1}".format(topic, pid)) - - -# Get certificate and private key from a certificates.py file -try: - from certificates import DEVICE_CERT, DEVICE_KEY -except ImportError: - print( - "Certificate and private key data is kept in certificates.py, please add them there!" - ) - raise - -# Set Device Certificate -esp.set_certificate(DEVICE_CERT) - -# Set Private Key -esp.set_private_key(DEVICE_KEY) - -# Connect to WiFi -print("Connecting to WiFi...") -wifi.connect() -print("Connected!") - -pool = adafruit_connection_manager.get_radio_socketpool(esp) -ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp) - -# Set up a MiniMQTT Client -client = MQTT.MQTT( - broker=secrets["broker"], - username=secrets["user"], - password=secrets["pass"], - socket_pool=pool, - ssl_context=ssl_context, -) - -# Connect callback handlers to client -client.on_connect = connect -client.on_disconnect = disconnect -client.on_subscribe = subscribe -client.on_unsubscribe = unsubscribe -client.on_publish = publish - -print("Attempting to connect to %s" % client.broker) -client.connect() - -print("Subscribing to %s" % mqtt_topic) -client.subscribe(mqtt_topic) - -print("Publishing to %s" % mqtt_topic) -client.publish(mqtt_topic, "Hello Broker!") - -print("Unsubscribing from %s" % mqtt_topic) -client.unsubscribe(mqtt_topic) - -print("Disconnecting from %s" % client.broker) -client.disconnect() +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + +import board +import busio +from digitalio import DigitalInOut +import neopixel +import adafruit_connection_manager +from adafruit_esp32spi import adafruit_esp32spi +from adafruit_esp32spi import adafruit_esp32spi_wifimanager + +import adafruit_minimqtt.adafruit_minimqtt as MQTT + +### WiFi ### + +# 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 + +# If you are using a board with pre-defined ESP32 Pins: +esp32_cs = DigitalInOut(board.ESP_CS) +esp32_ready = DigitalInOut(board.ESP_BUSY) +esp32_reset = DigitalInOut(board.ESP_RESET) + +# If you have an externally connected ESP32: +# esp32_cs = DigitalInOut(board.D9) +# esp32_ready = DigitalInOut(board.D10) +# esp32_reset = DigitalInOut(board.D5) + +spi = busio.SPI(board.SCK, board.MOSI, board.MISO) +esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) +"""Use below for Most Boards""" +status_light = neopixel.NeoPixel( + board.NEOPIXEL, 1, brightness=0.2 +) # Uncomment for Most Boards +"""Uncomment below for ItsyBitsy M4""" +# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) +# Uncomment below for an externally defined RGB LED +# import adafruit_rgbled +# from adafruit_esp32spi import PWMOut +# RED_LED = PWMOut.PWMOut(esp, 26) +# GREEN_LED = PWMOut.PWMOut(esp, 27) +# BLUE_LED = PWMOut.PWMOut(esp, 25) +# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED) +wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light) + +### Topic Setup ### + +# MQTT Topic +# Use this topic if you'd like to connect to a standard MQTT broker +mqtt_topic = "test/topic" + +# Adafruit IO-style Topic +# Use this topic if you'd like to connect to io.adafruit.com +# mqtt_topic = 'aio_user/feeds/temperature' + +### Code ### + + +# Define callback methods which are called when events occur +# pylint: disable=unused-argument, redefined-outer-name +def connect(client, userdata, flags, rc): + # This function will be called when the client is connected + # successfully to the broker. + print("Connected to MQTT Broker!") + print("Flags: {0}\n RC: {1}".format(flags, rc)) + + +def disconnect(client, userdata, rc): + # This method is called when the client disconnects + # from the broker. + print("Disconnected from MQTT Broker!") + + +def subscribe(client, userdata, topic, granted_qos): + # This method is called when the client subscribes to a new feed. + print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) + + +def unsubscribe(client, userdata, topic, pid): + # This method is called when the client unsubscribes from a feed. + print("Unsubscribed from {0} with PID {1}".format(topic, pid)) + + +def publish(client, userdata, topic, pid): + # This method is called when the client publishes data to a feed. + print("Published to {0} with PID {1}".format(topic, pid)) + + +# Get certificate and private key from a certificates.py file +try: + from certificates import DEVICE_CERT, DEVICE_KEY +except ImportError: + print( + "Certificate and private key data is kept in certificates.py, please add them there!" + ) + raise + +# Set Device Certificate +esp.set_certificate(DEVICE_CERT) + +# Set Private Key +esp.set_private_key(DEVICE_KEY) + +# Connect to WiFi +print("Connecting to WiFi...") +wifi.connect() +print("Connected!") + +pool = adafruit_connection_manager.get_radio_socketpool(esp) +ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp) + +# Set up a MiniMQTT Client +client = MQTT.MQTT( + broker=secrets["broker"], + username=secrets["user"], + password=secrets["pass"], + socket_pool=pool, + ssl_context=ssl_context, +) + +# Connect callback handlers to client +client.on_connect = connect +client.on_disconnect = disconnect +client.on_subscribe = subscribe +client.on_unsubscribe = unsubscribe +client.on_publish = publish + +print("Attempting to connect to %s" % client.broker) +client.connect() + +print("Subscribing to %s" % mqtt_topic) +client.subscribe(mqtt_topic) + +print("Publishing to %s" % mqtt_topic) +client.publish(mqtt_topic, "Hello Broker!") + +print("Unsubscribing from %s" % mqtt_topic) +client.unsubscribe(mqtt_topic) + +print("Disconnecting from %s" % client.broker) +client.disconnect() diff --git a/examples/esp32spi/minimqtt_pub_sub_blocking_esp32spi.py b/examples/esp32spi/minimqtt_pub_sub_blocking_esp32spi.py index e7eed067..7daeec02 100644 --- a/examples/esp32spi/minimqtt_pub_sub_blocking_esp32spi.py +++ b/examples/esp32spi/minimqtt_pub_sub_blocking_esp32spi.py @@ -1,121 +1,121 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# SPDX-License-Identifier: MIT - -import os -import time -import board -import busio -from digitalio import DigitalInOut -import neopixel -import adafruit_connection_manager -from adafruit_esp32spi import adafruit_esp32spi - -import adafruit_minimqtt.adafruit_minimqtt as MQTT - -# Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys -# with your WiFi credentials. Add your Adafruit IO username and key as well. -# DO NOT share that file or commit it into Git or other source control. - -aio_username = os.getenv("aio_username") -aio_key = os.getenv("aio_key") - -# If you are using a board with pre-defined ESP32 Pins: -esp32_cs = DigitalInOut(board.ESP_CS) -esp32_ready = DigitalInOut(board.ESP_BUSY) -esp32_reset = DigitalInOut(board.ESP_RESET) - -# If you have an externally connected ESP32: -# esp32_cs = DigitalInOut(board.D9) -# esp32_ready = DigitalInOut(board.D10) -# esp32_reset = DigitalInOut(board.D5) - -spi = busio.SPI(board.SCK, board.MOSI, board.MISO) -esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) -"""Use below for Most Boards""" -status_light = neopixel.NeoPixel( - board.NEOPIXEL, 1, brightness=0.2 -) # Uncomment for Most Boards -"""Uncomment below for ItsyBitsy M4""" -# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) -# Uncomment below for an externally defined RGB LED -# import adafruit_rgbled -# from adafruit_esp32spi import PWMOut -# RED_LED = PWMOut.PWMOut(esp, 26) -# GREEN_LED = PWMOut.PWMOut(esp, 27) -# BLUE_LED = PWMOut.PWMOut(esp, 25) -# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED) - -### Adafruit IO Setup ### - -# Setup a feed named `testfeed` for publishing. -default_topic = aio_username + "/feeds/testfeed" - -### Code ### - - -# Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name -def connected(client, userdata, flags, rc): - # This function will be called when the client is connected - # successfully to the broker. - print("Connected to MQTT broker! Listening for topic changes on %s" % default_topic) - # Subscribe to all changes on the default_topic feed. - client.subscribe(default_topic) - - -def disconnected(client, userdata, rc): - # This method is called when the client is disconnected - print("Disconnected from MQTT Broker!") - - -def message(client, topic, message): - """Method callled when a client's subscribed feed has a new - value. - :param str topic: The topic of the feed with a new value. - :param str message: The new value - """ - print("New message on topic {0}: {1}".format(topic, message)) - - -# Connect to WiFi -print("Connecting to WiFi...") -esp.connect_AP(os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD")) -print("Connected!") - -pool = adafruit_connection_manager.get_radio_socketpool(esp) -ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp) - -# Set up a MiniMQTT Client -mqtt_client = MQTT.MQTT( - broker="io.adafruit.com", - username=aio_username, - password=aio_key, - socket_pool=pool, - ssl_context=ssl_context, -) - -# Setup the callback methods above -mqtt_client.on_connect = connected -mqtt_client.on_disconnect = disconnected -mqtt_client.on_message = message - -# Connect the client to the MQTT broker. -print("Connecting to MQTT broker...") -mqtt_client.connect() - -# Start a blocking message loop... -# NOTE: NO code below this loop will execute -# NOTE: Network reconnection is handled within this loop -while True: - try: - mqtt_client.loop() - except (ValueError, RuntimeError) as e: - print("Failed to get data, retrying\n", e) - esp.reset() - time.sleep(1) - esp.connect_AP( - os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD") - ) - mqtt_client.reconnect() - continue - time.sleep(1) +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + +import os +import time +import board +import busio +from digitalio import DigitalInOut +import neopixel +import adafruit_connection_manager +from adafruit_esp32spi import adafruit_esp32spi + +import adafruit_minimqtt.adafruit_minimqtt as MQTT + +# Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys +# with your WiFi credentials. Add your Adafruit IO username and key as well. +# DO NOT share that file or commit it into Git or other source control. + +aio_username = os.getenv("aio_username") +aio_key = os.getenv("aio_key") + +# If you are using a board with pre-defined ESP32 Pins: +esp32_cs = DigitalInOut(board.ESP_CS) +esp32_ready = DigitalInOut(board.ESP_BUSY) +esp32_reset = DigitalInOut(board.ESP_RESET) + +# If you have an externally connected ESP32: +# esp32_cs = DigitalInOut(board.D9) +# esp32_ready = DigitalInOut(board.D10) +# esp32_reset = DigitalInOut(board.D5) + +spi = busio.SPI(board.SCK, board.MOSI, board.MISO) +esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) +"""Use below for Most Boards""" +status_light = neopixel.NeoPixel( + board.NEOPIXEL, 1, brightness=0.2 +) # Uncomment for Most Boards +"""Uncomment below for ItsyBitsy M4""" +# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) +# Uncomment below for an externally defined RGB LED +# import adafruit_rgbled +# from adafruit_esp32spi import PWMOut +# RED_LED = PWMOut.PWMOut(esp, 26) +# GREEN_LED = PWMOut.PWMOut(esp, 27) +# BLUE_LED = PWMOut.PWMOut(esp, 25) +# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED) + +### Adafruit IO Setup ### + +# Setup a feed named `testfeed` for publishing. +default_topic = aio_username + "/feeds/testfeed" + +### Code ### + + +# Define callback methods which are called when events occur +# pylint: disable=unused-argument, redefined-outer-name +def connected(client, userdata, flags, rc): + # This function will be called when the client is connected + # successfully to the broker. + print("Connected to MQTT broker! Listening for topic changes on %s" % default_topic) + # Subscribe to all changes on the default_topic feed. + client.subscribe(default_topic) + + +def disconnected(client, userdata, rc): + # This method is called when the client is disconnected + print("Disconnected from MQTT Broker!") + + +def message(client, topic, message): + """Method callled when a client's subscribed feed has a new + value. + :param str topic: The topic of the feed with a new value. + :param str message: The new value + """ + print("New message on topic {0}: {1}".format(topic, message)) + + +# Connect to WiFi +print("Connecting to WiFi...") +esp.connect_AP(os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD")) +print("Connected!") + +pool = adafruit_connection_manager.get_radio_socketpool(esp) +ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp) + +# Set up a MiniMQTT Client +mqtt_client = MQTT.MQTT( + broker="io.adafruit.com", + username=aio_username, + password=aio_key, + socket_pool=pool, + ssl_context=ssl_context, +) + +# Setup the callback methods above +mqtt_client.on_connect = connected +mqtt_client.on_disconnect = disconnected +mqtt_client.on_message = message + +# Connect the client to the MQTT broker. +print("Connecting to MQTT broker...") +mqtt_client.connect() + +# Start a blocking message loop... +# NOTE: NO code below this loop will execute +# NOTE: Network reconnection is handled within this loop +while True: + try: + mqtt_client.loop() + except (ValueError, RuntimeError) as e: + print("Failed to get data, retrying\n", e) + esp.reset() + time.sleep(1) + esp.connect_AP( + os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD") + ) + mqtt_client.reconnect() + continue + time.sleep(1) diff --git a/examples/esp32spi/minimqtt_pub_sub_blocking_topic_callbacks_esp32spi.py b/examples/esp32spi/minimqtt_pub_sub_blocking_topic_callbacks_esp32spi.py index cb89ed17..96cb0fa0 100644 --- a/examples/esp32spi/minimqtt_pub_sub_blocking_topic_callbacks_esp32spi.py +++ b/examples/esp32spi/minimqtt_pub_sub_blocking_topic_callbacks_esp32spi.py @@ -1,133 +1,133 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# SPDX-License-Identifier: MIT - -import os -import time -import board -import busio -from digitalio import DigitalInOut -import neopixel -import adafruit_connection_manager -from adafruit_esp32spi import adafruit_esp32spi -from adafruit_esp32spi import adafruit_esp32spi_wifimanager - -import adafruit_minimqtt.adafruit_minimqtt as MQTT - -### WiFi ### - -# 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 - -# If you are using a board with pre-defined ESP32 Pins: -esp32_cs = DigitalInOut(board.ESP_CS) -esp32_ready = DigitalInOut(board.ESP_BUSY) -esp32_reset = DigitalInOut(board.ESP_RESET) - -# If you have an externally connected ESP32: -# esp32_cs = DigitalInOut(board.D9) -# esp32_ready = DigitalInOut(board.D10) -# esp32_reset = DigitalInOut(board.D5) - -spi = busio.SPI(board.SCK, board.MOSI, board.MISO) -esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) -"""Use below for Most Boards""" -status_light = neopixel.NeoPixel( - board.NEOPIXEL, 1, brightness=0.2 -) # Uncomment for Most Boards -"""Uncomment below for ItsyBitsy M4""" -# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) -# Uncomment below for an externally defined RGB LED -# import adafruit_rgbled -# from adafruit_esp32spi import PWMOut -# RED_LED = PWMOut.PWMOut(esp, 26) -# GREEN_LED = PWMOut.PWMOut(esp, 27) -# BLUE_LED = PWMOut.PWMOut(esp, 25) -# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED) -wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light) - -### Code ### - - -# Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name -def connected(client, userdata, flags, rc): - # This function will be called when the client is connected - # successfully to the broker. - print("Connected to MQTT Broker!") - - -def disconnected(client, userdata, rc): - # This method is called when the client is disconnected - print("Disconnected from MQTT Broker!") - - -def subscribe(client, userdata, topic, granted_qos): - # This method is called when the client subscribes to a new feed. - print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) - - -def unsubscribe(client, userdata, topic, pid): - # This method is called when the client unsubscribes from a feed. - print("Unsubscribed from {0} with PID {1}".format(topic, pid)) - - -def on_battery_msg(client, topic, message): - # Method called when device/batteryLife has a new value - print("Battery level: {}v".format(message)) - - # client.remove_topic_callback(secrets["aio_username"] + "/feeds/device.batterylevel") - - -def on_message(client, topic, message): - # Method callled when a client's subscribed feed has a new value. - print("New message on topic {0}: {1}".format(topic, message)) - - -# Connect to WiFi -print("Connecting to WiFi...") -wifi.connect() -print("Connected!") - -pool = adafruit_connection_manager.get_radio_socketpool(esp) -ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp) - -# Set up a MiniMQTT Client -client = MQTT.MQTT( - broker=os.getenv("broker"), - port=os.getenv("broker_port"), - socket_pool=pool, - ssl_context=ssl_context, -) - -# Setup the callback methods above -client.on_connect = connected -client.on_disconnect = disconnected -client.on_subscribe = subscribe -client.on_unsubscribe = unsubscribe -client.on_message = on_message -client.add_topic_callback( - secrets["aio_username"] + "/feeds/device.batterylevel", on_battery_msg -) - -# Connect the client to the MQTT broker. -print("Connecting to MQTT broker...") -client.connect() - -# Subscribe to all notifications on the device group -client.subscribe(secrets["aio_username"] + "/groups/device", 1) - -# Start a blocking message loop... -# NOTE: NO code below this loop will execute -while True: - try: - client.loop() - except (ValueError, RuntimeError) as e: - print("Failed to get data, retrying\n", e) - wifi.reset() - client.reconnect() - continue - time.sleep(1) +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + +import os +import time +import board +import busio +from digitalio import DigitalInOut +import neopixel +import adafruit_connection_manager +from adafruit_esp32spi import adafruit_esp32spi +from adafruit_esp32spi import adafruit_esp32spi_wifimanager + +import adafruit_minimqtt.adafruit_minimqtt as MQTT + +### WiFi ### + +# 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 + +# If you are using a board with pre-defined ESP32 Pins: +esp32_cs = DigitalInOut(board.ESP_CS) +esp32_ready = DigitalInOut(board.ESP_BUSY) +esp32_reset = DigitalInOut(board.ESP_RESET) + +# If you have an externally connected ESP32: +# esp32_cs = DigitalInOut(board.D9) +# esp32_ready = DigitalInOut(board.D10) +# esp32_reset = DigitalInOut(board.D5) + +spi = busio.SPI(board.SCK, board.MOSI, board.MISO) +esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) +"""Use below for Most Boards""" +status_light = neopixel.NeoPixel( + board.NEOPIXEL, 1, brightness=0.2 +) # Uncomment for Most Boards +"""Uncomment below for ItsyBitsy M4""" +# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) +# Uncomment below for an externally defined RGB LED +# import adafruit_rgbled +# from adafruit_esp32spi import PWMOut +# RED_LED = PWMOut.PWMOut(esp, 26) +# GREEN_LED = PWMOut.PWMOut(esp, 27) +# BLUE_LED = PWMOut.PWMOut(esp, 25) +# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED) +wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(esp, secrets, status_light) + +### Code ### + + +# Define callback methods which are called when events occur +# pylint: disable=unused-argument, redefined-outer-name +def connected(client, userdata, flags, rc): + # This function will be called when the client is connected + # successfully to the broker. + print("Connected to MQTT Broker!") + + +def disconnected(client, userdata, rc): + # This method is called when the client is disconnected + print("Disconnected from MQTT Broker!") + + +def subscribe(client, userdata, topic, granted_qos): + # This method is called when the client subscribes to a new feed. + print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) + + +def unsubscribe(client, userdata, topic, pid): + # This method is called when the client unsubscribes from a feed. + print("Unsubscribed from {0} with PID {1}".format(topic, pid)) + + +def on_battery_msg(client, topic, message): + # Method called when device/batteryLife has a new value + print("Battery level: {}v".format(message)) + + # client.remove_topic_callback(secrets["aio_username"] + "/feeds/device.batterylevel") + + +def on_message(client, topic, message): + # Method callled when a client's subscribed feed has a new value. + print("New message on topic {0}: {1}".format(topic, message)) + + +# Connect to WiFi +print("Connecting to WiFi...") +wifi.connect() +print("Connected!") + +pool = adafruit_connection_manager.get_radio_socketpool(esp) +ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp) + +# Set up a MiniMQTT Client +client = MQTT.MQTT( + broker=os.getenv("broker"), + port=os.getenv("broker_port"), + socket_pool=pool, + ssl_context=ssl_context, +) + +# Setup the callback methods above +client.on_connect = connected +client.on_disconnect = disconnected +client.on_subscribe = subscribe +client.on_unsubscribe = unsubscribe +client.on_message = on_message +client.add_topic_callback( + secrets["aio_username"] + "/feeds/device.batterylevel", on_battery_msg +) + +# Connect the client to the MQTT broker. +print("Connecting to MQTT broker...") +client.connect() + +# Subscribe to all notifications on the device group +client.subscribe(secrets["aio_username"] + "/groups/device", 1) + +# Start a blocking message loop... +# NOTE: NO code below this loop will execute +while True: + try: + client.loop() + except (ValueError, RuntimeError) as e: + print("Failed to get data, retrying\n", e) + wifi.reset() + client.reconnect() + continue + time.sleep(1) diff --git a/examples/esp32spi/minimqtt_pub_sub_nonblocking_esp32spi.py b/examples/esp32spi/minimqtt_pub_sub_nonblocking_esp32spi.py index 20191915..1f8c79ca 100644 --- a/examples/esp32spi/minimqtt_pub_sub_nonblocking_esp32spi.py +++ b/examples/esp32spi/minimqtt_pub_sub_nonblocking_esp32spi.py @@ -1,113 +1,113 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# SPDX-License-Identifier: MIT - -import os -import time -import board -import busio -from digitalio import DigitalInOut -import neopixel -import adafruit_connection_manager -from adafruit_esp32spi import adafruit_esp32spi - -import adafruit_minimqtt.adafruit_minimqtt as MQTT - -# Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys -# with your WiFi credentials. Add your Adafruit IO username and key as well. -# DO NOT share that file or commit it into Git or other source control. - -aio_username = os.getenv("aio_username") -aio_key = os.getenv("aio_key") - -# If you are using a board with pre-defined ESP32 Pins: -esp32_cs = DigitalInOut(board.ESP_CS) -esp32_ready = DigitalInOut(board.ESP_BUSY) -esp32_reset = DigitalInOut(board.ESP_RESET) - -# If you have an externally connected ESP32: -# esp32_cs = DigitalInOut(board.D9) -# esp32_ready = DigitalInOut(board.D10) -# esp32_reset = DigitalInOut(board.D5) - -spi = busio.SPI(board.SCK, board.MOSI, board.MISO) -esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) -"""Use below for Most Boards""" -status_light = neopixel.NeoPixel( - board.NEOPIXEL, 1, brightness=0.2 -) # Uncomment for Most Boards -"""Uncomment below for ItsyBitsy M4""" -# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) -# Uncomment below for an externally defined RGB LED -# import adafruit_rgbled -# from adafruit_esp32spi import PWMOut -# RED_LED = PWMOut.PWMOut(esp, 26) -# GREEN_LED = PWMOut.PWMOut(esp, 27) -# BLUE_LED = PWMOut.PWMOut(esp, 25) -# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED) - -### Adafruit IO Setup ### - -# Setup a feed named `testfeed` for publishing. -default_topic = aio_username + "/feeds/testfeed" - - -### Code ### -# Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name -def connected(client, userdata, flags, rc): - # This function will be called when the client is connected - # successfully to the broker. - print(f"Connected to MQTT broker! Listening for topic changes on {default_topic}") - # Subscribe to all changes on the default_topic feed. - client.subscribe(default_topic) - - -def disconnected(client, userdata, rc): - # This method is called when the client is disconnected - print("Disconnected from MQTT Broker!") - - -def message(client, topic, message): - """Method callled when a client's subscribed feed has a new - value. - :param str topic: The topic of the feed with a new value. - :param str message: The new value - """ - print(f"New message on topic {topic}: {message}") - - -# Connect to WiFi -print("Connecting to WiFi...") -esp.connect_AP(os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD")) -print("Connected!") - -pool = adafruit_connection_manager.get_radio_socketpool(esp) -ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp) - -# Set up a MiniMQTT Client -mqtt_client = MQTT.MQTT( - broker="io.adafruit.com", - username=aio_username, - password=aio_key, - socket_pool=pool, - ssl_context=ssl_context, -) - -# Setup the callback methods above -mqtt_client.on_connect = connected -mqtt_client.on_disconnect = disconnected -mqtt_client.on_message = message - -# Connect the client to the MQTT broker. -mqtt_client.connect() - -photocell_val = 0 -while True: - # Poll the message queue - mqtt_client.loop() - - # Send a new message - print(f"Sending photocell value: {photocell_val}") - mqtt_client.publish(default_topic, photocell_val) - photocell_val += 1 - time.sleep(3) +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + +import os +import time +import board +import busio +from digitalio import DigitalInOut +import neopixel +import adafruit_connection_manager +from adafruit_esp32spi import adafruit_esp32spi + +import adafruit_minimqtt.adafruit_minimqtt as MQTT + +# Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys +# with your WiFi credentials. Add your Adafruit IO username and key as well. +# DO NOT share that file or commit it into Git or other source control. + +aio_username = os.getenv("aio_username") +aio_key = os.getenv("aio_key") + +# If you are using a board with pre-defined ESP32 Pins: +esp32_cs = DigitalInOut(board.ESP_CS) +esp32_ready = DigitalInOut(board.ESP_BUSY) +esp32_reset = DigitalInOut(board.ESP_RESET) + +# If you have an externally connected ESP32: +# esp32_cs = DigitalInOut(board.D9) +# esp32_ready = DigitalInOut(board.D10) +# esp32_reset = DigitalInOut(board.D5) + +spi = busio.SPI(board.SCK, board.MOSI, board.MISO) +esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) +"""Use below for Most Boards""" +status_light = neopixel.NeoPixel( + board.NEOPIXEL, 1, brightness=0.2 +) # Uncomment for Most Boards +"""Uncomment below for ItsyBitsy M4""" +# status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=0.2) +# Uncomment below for an externally defined RGB LED +# import adafruit_rgbled +# from adafruit_esp32spi import PWMOut +# RED_LED = PWMOut.PWMOut(esp, 26) +# GREEN_LED = PWMOut.PWMOut(esp, 27) +# BLUE_LED = PWMOut.PWMOut(esp, 25) +# status_light = adafruit_rgbled.RGBLED(RED_LED, BLUE_LED, GREEN_LED) + +### Adafruit IO Setup ### + +# Setup a feed named `testfeed` for publishing. +default_topic = aio_username + "/feeds/testfeed" + + +### Code ### +# Define callback methods which are called when events occur +# pylint: disable=unused-argument, redefined-outer-name +def connected(client, userdata, flags, rc): + # This function will be called when the client is connected + # successfully to the broker. + print(f"Connected to MQTT broker! Listening for topic changes on {default_topic}") + # Subscribe to all changes on the default_topic feed. + client.subscribe(default_topic) + + +def disconnected(client, userdata, rc): + # This method is called when the client is disconnected + print("Disconnected from MQTT Broker!") + + +def message(client, topic, message): + """Method callled when a client's subscribed feed has a new + value. + :param str topic: The topic of the feed with a new value. + :param str message: The new value + """ + print(f"New message on topic {topic}: {message}") + + +# Connect to WiFi +print("Connecting to WiFi...") +esp.connect_AP(os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD")) +print("Connected!") + +pool = adafruit_connection_manager.get_radio_socketpool(esp) +ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp) + +# Set up a MiniMQTT Client +mqtt_client = MQTT.MQTT( + broker="io.adafruit.com", + username=aio_username, + password=aio_key, + socket_pool=pool, + ssl_context=ssl_context, +) + +# Setup the callback methods above +mqtt_client.on_connect = connected +mqtt_client.on_disconnect = disconnected +mqtt_client.on_message = message + +# Connect the client to the MQTT broker. +mqtt_client.connect() + +photocell_val = 0 +while True: + # Poll the message queue + mqtt_client.loop() + + # Send a new message + print(f"Sending photocell value: {photocell_val}") + mqtt_client.publish(default_topic, photocell_val) + photocell_val += 1 + time.sleep(3) diff --git a/examples/esp32spi/minimqtt_pub_sub_pyportal_esp32spi.py b/examples/esp32spi/minimqtt_pub_sub_pyportal_esp32spi.py index 3db02803..ec67f9c4 100644 --- a/examples/esp32spi/minimqtt_pub_sub_pyportal_esp32spi.py +++ b/examples/esp32spi/minimqtt_pub_sub_pyportal_esp32spi.py @@ -1,86 +1,86 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# SPDX-License-Identifier: MIT - -import os -import time -import adafruit_connection_manager -import adafruit_pyportal - -import adafruit_minimqtt.adafruit_minimqtt as MQTT - -pyportal = adafruit_pyportal.PyPortal() - -# Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys -# with your WiFi credentials. Add your Adafruit IO username and key as well. -# DO NOT share that file or commit it into Git or other source control. - -aio_username = os.getenv("aio_username") -aio_key = os.getenv("aio_key") - -# ------------- MQTT Topic Setup ------------- # -mqtt_topic = "test/topic" - - -### Code ### -# Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name -def connected(client, userdata, flags, rc): - # This function will be called when the client is connected - # successfully to the broker. - print("Subscribing to %s" % (mqtt_topic)) - client.subscribe(mqtt_topic) - - -def disconnected(client, userdata, rc): - # This method is called when the client is disconnected - print("Disconnected from MQTT Broker!") - - -def message(client, topic, message): - """Method callled when a client's subscribed feed has a new - value. - :param str topic: The topic of the feed with a new value. - :param str message: The new value - """ - print("New message on topic {0}: {1}".format(topic, message)) - - -# Connect to WiFi -print("Connecting to WiFi...") -pyportal.network.connect() -print("Connected!") - -# pylint: disable=protected-access -pool = adafruit_connection_manager.get_radio_socketpool(pyportal.network._wifi.esp) -ssl_context = adafruit_connection_manager.get_radio_ssl_context( - pyportal.network._wifi.esp -) - -# Set up a MiniMQTT Client -mqtt_client = MQTT.MQTT( - broker=os.getenv("broker"), - username=os.getenv("username"), - password=os.getenv("password"), - is_ssl=False, - socket_pool=pool, - ssl_context=ssl_context, -) - -# Setup the callback methods above -mqtt_client.on_connect = connected -mqtt_client.on_disconnect = disconnected -mqtt_client.on_message = message - -# Connect the client to the MQTT broker. -mqtt_client.connect() - -photocell_val = 0 -while True: - # Poll the message queue - mqtt_client.loop() - - # Send a new message - print("Sending photocell value: %d" % photocell_val) - mqtt_client.publish(mqtt_topic, photocell_val) - photocell_val += 1 - time.sleep(1) +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + +import os +import time +import adafruit_connection_manager +import adafruit_pyportal + +import adafruit_minimqtt.adafruit_minimqtt as MQTT + +pyportal = adafruit_pyportal.PyPortal() + +# Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys +# with your WiFi credentials. Add your Adafruit IO username and key as well. +# DO NOT share that file or commit it into Git or other source control. + +aio_username = os.getenv("aio_username") +aio_key = os.getenv("aio_key") + +# ------------- MQTT Topic Setup ------------- # +mqtt_topic = "test/topic" + + +### Code ### +# Define callback methods which are called when events occur +# pylint: disable=unused-argument, redefined-outer-name +def connected(client, userdata, flags, rc): + # This function will be called when the client is connected + # successfully to the broker. + print("Subscribing to %s" % (mqtt_topic)) + client.subscribe(mqtt_topic) + + +def disconnected(client, userdata, rc): + # This method is called when the client is disconnected + print("Disconnected from MQTT Broker!") + + +def message(client, topic, message): + """Method callled when a client's subscribed feed has a new + value. + :param str topic: The topic of the feed with a new value. + :param str message: The new value + """ + print("New message on topic {0}: {1}".format(topic, message)) + + +# Connect to WiFi +print("Connecting to WiFi...") +pyportal.network.connect() +print("Connected!") + +# pylint: disable=protected-access +pool = adafruit_connection_manager.get_radio_socketpool(pyportal.network._wifi.esp) +ssl_context = adafruit_connection_manager.get_radio_ssl_context( + pyportal.network._wifi.esp +) + +# Set up a MiniMQTT Client +mqtt_client = MQTT.MQTT( + broker=os.getenv("broker"), + username=os.getenv("username"), + password=os.getenv("password"), + is_ssl=False, + socket_pool=pool, + ssl_context=ssl_context, +) + +# Setup the callback methods above +mqtt_client.on_connect = connected +mqtt_client.on_disconnect = disconnected +mqtt_client.on_message = message + +# Connect the client to the MQTT broker. +mqtt_client.connect() + +photocell_val = 0 +while True: + # Poll the message queue + mqtt_client.loop() + + # Send a new message + print("Sending photocell value: %d" % photocell_val) + mqtt_client.publish(mqtt_topic, photocell_val) + photocell_val += 1 + time.sleep(1) diff --git a/examples/esp32spi/minimqtt_simpletest_esp32spi.py b/examples/esp32spi/minimqtt_simpletest_esp32spi.py index a1cc2712..fd407f30 100644 --- a/examples/esp32spi/minimqtt_simpletest_esp32spi.py +++ b/examples/esp32spi/minimqtt_simpletest_esp32spi.py @@ -1,122 +1,122 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# SPDX-License-Identifier: MIT - -import os -import board -import busio -from digitalio import DigitalInOut -import adafruit_connection_manager -from adafruit_esp32spi import adafruit_esp32spi -import adafruit_minimqtt.adafruit_minimqtt as MQTT - -# Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys -# with your WiFi credentials. Add your Adafruit IO username and key as well. -# DO NOT share that file or commit it into Git or other source control. - -aio_username = os.getenv("aio_username") -aio_key = os.getenv("aio_key") - -# If you are using a board with pre-defined ESP32 Pins: -esp32_cs = DigitalInOut(board.ESP_CS) -esp32_ready = DigitalInOut(board.ESP_BUSY) -esp32_reset = DigitalInOut(board.ESP_RESET) - -# If you have an externally connected ESP32: -# esp32_cs = DigitalInOut(board.D9) -# esp32_ready = DigitalInOut(board.D10) -# esp32_reset = DigitalInOut(board.D5) - -spi = busio.SPI(board.SCK, board.MOSI, board.MISO) -esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) - -print("Connecting to AP...") -while not esp.is_connected: - try: - esp.connect_AP(os.getenv("ssid"), os.getenv("password")) - except RuntimeError as e: - print("could not connect to AP, retrying: ", e) - continue -print("Connected to", str(esp.ssid, "utf-8"), "\tRSSI:", esp.rssi) - -### Topic Setup ### - -# MQTT Topic -# Use this topic if you'd like to connect to a standard MQTT broker -mqtt_topic = "test/topic" - -# Adafruit IO-style Topic -# Use this topic if you'd like to connect to io.adafruit.com -# mqtt_topic = aio_username + '/feeds/temperature' - -### Code ### - - -# Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name -def connect(mqtt_client, userdata, flags, rc): - # This function will be called when the mqtt_client is connected - # successfully to the broker. - print("Connected to MQTT Broker!") - print("Flags: {0}\n RC: {1}".format(flags, rc)) - - -def disconnect(mqtt_client, userdata, rc): - # This method is called when the mqtt_client disconnects - # from the broker. - print("Disconnected from MQTT Broker!") - - -def subscribe(mqtt_client, userdata, topic, granted_qos): - # This method is called when the mqtt_client subscribes to a new feed. - print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) - - -def unsubscribe(mqtt_client, userdata, topic, pid): - # This method is called when the mqtt_client unsubscribes from a feed. - print("Unsubscribed from {0} with PID {1}".format(topic, pid)) - - -def publish(mqtt_client, userdata, topic, pid): - # This method is called when the mqtt_client publishes data to a feed. - print("Published to {0} with PID {1}".format(topic, pid)) - - -def message(client, topic, message): - print("New message on topic {0}: {1}".format(topic, message)) - - -pool = adafruit_connection_manager.get_radio_socketpool(esp) -ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp) - -# Set up a MiniMQTT Client -mqtt_client = MQTT.MQTT( - broker=os.getenv("broker"), - port=os.getenv("port"), - username=os.getenv("username"), - password=os.getenv("password"), - socket_pool=pool, - ssl_context=ssl_context, -) - -# Connect callback handlers to mqtt_client -mqtt_client.on_connect = connect -mqtt_client.on_disconnect = disconnect -mqtt_client.on_subscribe = subscribe -mqtt_client.on_unsubscribe = unsubscribe -mqtt_client.on_publish = publish -mqtt_client.on_message = message - -print("Attempting to connect to %s" % mqtt_client.broker) -mqtt_client.connect() - -print("Subscribing to %s" % mqtt_topic) -mqtt_client.subscribe(mqtt_topic) - -print("Publishing to %s" % mqtt_topic) -mqtt_client.publish(mqtt_topic, "Hello Broker!") - -print("Unsubscribing from %s" % mqtt_topic) -mqtt_client.unsubscribe(mqtt_topic) - -print("Disconnecting from %s" % mqtt_client.broker) -mqtt_client.disconnect() +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + +import os +import board +import busio +from digitalio import DigitalInOut +import adafruit_connection_manager +from adafruit_esp32spi import adafruit_esp32spi +import adafruit_minimqtt.adafruit_minimqtt as MQTT + +# Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys +# with your WiFi credentials. Add your Adafruit IO username and key as well. +# DO NOT share that file or commit it into Git or other source control. + +aio_username = os.getenv("aio_username") +aio_key = os.getenv("aio_key") + +# If you are using a board with pre-defined ESP32 Pins: +esp32_cs = DigitalInOut(board.ESP_CS) +esp32_ready = DigitalInOut(board.ESP_BUSY) +esp32_reset = DigitalInOut(board.ESP_RESET) + +# If you have an externally connected ESP32: +# esp32_cs = DigitalInOut(board.D9) +# esp32_ready = DigitalInOut(board.D10) +# esp32_reset = DigitalInOut(board.D5) + +spi = busio.SPI(board.SCK, board.MOSI, board.MISO) +esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) + +print("Connecting to AP...") +while not esp.is_connected: + try: + esp.connect_AP(os.getenv("ssid"), os.getenv("password")) + except RuntimeError as e: + print("could not connect to AP, retrying: ", e) + continue +print("Connected to", str(esp.ssid, "utf-8"), "\tRSSI:", esp.rssi) + +### Topic Setup ### + +# MQTT Topic +# Use this topic if you'd like to connect to a standard MQTT broker +mqtt_topic = "test/topic" + +# Adafruit IO-style Topic +# Use this topic if you'd like to connect to io.adafruit.com +# mqtt_topic = aio_username + '/feeds/temperature' + +### Code ### + + +# Define callback methods which are called when events occur +# pylint: disable=unused-argument, redefined-outer-name +def connect(mqtt_client, userdata, flags, rc): + # This function will be called when the mqtt_client is connected + # successfully to the broker. + print("Connected to MQTT Broker!") + print("Flags: {0}\n RC: {1}".format(flags, rc)) + + +def disconnect(mqtt_client, userdata, rc): + # This method is called when the mqtt_client disconnects + # from the broker. + print("Disconnected from MQTT Broker!") + + +def subscribe(mqtt_client, userdata, topic, granted_qos): + # This method is called when the mqtt_client subscribes to a new feed. + print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) + + +def unsubscribe(mqtt_client, userdata, topic, pid): + # This method is called when the mqtt_client unsubscribes from a feed. + print("Unsubscribed from {0} with PID {1}".format(topic, pid)) + + +def publish(mqtt_client, userdata, topic, pid): + # This method is called when the mqtt_client publishes data to a feed. + print("Published to {0} with PID {1}".format(topic, pid)) + + +def message(client, topic, message): + print("New message on topic {0}: {1}".format(topic, message)) + + +pool = adafruit_connection_manager.get_radio_socketpool(esp) +ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp) + +# Set up a MiniMQTT Client +mqtt_client = MQTT.MQTT( + broker=os.getenv("broker"), + port=os.getenv("port"), + username=os.getenv("username"), + password=os.getenv("password"), + socket_pool=pool, + ssl_context=ssl_context, +) + +# Connect callback handlers to mqtt_client +mqtt_client.on_connect = connect +mqtt_client.on_disconnect = disconnect +mqtt_client.on_subscribe = subscribe +mqtt_client.on_unsubscribe = unsubscribe +mqtt_client.on_publish = publish +mqtt_client.on_message = message + +print("Attempting to connect to %s" % mqtt_client.broker) +mqtt_client.connect() + +print("Subscribing to %s" % mqtt_topic) +mqtt_client.subscribe(mqtt_topic) + +print("Publishing to %s" % mqtt_topic) +mqtt_client.publish(mqtt_topic, "Hello Broker!") + +print("Unsubscribing from %s" % mqtt_topic) +mqtt_client.unsubscribe(mqtt_topic) + +print("Disconnecting from %s" % mqtt_client.broker) +mqtt_client.disconnect() diff --git a/examples/ethernet/minimqtt_adafruitio_eth.py b/examples/ethernet/minimqtt_adafruitio_eth.py index 5ad677dd..6b5b465b 100755 --- a/examples/ethernet/minimqtt_adafruitio_eth.py +++ b/examples/ethernet/minimqtt_adafruitio_eth.py @@ -1,91 +1,91 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# SPDX-License-Identifier: MIT - -import os -import time -import board -import busio -from digitalio import DigitalInOut -import adafruit_connection_manager -from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET5K - -import adafruit_minimqtt.adafruit_minimqtt as MQTT - -# Add settings.toml to your filesystem. Add your Adafruit IO username and key as well. -# DO NOT share that file or commit it into Git or other source control. - -aio_username = os.getenv("aio_username") -aio_key = os.getenv("aio_key") - -cs = DigitalInOut(board.D10) -spi_bus = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) - -# Initialize ethernet interface with DHCP -eth = WIZNET5K(spi_bus, cs) - -### Feeds ### - -# Setup a feed named 'photocell' for publishing to a feed -photocell_feed = aio_username + "/feeds/photocell" - -# Setup a feed named 'onoff' for subscribing to changes -onoff_feed = aio_username + "/feeds/onoff" - -### Code ### - - -# Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name -def connected(client, userdata, flags, rc): - # This function will be called when the client is connected - # successfully to the broker. - print("Connected to Adafruit IO! Listening for topic changes on %s" % onoff_feed) - # Subscribe to all changes on the onoff_feed. - client.subscribe(onoff_feed) - - -def disconnected(client, userdata, rc): - # This method is called when the client is disconnected - print("Disconnected from Adafruit IO!") - - -def message(client, topic, message): - # This method is called when a topic the client is subscribed to - # has a new message. - print("New message on topic {0}: {1}".format(topic, message)) - - -pool = adafruit_connection_manager.get_radio_socketpool(eth) -ssl_context = adafruit_connection_manager.get_radio_ssl_context(eth) - -# Set up a MiniMQTT Client -# NOTE: We'll need to connect insecurely for ethernet configurations. -mqtt_client = MQTT.MQTT( - broker="io.adafruit.com", - username=aio_username, - password=aio_key, - is_ssl=False, - socket_pool=pool, - ssl_context=ssl_context, -) - -# Setup the callback methods above -mqtt_client.on_connect = connected -mqtt_client.on_disconnect = disconnected -mqtt_client.on_message = message - -# Connect the client to the MQTT broker. -print("Connecting to Adafruit IO...") -mqtt_client.connect() - -photocell_val = 0 -while True: - # Poll the message queue - mqtt_client.loop() - - # Send a new message - print("Sending photocell value: %d..." % photocell_val) - mqtt_client.publish(photocell_feed, photocell_val) - print("Sent!") - photocell_val += 1 - time.sleep(5) +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + +import os +import time +import board +import busio +from digitalio import DigitalInOut +import adafruit_connection_manager +from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET5K + +import adafruit_minimqtt.adafruit_minimqtt as MQTT + +# Add settings.toml to your filesystem. Add your Adafruit IO username and key as well. +# DO NOT share that file or commit it into Git or other source control. + +aio_username = os.getenv("aio_username") +aio_key = os.getenv("aio_key") + +cs = DigitalInOut(board.D10) +spi_bus = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) + +# Initialize ethernet interface with DHCP +eth = WIZNET5K(spi_bus, cs) + +### Feeds ### + +# Setup a feed named 'photocell' for publishing to a feed +photocell_feed = aio_username + "/feeds/photocell" + +# Setup a feed named 'onoff' for subscribing to changes +onoff_feed = aio_username + "/feeds/onoff" + +### Code ### + + +# Define callback methods which are called when events occur +# pylint: disable=unused-argument, redefined-outer-name +def connected(client, userdata, flags, rc): + # This function will be called when the client is connected + # successfully to the broker. + print("Connected to Adafruit IO! Listening for topic changes on %s" % onoff_feed) + # Subscribe to all changes on the onoff_feed. + client.subscribe(onoff_feed) + + +def disconnected(client, userdata, rc): + # This method is called when the client is disconnected + print("Disconnected from Adafruit IO!") + + +def message(client, topic, message): + # This method is called when a topic the client is subscribed to + # has a new message. + print("New message on topic {0}: {1}".format(topic, message)) + + +pool = adafruit_connection_manager.get_radio_socketpool(eth) +ssl_context = adafruit_connection_manager.get_radio_ssl_context(eth) + +# Set up a MiniMQTT Client +# NOTE: We'll need to connect insecurely for ethernet configurations. +mqtt_client = MQTT.MQTT( + broker="io.adafruit.com", + username=aio_username, + password=aio_key, + is_ssl=False, + socket_pool=pool, + ssl_context=ssl_context, +) + +# Setup the callback methods above +mqtt_client.on_connect = connected +mqtt_client.on_disconnect = disconnected +mqtt_client.on_message = message + +# Connect the client to the MQTT broker. +print("Connecting to Adafruit IO...") +mqtt_client.connect() + +photocell_val = 0 +while True: + # Poll the message queue + mqtt_client.loop() + + # Send a new message + print("Sending photocell value: %d..." % photocell_val) + mqtt_client.publish(photocell_feed, photocell_val) + print("Sent!") + photocell_val += 1 + time.sleep(5) diff --git a/examples/ethernet/minimqtt_simpletest_eth.py b/examples/ethernet/minimqtt_simpletest_eth.py index a5ba5892..7405526b 100644 --- a/examples/ethernet/minimqtt_simpletest_eth.py +++ b/examples/ethernet/minimqtt_simpletest_eth.py @@ -1,101 +1,101 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# SPDX-License-Identifier: MIT - -import os -import board -import busio -from digitalio import DigitalInOut -import adafruit_connection_manager -from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET5K - -import adafruit_minimqtt.adafruit_minimqtt as MQTT - -# Add settings.toml to your filesystem. Add your Adafruit IO username and key as well. -# DO NOT share that file or commit it into Git or other source control. - -aio_username = os.getenv("aio_username") -aio_key = os.getenv("aio_key") - -cs = DigitalInOut(board.D10) -spi_bus = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) - -# Initialize ethernet interface with DHCP -eth = WIZNET5K(spi_bus, cs) -### Topic Setup ### - -# MQTT Topic -# Use this topic if you'd like to connect to a standard MQTT broker -mqtt_topic = "test/topic" - -# Adafruit IO-style Topic -# Use this topic if you'd like to connect to io.adafruit.com -# mqtt_topic = 'aio_user/feeds/temperature' - -### Code ### - - -# Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name -def connect(client, userdata, flags, rc): - # This function will be called when the client is connected - # successfully to the broker. - print("Connected to MQTT Broker!") - print("Flags: {0}\n RC: {1}".format(flags, rc)) - - -def disconnect(client, userdata, rc): - # This method is called when the client disconnects - # from the broker. - print("Disconnected from MQTT Broker!") - - -def subscribe(client, userdata, topic, granted_qos): - # This method is called when the client subscribes to a new feed. - print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) - - -def unsubscribe(client, userdata, topic, pid): - # This method is called when the client unsubscribes from a feed. - print("Unsubscribed from {0} with PID {1}".format(topic, pid)) - - -def publish(client, userdata, topic, pid): - # This method is called when the client publishes data to a feed. - print("Published to {0} with PID {1}".format(topic, pid)) - - -pool = adafruit_connection_manager.get_radio_socketpool(eth) -ssl_context = adafruit_connection_manager.get_radio_ssl_context(eth) - -# Set up a MiniMQTT Client -# NOTE: We'll need to connect insecurely for ethernet configurations. -client = MQTT.MQTT( - broker=os.getenv("broker"), - username=os.getenv("username"), - password=os.getenv("password"), - is_ssl=False, - socket_pool=pool, - ssl_context=ssl_context, -) - -# Connect callback handlers to client -client.on_connect = connect -client.on_disconnect = disconnect -client.on_subscribe = subscribe -client.on_unsubscribe = unsubscribe -client.on_publish = publish - -print("Attempting to connect to %s" % client.broker) -client.connect() - -print("Subscribing to %s" % mqtt_topic) -client.subscribe(mqtt_topic) - -print("Publishing to %s" % mqtt_topic) -client.publish(mqtt_topic, "Hello Broker!") - -print("Unsubscribing from %s" % mqtt_topic) -client.unsubscribe(mqtt_topic) - -print("Disconnecting from %s" % client.broker) -client.disconnect() +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + +import os +import board +import busio +from digitalio import DigitalInOut +import adafruit_connection_manager +from adafruit_wiznet5k.adafruit_wiznet5k import WIZNET5K + +import adafruit_minimqtt.adafruit_minimqtt as MQTT + +# Add settings.toml to your filesystem. Add your Adafruit IO username and key as well. +# DO NOT share that file or commit it into Git or other source control. + +aio_username = os.getenv("aio_username") +aio_key = os.getenv("aio_key") + +cs = DigitalInOut(board.D10) +spi_bus = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) + +# Initialize ethernet interface with DHCP +eth = WIZNET5K(spi_bus, cs) +### Topic Setup ### + +# MQTT Topic +# Use this topic if you'd like to connect to a standard MQTT broker +mqtt_topic = "test/topic" + +# Adafruit IO-style Topic +# Use this topic if you'd like to connect to io.adafruit.com +# mqtt_topic = 'aio_user/feeds/temperature' + +### Code ### + + +# Define callback methods which are called when events occur +# pylint: disable=unused-argument, redefined-outer-name +def connect(client, userdata, flags, rc): + # This function will be called when the client is connected + # successfully to the broker. + print("Connected to MQTT Broker!") + print("Flags: {0}\n RC: {1}".format(flags, rc)) + + +def disconnect(client, userdata, rc): + # This method is called when the client disconnects + # from the broker. + print("Disconnected from MQTT Broker!") + + +def subscribe(client, userdata, topic, granted_qos): + # This method is called when the client subscribes to a new feed. + print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) + + +def unsubscribe(client, userdata, topic, pid): + # This method is called when the client unsubscribes from a feed. + print("Unsubscribed from {0} with PID {1}".format(topic, pid)) + + +def publish(client, userdata, topic, pid): + # This method is called when the client publishes data to a feed. + print("Published to {0} with PID {1}".format(topic, pid)) + + +pool = adafruit_connection_manager.get_radio_socketpool(eth) +ssl_context = adafruit_connection_manager.get_radio_ssl_context(eth) + +# Set up a MiniMQTT Client +# NOTE: We'll need to connect insecurely for ethernet configurations. +client = MQTT.MQTT( + broker=os.getenv("broker"), + username=os.getenv("username"), + password=os.getenv("password"), + is_ssl=False, + socket_pool=pool, + ssl_context=ssl_context, +) + +# Connect callback handlers to client +client.on_connect = connect +client.on_disconnect = disconnect +client.on_subscribe = subscribe +client.on_unsubscribe = unsubscribe +client.on_publish = publish + +print("Attempting to connect to %s" % client.broker) +client.connect() + +print("Subscribing to %s" % mqtt_topic) +client.subscribe(mqtt_topic) + +print("Publishing to %s" % mqtt_topic) +client.publish(mqtt_topic, "Hello Broker!") + +print("Unsubscribing from %s" % mqtt_topic) +client.unsubscribe(mqtt_topic) + +print("Disconnecting from %s" % client.broker) +client.disconnect() diff --git a/examples/minimqtt_simpletest.py b/examples/minimqtt_simpletest.py index 45aa077b..08f7c220 100644 --- a/examples/minimqtt_simpletest.py +++ b/examples/minimqtt_simpletest.py @@ -1,124 +1,124 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# SPDX-License-Identifier: MIT - -import os -import board -import busio -from digitalio import DigitalInOut -import adafruit_connection_manager -from adafruit_esp32spi import adafruit_esp32spi -import adafruit_minimqtt.adafruit_minimqtt as MQTT - -# Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys -# with your WiFi credentials. Add your Adafruit IO username and key as well. -# DO NOT share that file or commit it into Git or other source control. - -aio_username = os.getenv("aio_username") -aio_key = os.getenv("aio_key") - -# If you are using a board with pre-defined ESP32 Pins: -esp32_cs = DigitalInOut(board.ESP_CS) -esp32_ready = DigitalInOut(board.ESP_BUSY) -esp32_reset = DigitalInOut(board.ESP_RESET) - -# If you have an externally connected ESP32: -# esp32_cs = DigitalInOut(board.D9) -# esp32_ready = DigitalInOut(board.D10) -# esp32_reset = DigitalInOut(board.D5) - -spi = busio.SPI(board.SCK, board.MOSI, board.MISO) -esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) - -print("Connecting to AP...") -while not esp.is_connected: - try: - esp.connect_AP( - os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD") - ) - except RuntimeError as e: - print("could not connect to AP, retrying: ", e) - continue -print("Connected to", str(esp.ssid, "utf-8"), "\tRSSI:", esp.rssi) - -### Topic Setup ### - -# MQTT Topic -# Use this topic if you'd like to connect to a standard MQTT broker -# mqtt_topic = "test/topic" - -# Adafruit IO-style Topic -# Use this topic if you'd like to connect to io.adafruit.com -mqtt_topic = aio_username + "/feeds/temperature" - - -### Code ### - - -# Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name -def connect(mqtt_client, userdata, flags, rc): - # This function will be called when the mqtt_client is connected - # successfully to the broker. - print("Connected to MQTT Broker!") - print("Flags: {0}\n RC: {1}".format(flags, rc)) - - -def disconnect(mqtt_client, userdata, rc): - # This method is called when the mqtt_client disconnects - # from the broker. - print("Disconnected from MQTT Broker!") - - -def subscribe(mqtt_client, userdata, topic, granted_qos): - # This method is called when the mqtt_client subscribes to a new feed. - print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) - - -def unsubscribe(mqtt_client, userdata, topic, pid): - # This method is called when the mqtt_client unsubscribes from a feed. - print("Unsubscribed from {0} with PID {1}".format(topic, pid)) - - -def publish(mqtt_client, userdata, topic, pid): - # This method is called when the mqtt_client publishes data to a feed. - print("Published to {0} with PID {1}".format(topic, pid)) - - -def message(client, topic, message): - print("New message on topic {0}: {1}".format(topic, message)) - - -pool = adafruit_connection_manager.get_radio_socketpool(esp) -ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp) - -# Set up a MiniMQTT Client -mqtt_client = MQTT.MQTT( - broker="io.adafruit.com", - username=aio_username, - password=aio_key, - socket_pool=pool, - ssl_context=ssl_context, -) - -# Connect callback handlers to mqtt_client -mqtt_client.on_connect = connect -mqtt_client.on_disconnect = disconnect -mqtt_client.on_subscribe = subscribe -mqtt_client.on_unsubscribe = unsubscribe -mqtt_client.on_publish = publish -mqtt_client.on_message = message - -print("Attempting to connect to %s" % mqtt_client.broker) -mqtt_client.connect() - -print("Subscribing to %s" % mqtt_topic) -mqtt_client.subscribe(mqtt_topic) - -print("Publishing to %s" % mqtt_topic) -mqtt_client.publish(mqtt_topic, "Hello Broker!") - -print("Unsubscribing from %s" % mqtt_topic) -mqtt_client.unsubscribe(mqtt_topic) - -print("Disconnecting from %s" % mqtt_client.broker) -mqtt_client.disconnect() +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + +import os +import board +import busio +from digitalio import DigitalInOut +import adafruit_connection_manager +from adafruit_esp32spi import adafruit_esp32spi +import adafruit_minimqtt.adafruit_minimqtt as MQTT + +# Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys +# with your WiFi credentials. Add your Adafruit IO username and key as well. +# DO NOT share that file or commit it into Git or other source control. + +aio_username = os.getenv("aio_username") +aio_key = os.getenv("aio_key") + +# If you are using a board with pre-defined ESP32 Pins: +esp32_cs = DigitalInOut(board.ESP_CS) +esp32_ready = DigitalInOut(board.ESP_BUSY) +esp32_reset = DigitalInOut(board.ESP_RESET) + +# If you have an externally connected ESP32: +# esp32_cs = DigitalInOut(board.D9) +# esp32_ready = DigitalInOut(board.D10) +# esp32_reset = DigitalInOut(board.D5) + +spi = busio.SPI(board.SCK, board.MOSI, board.MISO) +esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) + +print("Connecting to AP...") +while not esp.is_connected: + try: + esp.connect_AP( + os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD") + ) + except RuntimeError as e: + print("could not connect to AP, retrying: ", e) + continue +print("Connected to", str(esp.ssid, "utf-8"), "\tRSSI:", esp.rssi) + +### Topic Setup ### + +# MQTT Topic +# Use this topic if you'd like to connect to a standard MQTT broker +# mqtt_topic = "test/topic" + +# Adafruit IO-style Topic +# Use this topic if you'd like to connect to io.adafruit.com +mqtt_topic = aio_username + "/feeds/temperature" + + +### Code ### + + +# Define callback methods which are called when events occur +# pylint: disable=unused-argument, redefined-outer-name +def connect(mqtt_client, userdata, flags, rc): + # This function will be called when the mqtt_client is connected + # successfully to the broker. + print("Connected to MQTT Broker!") + print("Flags: {0}\n RC: {1}".format(flags, rc)) + + +def disconnect(mqtt_client, userdata, rc): + # This method is called when the mqtt_client disconnects + # from the broker. + print("Disconnected from MQTT Broker!") + + +def subscribe(mqtt_client, userdata, topic, granted_qos): + # This method is called when the mqtt_client subscribes to a new feed. + print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) + + +def unsubscribe(mqtt_client, userdata, topic, pid): + # This method is called when the mqtt_client unsubscribes from a feed. + print("Unsubscribed from {0} with PID {1}".format(topic, pid)) + + +def publish(mqtt_client, userdata, topic, pid): + # This method is called when the mqtt_client publishes data to a feed. + print("Published to {0} with PID {1}".format(topic, pid)) + + +def message(client, topic, message): + print("New message on topic {0}: {1}".format(topic, message)) + + +pool = adafruit_connection_manager.get_radio_socketpool(esp) +ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp) + +# Set up a MiniMQTT Client +mqtt_client = MQTT.MQTT( + broker="io.adafruit.com", + username=aio_username, + password=aio_key, + socket_pool=pool, + ssl_context=ssl_context, +) + +# Connect callback handlers to mqtt_client +mqtt_client.on_connect = connect +mqtt_client.on_disconnect = disconnect +mqtt_client.on_subscribe = subscribe +mqtt_client.on_unsubscribe = unsubscribe +mqtt_client.on_publish = publish +mqtt_client.on_message = message + +print("Attempting to connect to %s" % mqtt_client.broker) +mqtt_client.connect() + +print("Subscribing to %s" % mqtt_topic) +mqtt_client.subscribe(mqtt_topic) + +print("Publishing to %s" % mqtt_topic) +mqtt_client.publish(mqtt_topic, "Hello Broker!") + +print("Unsubscribing from %s" % mqtt_topic) +mqtt_client.unsubscribe(mqtt_topic) + +print("Disconnecting from %s" % mqtt_client.broker) +mqtt_client.disconnect() diff --git a/examples/native_networking/minimqtt_adafruitio_native_networking.py b/examples/native_networking/minimqtt_adafruitio_native_networking.py index 65632043..caba2b3c 100644 --- a/examples/native_networking/minimqtt_adafruitio_native_networking.py +++ b/examples/native_networking/minimqtt_adafruitio_native_networking.py @@ -1,99 +1,99 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# SPDX-License-Identifier: MIT - -import os -import time -import ssl -import socketpool -import wifi -import adafruit_minimqtt.adafruit_minimqtt as MQTT - -# Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys -# with your WiFi credentials. DO NOT share that file or commit it into Git or other -# source control. - -# Set your Adafruit IO Username, Key and Port in settings.toml -# (visit io.adafruit.com if you need to create an account, -# or if you need your Adafruit IO key.) -aio_username = os.getenv("aio_username") -aio_key = os.getenv("aio_key") - -print(f"Connecting to {os.getenv('CIRCUITPY_WIFI_SSID')}") -wifi.radio.connect( - os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD") -) -print(f"Connected to {os.getenv('CIRCUITPY_WIFI_SSID')}!") -### Feeds ### - -# Setup a feed named 'photocell' for publishing to a feed -photocell_feed = aio_username + "/feeds/photocell" - -# Setup a feed named 'onoff' for subscribing to changes -onoff_feed = aio_username + "/feeds/onoff" - -### Code ### - - -# Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name -def connected(client, userdata, flags, rc): - # This function will be called when the client is connected - # successfully to the broker. - print(f"Connected to Adafruit IO! Listening for topic changes on {onoff_feed}") - # Subscribe to all changes on the onoff_feed. - client.subscribe(onoff_feed) - - -def disconnected(client, userdata, rc): - # This method is called when the client is disconnected - print("Disconnected from Adafruit IO!") - - -def message(client, topic, message): - # This method is called when a topic the client is subscribed to - # has a new message. - print(f"New message on topic {topic}: {message}") - - -# Create a socket pool -pool = socketpool.SocketPool(wifi.radio) -ssl_context = ssl.create_default_context() - -# If you need to use certificate/key pair authentication (e.g. X.509), you can load them in the -# ssl context by uncommenting the lines below and adding the following keys to your settings.toml: -# "device_cert_path" - Path to the Device Certificate -# "device_key_path" - Path to the RSA Private Key -# ssl_context.load_cert_chain( -# certfile=os.getenv("device_cert_path"), keyfile=os.getenv("device_key_path") -# ) - -# Set up a MiniMQTT Client -mqtt_client = MQTT.MQTT( - broker="io.adafruit.com", - port=1883, - username=aio_username, - password=aio_key, - socket_pool=pool, - ssl_context=ssl_context, -) - -# Setup the callback methods above -mqtt_client.on_connect = connected -mqtt_client.on_disconnect = disconnected -mqtt_client.on_message = message - -# Connect the client to the MQTT broker. -print("Connecting to Adafruit IO...") -mqtt_client.connect() - -photocell_val = 0 -while True: - # Poll the message queue - mqtt_client.loop(timeout=1) - - # Send a new message - print(f"Sending photocell value: {photocell_val}...") - mqtt_client.publish(photocell_feed, photocell_val) - print("Sent!") - photocell_val += 1 - time.sleep(5) +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + +import os +import time +import ssl +import socketpool +import wifi +import adafruit_minimqtt.adafruit_minimqtt as MQTT + +# Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys +# with your WiFi credentials. DO NOT share that file or commit it into Git or other +# source control. + +# Set your Adafruit IO Username, Key and Port in settings.toml +# (visit io.adafruit.com if you need to create an account, +# or if you need your Adafruit IO key.) +aio_username = os.getenv("aio_username") +aio_key = os.getenv("aio_key") + +print(f"Connecting to {os.getenv('CIRCUITPY_WIFI_SSID')}") +wifi.radio.connect( + os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD") +) +print(f"Connected to {os.getenv('CIRCUITPY_WIFI_SSID')}!") +### Feeds ### + +# Setup a feed named 'photocell' for publishing to a feed +photocell_feed = aio_username + "/feeds/photocell" + +# Setup a feed named 'onoff' for subscribing to changes +onoff_feed = aio_username + "/feeds/onoff" + +### Code ### + + +# Define callback methods which are called when events occur +# pylint: disable=unused-argument, redefined-outer-name +def connected(client, userdata, flags, rc): + # This function will be called when the client is connected + # successfully to the broker. + print(f"Connected to Adafruit IO! Listening for topic changes on {onoff_feed}") + # Subscribe to all changes on the onoff_feed. + client.subscribe(onoff_feed) + + +def disconnected(client, userdata, rc): + # This method is called when the client is disconnected + print("Disconnected from Adafruit IO!") + + +def message(client, topic, message): + # This method is called when a topic the client is subscribed to + # has a new message. + print(f"New message on topic {topic}: {message}") + + +# Create a socket pool +pool = socketpool.SocketPool(wifi.radio) +ssl_context = ssl.create_default_context() + +# If you need to use certificate/key pair authentication (e.g. X.509), you can load them in the +# ssl context by uncommenting the lines below and adding the following keys to your settings.toml: +# "device_cert_path" - Path to the Device Certificate +# "device_key_path" - Path to the RSA Private Key +# ssl_context.load_cert_chain( +# certfile=os.getenv("device_cert_path"), keyfile=os.getenv("device_key_path") +# ) + +# Set up a MiniMQTT Client +mqtt_client = MQTT.MQTT( + broker="io.adafruit.com", + port=1883, + username=aio_username, + password=aio_key, + socket_pool=pool, + ssl_context=ssl_context, +) + +# Setup the callback methods above +mqtt_client.on_connect = connected +mqtt_client.on_disconnect = disconnected +mqtt_client.on_message = message + +# Connect the client to the MQTT broker. +print("Connecting to Adafruit IO...") +mqtt_client.connect() + +photocell_val = 0 +while True: + # Poll the message queue + mqtt_client.loop(timeout=1) + + # Send a new message + print(f"Sending photocell value: {photocell_val}...") + mqtt_client.publish(photocell_feed, photocell_val) + print("Sent!") + photocell_val += 1 + time.sleep(5) diff --git a/examples/native_networking/minimqtt_pub_sub_blocking_native_networking.py b/examples/native_networking/minimqtt_pub_sub_blocking_native_networking.py index 5aad73c7..1e1412b6 100644 --- a/examples/native_networking/minimqtt_pub_sub_blocking_native_networking.py +++ b/examples/native_networking/minimqtt_pub_sub_blocking_native_networking.py @@ -1,100 +1,100 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# SPDX-License-Identifier: MIT - -import os -import time -import ssl -import socketpool -import wifi -import adafruit_minimqtt.adafruit_minimqtt as MQTT - -# Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys -# with your WiFi credentials. DO NOT share that file or commit it into Git or other -# source control. - -# Set your Adafruit IO Username, Key and Port in settings.toml -# (visit io.adafruit.com if you need to create an account, -# or if you need your Adafruit IO key.) -aio_username = os.getenv("aio_username") -aio_key = os.getenv("aio_key") - -print("Connecting to %s" % os.getenv("CIRCUITPY_WIFI_SSID")) -wifi.radio.connect( - os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD") -) -print("Connected to %s!" % os.getenv("CIRCUITPY_WIFI_SSID")) - -### Adafruit IO Setup ### - -# Setup a feed named `testfeed` for publishing. -default_topic = aio_username + "/feeds/testfeed" - - -### Code ### -# Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name -def connected(client, userdata, flags, rc): - # This function will be called when the client is connected - # successfully to the broker. - print(f"Connected to MQTT broker! Listening for topic changes on {default_topic}") - # Subscribe to all changes on the default_topic feed. - client.subscribe(default_topic) - - -def disconnected(client, userdata, rc): - # This method is called when the client is disconnected - print("Disconnected from MQTT Broker!") - - -def message(client, topic, message): - """Method callled when a client's subscribed feed has a new - value. - :param str topic: The topic of the feed with a new value. - :param str message: The new value - """ - print(f"New message on topic {topic}: {message}") - - -# Create a socket pool -pool = socketpool.SocketPool(wifi.radio) -ssl_context = ssl.create_default_context() - -# If you need to use certificate/key pair authentication (e.g. X.509), you can load them in the -# ssl context by uncommenting the lines below and adding the following keys to your settings.toml: -# "device_cert_path" - Path to the Device Certificate -# "device_key_path" - Path to the RSA Private Key -# ssl_context.load_cert_chain( -# certfile=os.getenv("device_cert_path"), keyfile=os.getenv("device_key_path") -# ) - -# Set up a MiniMQTT Client -mqtt_client = MQTT.MQTT( - broker="io.adafruit.com", - port=1883, - username=aio_username, - password=aio_key, - socket_pool=pool, - ssl_context=ssl_context, -) - -# Setup the callback methods above -mqtt_client.on_connect = connected -mqtt_client.on_disconnect = disconnected -mqtt_client.on_message = message - -# Connect the client to the MQTT broker. -print("Connecting to MQTT broker...") -mqtt_client.connect() - -# Start a blocking message loop... -# NOTE: NO code below this loop will execute -# NOTE: Network reconnection is handled within this loop -while True: - try: - mqtt_client.loop(timeout=1) - except (ValueError, RuntimeError) as e: - print("Failed to get data, retrying\n", e) - wifi.reset() - mqtt_client.reconnect() - continue - time.sleep(1) +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + +import os +import time +import ssl +import socketpool +import wifi +import adafruit_minimqtt.adafruit_minimqtt as MQTT + +# Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys +# with your WiFi credentials. DO NOT share that file or commit it into Git or other +# source control. + +# Set your Adafruit IO Username, Key and Port in settings.toml +# (visit io.adafruit.com if you need to create an account, +# or if you need your Adafruit IO key.) +aio_username = os.getenv("aio_username") +aio_key = os.getenv("aio_key") + +print("Connecting to %s" % os.getenv("CIRCUITPY_WIFI_SSID")) +wifi.radio.connect( + os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD") +) +print("Connected to %s!" % os.getenv("CIRCUITPY_WIFI_SSID")) + +### Adafruit IO Setup ### + +# Setup a feed named `testfeed` for publishing. +default_topic = aio_username + "/feeds/testfeed" + + +### Code ### +# Define callback methods which are called when events occur +# pylint: disable=unused-argument, redefined-outer-name +def connected(client, userdata, flags, rc): + # This function will be called when the client is connected + # successfully to the broker. + print(f"Connected to MQTT broker! Listening for topic changes on {default_topic}") + # Subscribe to all changes on the default_topic feed. + client.subscribe(default_topic) + + +def disconnected(client, userdata, rc): + # This method is called when the client is disconnected + print("Disconnected from MQTT Broker!") + + +def message(client, topic, message): + """Method callled when a client's subscribed feed has a new + value. + :param str topic: The topic of the feed with a new value. + :param str message: The new value + """ + print(f"New message on topic {topic}: {message}") + + +# Create a socket pool +pool = socketpool.SocketPool(wifi.radio) +ssl_context = ssl.create_default_context() + +# If you need to use certificate/key pair authentication (e.g. X.509), you can load them in the +# ssl context by uncommenting the lines below and adding the following keys to your settings.toml: +# "device_cert_path" - Path to the Device Certificate +# "device_key_path" - Path to the RSA Private Key +# ssl_context.load_cert_chain( +# certfile=os.getenv("device_cert_path"), keyfile=os.getenv("device_key_path") +# ) + +# Set up a MiniMQTT Client +mqtt_client = MQTT.MQTT( + broker="io.adafruit.com", + port=1883, + username=aio_username, + password=aio_key, + socket_pool=pool, + ssl_context=ssl_context, +) + +# Setup the callback methods above +mqtt_client.on_connect = connected +mqtt_client.on_disconnect = disconnected +mqtt_client.on_message = message + +# Connect the client to the MQTT broker. +print("Connecting to MQTT broker...") +mqtt_client.connect() + +# Start a blocking message loop... +# NOTE: NO code below this loop will execute +# NOTE: Network reconnection is handled within this loop +while True: + try: + mqtt_client.loop(timeout=1) + except (ValueError, RuntimeError) as e: + print("Failed to get data, retrying\n", e) + wifi.reset() + mqtt_client.reconnect() + continue + time.sleep(1) diff --git a/examples/native_networking/minimqtt_pub_sub_blocking_topic_callbacks_native_networking.py b/examples/native_networking/minimqtt_pub_sub_blocking_topic_callbacks_native_networking.py index 86f4e9cd..8fe878d3 100644 --- a/examples/native_networking/minimqtt_pub_sub_blocking_topic_callbacks_native_networking.py +++ b/examples/native_networking/minimqtt_pub_sub_blocking_topic_callbacks_native_networking.py @@ -1,112 +1,112 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# SPDX-License-Identifier: MIT - -import os -import time -import ssl -import socketpool -import wifi -import adafruit_minimqtt.adafruit_minimqtt as MQTT - -# Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys -# with your WiFi credentials. DO NOT share that file or commit it into Git or other -# source control. - -# Set your Adafruit IO Username, Key and Port in settings.toml -# (visit io.adafruit.com if you need to create an account, -# or if you need your Adafruit IO key.) -aio_username = os.getenv("aio_username") -aio_key = os.getenv("aio_key") - -print("Connecting to %s" % os.getenv("CIRCUITPY_WIFI_SSID")) -wifi.radio.connect( - os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD") -) -print("Connected to %s!" % os.getenv("CIRCUITPY_WIFI_SSID")) - -### Code ### - - -# Define callback methods which are called when events occur -# pylint: disable=unused-argument, redefined-outer-name -def connected(client, userdata, flags, rc): - # This function will be called when the client is connected - # successfully to the broker. - print("Connected to MQTT Broker!") - - -def disconnected(client, userdata, rc): - # This method is called when the client is disconnected - print("Disconnected from MQTT Broker!") - - -def subscribe(client, userdata, topic, granted_qos): - # This method is called when the client subscribes to a new feed. - print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) - - -def unsubscribe(client, userdata, topic, pid): - # This method is called when the client unsubscribes from a feed. - print("Unsubscribed from {0} with PID {1}".format(topic, pid)) - - -def on_battery_msg(client, topic, message): - # Method called when device/batteryLife has a new value - print("Battery level: {}v".format(message)) - - # client.remove_topic_callback(aio_username + "/feeds/device.batterylevel") - - -def on_message(client, topic, message): - # Method callled when a client's subscribed feed has a new value. - print("New message on topic {0}: {1}".format(topic, message)) - - -# Create a socket pool -pool = socketpool.SocketPool(wifi.radio) -ssl_context = ssl.create_default_context() - -# If you need to use certificate/key pair authentication (e.g. X.509), you can load them in the -# ssl context by uncommenting the lines below and adding the following keys to your settings.toml: -# "device_cert_path" - Path to the Device Certificate -# "device_key_path" - Path to the RSA Private Key -# ssl_context.load_cert_chain( -# certfile=os.getenv("device_cert_path"), keyfile=os.getenv("device_key_path") -# ) - -# Set up a MiniMQTT Client -client = MQTT.MQTT( - broker="io.adafruit.com", - port=1883, - username=aio_username, - password=aio_key, - socket_pool=pool, - ssl_context=ssl_context, -) - -# Setup the callback methods above -client.on_connect = connected -client.on_disconnect = disconnected -client.on_subscribe = subscribe -client.on_unsubscribe = unsubscribe -client.on_message = on_message -client.add_topic_callback(aio_username + "/feeds/device.batterylevel", on_battery_msg) - -# Connect the client to the MQTT broker. -print("Connecting to MQTT broker...") -client.connect() - -# Subscribe to all notifications on the device group -client.subscribe(aio_username + "/groups/device", 1) - -# Start a blocking message loop... -# NOTE: NO code below this loop will execute -while True: - try: - client.loop(timeout=1) - except (ValueError, RuntimeError) as e: - print("Failed to get data, retrying\n", e) - wifi.reset() - client.reconnect() - continue - time.sleep(1) +# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-License-Identifier: MIT + +import os +import time +import ssl +import socketpool +import wifi +import adafruit_minimqtt.adafruit_minimqtt as MQTT + +# Add settings.toml to your filesystem CIRCUITPY_WIFI_SSID and CIRCUITPY_WIFI_PASSWORD keys +# with your WiFi credentials. DO NOT share that file or commit it into Git or other +# source control. + +# Set your Adafruit IO Username, Key and Port in settings.toml +# (visit io.adafruit.com if you need to create an account, +# or if you need your Adafruit IO key.) +aio_username = os.getenv("aio_username") +aio_key = os.getenv("aio_key") + +print("Connecting to %s" % os.getenv("CIRCUITPY_WIFI_SSID")) +wifi.radio.connect( + os.getenv("CIRCUITPY_WIFI_SSID"), os.getenv("CIRCUITPY_WIFI_PASSWORD") +) +print("Connected to %s!" % os.getenv("CIRCUITPY_WIFI_SSID")) + +### Code ### + + +# Define callback methods which are called when events occur +# pylint: disable=unused-argument, redefined-outer-name +def connected(client, userdata, flags, rc): + # This function will be called when the client is connected + # successfully to the broker. + print("Connected to MQTT Broker!") + + +def disconnected(client, userdata, rc): + # This method is called when the client is disconnected + print("Disconnected from MQTT Broker!") + + +def subscribe(client, userdata, topic, granted_qos): + # This method is called when the client subscribes to a new feed. + print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos)) + + +def unsubscribe(client, userdata, topic, pid): + # This method is called when the client unsubscribes from a feed. + print("Unsubscribed from {0} with PID {1}".format(topic, pid)) + + +def on_battery_msg(client, topic, message): + # Method called when device/batteryLife has a new value + print("Battery level: {}v".format(message)) + + # client.remove_topic_callback(aio_username + "/feeds/device.batterylevel") + + +def on_message(client, topic, message): + # Method callled when a client's subscribed feed has a new value. + print("New message on topic {0}: {1}".format(topic, message)) + + +# Create a socket pool +pool = socketpool.SocketPool(wifi.radio) +ssl_context = ssl.create_default_context() + +# If you need to use certificate/key pair authentication (e.g. X.509), you can load them in the +# ssl context by uncommenting the lines below and adding the following keys to your settings.toml: +# "device_cert_path" - Path to the Device Certificate +# "device_key_path" - Path to the RSA Private Key +# ssl_context.load_cert_chain( +# certfile=os.getenv("device_cert_path"), keyfile=os.getenv("device_key_path") +# ) + +# Set up a MiniMQTT Client +client = MQTT.MQTT( + broker="io.adafruit.com", + port=1883, + username=aio_username, + password=aio_key, + socket_pool=pool, + ssl_context=ssl_context, +) + +# Setup the callback methods above +client.on_connect = connected +client.on_disconnect = disconnected +client.on_subscribe = subscribe +client.on_unsubscribe = unsubscribe +client.on_message = on_message +client.add_topic_callback(aio_username + "/feeds/device.batterylevel", on_battery_msg) + +# Connect the client to the MQTT broker. +print("Connecting to MQTT broker...") +client.connect() + +# Subscribe to all notifications on the device group +client.subscribe(aio_username + "/groups/device", 1) + +# Start a blocking message loop... +# NOTE: NO code below this loop will execute +while True: + try: + client.loop(timeout=1) + except (ValueError, RuntimeError) as e: + print("Failed to get data, retrying\n", e) + wifi.reset() + client.reconnect() + continue + time.sleep(1) diff --git a/optional_requirements.txt b/optional_requirements.txt index d4e27c4d..3d1a5601 100644 --- a/optional_requirements.txt +++ b/optional_requirements.txt @@ -1,3 +1,3 @@ -# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries -# -# SPDX-License-Identifier: Unlicense +# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense diff --git a/pyproject.toml b/pyproject.toml index 3d88672c..b365c7d4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,47 +1,47 @@ -# SPDX-FileCopyrightText: 2022 Alec Delaney for Adafruit Industries -# -# SPDX-License-Identifier: MIT - -[build-system] -requires = [ - "setuptools", - "wheel", - "setuptools-scm", -] - -[project] -name = "adafruit-circuitpython-minimqtt" -description = "MQTT client library for CircuitPython" -version = "0.0.0+auto.0" -readme = "README.rst" -authors = [ - {name = "Adafruit Industries", email = "circuitpython@adafruit.com"} -] -urls = {Homepage = "https://github.com/adafruit/Adafruit_CircuitPython_MiniMQTT"} -keywords = [ - "adafruit", - "blinka", - "circuitpython", - "micropython", - "minimqtt", - "mqtt,", - "client,", - "socket", -] -license = {text = "MIT"} -classifiers = [ - "Intended Audience :: Developers", - "Topic :: Software Development :: Libraries", - "Topic :: Software Development :: Embedded Systems", - "Topic :: System :: Hardware", - "License :: OSI Approved :: MIT License", - "Programming Language :: Python :: 3", -] -dynamic = ["dependencies", "optional-dependencies"] - -[tool.setuptools] -packages = ["adafruit_minimqtt"] - -[tool.setuptools.dynamic] -dependencies = {file = ["requirements.txt"]} -optional-dependencies = {optional = {file = ["optional_requirements.txt"]}} +# SPDX-FileCopyrightText: 2022 Alec Delaney for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +[build-system] +requires = [ + "setuptools", + "wheel", + "setuptools-scm", +] + +[project] +name = "adafruit-circuitpython-minimqtt" +description = "MQTT client library for CircuitPython" +version = "0.0.0+auto.0" +readme = "README.rst" +authors = [ + {name = "Adafruit Industries", email = "circuitpython@adafruit.com"} +] +urls = {Homepage = "https://github.com/adafruit/Adafruit_CircuitPython_MiniMQTT"} +keywords = [ + "adafruit", + "blinka", + "circuitpython", + "micropython", + "minimqtt", + "mqtt,", + "client,", + "socket", +] +license = {text = "MIT"} +classifiers = [ + "Intended Audience :: Developers", + "Topic :: Software Development :: Libraries", + "Topic :: Software Development :: Embedded Systems", + "Topic :: System :: Hardware", + "License :: OSI Approved :: MIT License", + "Programming Language :: Python :: 3", +] +dynamic = ["dependencies", "optional-dependencies"] + +[tool.setuptools] +packages = ["adafruit_minimqtt"] + +[tool.setuptools.dynamic] +dependencies = {file = ["requirements.txt"]} +optional-dependencies = {optional = {file = ["optional_requirements.txt"]}} diff --git a/requirements.txt b/requirements.txt index 8075f629..172291cb 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,7 @@ -# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries -# -# SPDX-License-Identifier: Unlicense - -Adafruit-Blinka -Adafruit-Circuitpython-ConnectionManager -adafruit-circuitpython-ticks +# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +Adafruit-Blinka +Adafruit-Circuitpython-ConnectionManager +adafruit-circuitpython-ticks diff --git a/tests/conftest.py b/tests/conftest.py index a4b8d631..90f257c8 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,17 +1,17 @@ -# SPDX-FileCopyrightText: 2023 Justin Myers for Adafruit Industries -# -# SPDX-License-Identifier: Unlicense - -""" PyTest Setup """ - -import pytest -import adafruit_connection_manager - - -@pytest.fixture(autouse=True) -def reset_connection_manager(monkeypatch): - """Reset the ConnectionManager, since it's a singlton and will hold data""" - monkeypatch.setattr( - "adafruit_minimqtt.adafruit_minimqtt.get_connection_manager", - adafruit_connection_manager.ConnectionManager, - ) +# SPDX-FileCopyrightText: 2023 Justin Myers for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +""" PyTest Setup """ + +import pytest +import adafruit_connection_manager + + +@pytest.fixture(autouse=True) +def reset_connection_manager(monkeypatch): + """Reset the ConnectionManager, since it's a singlton and will hold data""" + monkeypatch.setattr( + "adafruit_minimqtt.adafruit_minimqtt.get_connection_manager", + adafruit_connection_manager.ConnectionManager, + ) diff --git a/tests/mocket.py b/tests/mocket.py index 31b41015..73dcb8a3 100644 --- a/tests/mocket.py +++ b/tests/mocket.py @@ -1,41 +1,41 @@ -# SPDX-FileCopyrightText: 2023 Vladimír Kotal -# -# SPDX-License-Identifier: Unlicense - -"""fake socket class for protocol level testing""" - -from unittest import mock - - -class Mocket: - """ - Mock Socket tailored for MiniMQTT testing. Records sent data, - hands out pre-recorded reply. - - Inspired by the Mocket class from Adafruit_CircuitPython_Requests - """ - - def __init__(self, to_send): - self._to_send = to_send - - self.sent = bytearray() - - self.timeout = mock.Mock() - self.connect = mock.Mock() - self.close = mock.Mock() - - def send(self, bytes_to_send): - """merely record the bytes. return the length of this bytearray.""" - self.sent.extend(bytes_to_send) - return len(bytes_to_send) - - # MiniMQTT checks for the presence of "recv_into" and switches behavior based on that. - def recv_into(self, retbuf, bufsize): - """return data from internal buffer""" - size = min(bufsize, len(self._to_send)) - if size == 0: - return size - chop = self._to_send[0:size] - retbuf[0:] = chop - self._to_send = self._to_send[size:] - return size +# SPDX-FileCopyrightText: 2023 Vladimír Kotal +# +# SPDX-License-Identifier: Unlicense + +"""fake socket class for protocol level testing""" + +from unittest import mock + + +class Mocket: + """ + Mock Socket tailored for MiniMQTT testing. Records sent data, + hands out pre-recorded reply. + + Inspired by the Mocket class from Adafruit_CircuitPython_Requests + """ + + def __init__(self, to_send): + self._to_send = to_send + + self.sent = bytearray() + + self.timeout = mock.Mock() + self.connect = mock.Mock() + self.close = mock.Mock() + + def send(self, bytes_to_send): + """merely record the bytes. return the length of this bytearray.""" + self.sent.extend(bytes_to_send) + return len(bytes_to_send) + + # MiniMQTT checks for the presence of "recv_into" and switches behavior based on that. + def recv_into(self, retbuf, bufsize): + """return data from internal buffer""" + size = min(bufsize, len(self._to_send)) + if size == 0: + return size + chop = self._to_send[0:size] + retbuf[0:] = chop + self._to_send = self._to_send[size:] + return size diff --git a/tests/test_backoff.py b/tests/test_backoff.py index e26d07a4..7aed6995 100644 --- a/tests/test_backoff.py +++ b/tests/test_backoff.py @@ -1,56 +1,56 @@ -# SPDX-FileCopyrightText: 2023 Vladimír Kotal -# -# SPDX-License-Identifier: Unlicense - -"""exponential back-off tests""" - - -import socket -import ssl -import time -from unittest.mock import call, patch - -import pytest -import adafruit_minimqtt.adafruit_minimqtt as MQTT - - -class TestExpBackOff: - """basic exponential back-off test""" - - connect_times = [] - - # pylint: disable=unused-argument - def fake_connect(self, arg): - """connect() replacement that records the call times and always raises OSError""" - self.connect_times.append(time.monotonic()) - raise OSError("this connect failed") - - def test_failing_connect(self) -> None: - """test that exponential back-off is used when connect() always raises OSError""" - # use RFC 1918 address to avoid dealing with IPv6 in the call list below - host = "172.40.0.3" - port = 1883 - - with patch.object(socket.socket, "connect") as mock_method: - mock_method.side_effect = self.fake_connect - - connect_retries = 3 - mqtt_client = MQTT.MQTT( - broker=host, - port=port, - socket_pool=socket, - ssl_context=ssl.create_default_context(), - connect_retries=connect_retries, - ) - print("connecting") - with pytest.raises(MQTT.MMQTTException) as context: - mqtt_client.connect() - assert "Repeated connect failures" in str(context) - - mock_method.assert_called() - calls = [call((host, port)) for _ in range(0, connect_retries)] - mock_method.assert_has_calls(calls) - - print(f"connect() call times: {self.connect_times}") - for i in range(1, connect_retries): - assert self.connect_times[i] >= 2**i +# SPDX-FileCopyrightText: 2023 Vladimír Kotal +# +# SPDX-License-Identifier: Unlicense + +"""exponential back-off tests""" + + +import socket +import ssl +import time +from unittest.mock import call, patch + +import pytest +import adafruit_minimqtt.adafruit_minimqtt as MQTT + + +class TestExpBackOff: + """basic exponential back-off test""" + + connect_times = [] + + # pylint: disable=unused-argument + def fake_connect(self, arg): + """connect() replacement that records the call times and always raises OSError""" + self.connect_times.append(time.monotonic()) + raise OSError("this connect failed") + + def test_failing_connect(self) -> None: + """test that exponential back-off is used when connect() always raises OSError""" + # use RFC 1918 address to avoid dealing with IPv6 in the call list below + host = "172.40.0.3" + port = 1883 + + with patch.object(socket.socket, "connect") as mock_method: + mock_method.side_effect = self.fake_connect + + connect_retries = 3 + mqtt_client = MQTT.MQTT( + broker=host, + port=port, + socket_pool=socket, + ssl_context=ssl.create_default_context(), + connect_retries=connect_retries, + ) + print("connecting") + with pytest.raises(MQTT.MMQTTException) as context: + mqtt_client.connect() + assert "Repeated connect failures" in str(context) + + mock_method.assert_called() + calls = [call((host, port)) for _ in range(0, connect_retries)] + mock_method.assert_has_calls(calls) + + print(f"connect() call times: {self.connect_times}") + for i in range(1, connect_retries): + assert self.connect_times[i] >= 2**i diff --git a/tests/test_loop.py b/tests/test_loop.py index 6666d86f..ad9eb858 100644 --- a/tests/test_loop.py +++ b/tests/test_loop.py @@ -1,262 +1,262 @@ -# SPDX-FileCopyrightText: 2023 Vladimír Kotal -# -# SPDX-License-Identifier: Unlicense - -"""loop() tests""" - -import random -import socket -import ssl -import time -import errno - -from unittest.mock import patch -from unittest import mock - -import pytest -import adafruit_minimqtt.adafruit_minimqtt as MQTT - - -class Nulltet: - """ - Mock Socket that does nothing. - - Inspired by the Mocket class from Adafruit_CircuitPython_Requests - """ - - def __init__(self): - self.sent = bytearray() - - self.timeout = mock.Mock() - self.connect = mock.Mock() - self.close = mock.Mock() - - def send(self, bytes_to_send): - """ - Record the bytes. return the length of this bytearray. - """ - self.sent.extend(bytes_to_send) - return len(bytes_to_send) - - # MiniMQTT checks for the presence of "recv_into" and switches behavior based on that. - # pylint: disable=unused-argument,no-self-use - def recv_into(self, retbuf, bufsize): - """Always raise timeout exception.""" - exc = OSError() - exc.errno = errno.ETIMEDOUT - raise exc - - -class Pingtet: - """ - Mock Socket tailored for PINGREQ testing. - Records sent data, hands out PINGRESP for each PINGREQ received. - - Inspired by the Mocket class from Adafruit_CircuitPython_Requests - """ - - PINGRESP = bytearray([0xD0, 0x00]) - - def __init__(self): - self._to_send = self.PINGRESP - - self.sent = bytearray() - - self.timeout = mock.Mock() - self.connect = mock.Mock() - self.close = mock.Mock() - - self._got_pingreq = False - - def send(self, bytes_to_send): - """ - Recognize PINGREQ and record the indication that it was received. - Assumes it was sent in one chunk (of 2 bytes). - Also record the bytes. return the length of this bytearray. - """ - self.sent.extend(bytes_to_send) - if bytes_to_send == b"\xc0\0": - self._got_pingreq = True - return len(bytes_to_send) - - # MiniMQTT checks for the presence of "recv_into" and switches behavior based on that. - def recv_into(self, retbuf, bufsize): - """ - If the PINGREQ indication is on, return PINGRESP, otherwise raise timeout exception. - """ - if self._got_pingreq: - size = min(bufsize, len(self._to_send)) - if size == 0: - return size - chop = self._to_send[0:size] - retbuf[0:] = chop - self._to_send = self._to_send[size:] - if len(self._to_send) == 0: - self._got_pingreq = False - self._to_send = self.PINGRESP - return size - - exc = OSError() - exc.errno = errno.ETIMEDOUT - raise exc - - -class TestLoop: - """basic loop() test""" - - connect_times = [] - INITIAL_RCS_VAL = 42 - rcs_val = INITIAL_RCS_VAL - - def fake_wait_for_msg(self, timeout=1): - """_wait_for_msg() replacement. Sleeps for 1 second and returns an integer.""" - time.sleep(timeout) - retval = self.rcs_val - self.rcs_val += 1 - return retval - - def test_loop_basic(self) -> None: - """ - test that loop() returns only after the specified timeout, regardless whether - _wait_for_msg() returned repeatedly within that timeout. - """ - - host = "172.40.0.3" - port = 1883 - - mqtt_client = MQTT.MQTT( - broker=host, - port=port, - socket_pool=socket, - ssl_context=ssl.create_default_context(), - ) - - with patch.object( - mqtt_client, "_wait_for_msg" - ) as wait_for_msg_mock, patch.object( - mqtt_client, "is_connected" - ) as is_connected_mock: - wait_for_msg_mock.side_effect = self.fake_wait_for_msg - is_connected_mock.side_effect = lambda: True - - time_before = time.monotonic() - timeout = random.randint(3, 8) - # pylint: disable=protected-access - mqtt_client._last_msg_sent_timestamp = MQTT.ticks_ms() - rcs = mqtt_client.loop(timeout=timeout) - time_after = time.monotonic() - - assert time_after - time_before >= timeout - wait_for_msg_mock.assert_called() - - # Check the return value. - assert rcs is not None - assert len(rcs) >= 1 - expected_rc = self.INITIAL_RCS_VAL - # pylint: disable=not-an-iterable - for ret_code in rcs: - assert ret_code == expected_rc - expected_rc += 1 - - # pylint: disable=no-self-use - # pylint: disable=invalid-name - def test_loop_timeout_vs_socket_timeout(self): - """ - loop() should throw MMQTTException if the timeout argument - is bigger than the socket timeout. - """ - mqtt_client = MQTT.MQTT( - broker="127.0.0.1", - port=1883, - socket_pool=socket, - ssl_context=ssl.create_default_context(), - socket_timeout=1, - ) - - mqtt_client.is_connected = lambda: True - with pytest.raises(MQTT.MMQTTException) as context: - mqtt_client.loop(timeout=0.5) - - assert "loop timeout" in str(context) - - # pylint: disable=no-self-use - def test_loop_is_connected(self): - """ - loop() should throw MMQTTException if not connected - """ - mqtt_client = MQTT.MQTT( - broker="127.0.0.1", - port=1883, - socket_pool=socket, - ssl_context=ssl.create_default_context(), - ) - - with pytest.raises(MQTT.MMQTTException) as context: - mqtt_client.loop(timeout=1) - - assert "not connected" in str(context) - - # pylint: disable=no-self-use - def test_loop_ping_timeout(self): - """Verify that ping will be sent even with loop timeout bigger than keep alive timeout - and no outgoing messages are sent.""" - - recv_timeout = 2 - keep_alive_timeout = recv_timeout * 2 - mqtt_client = MQTT.MQTT( - broker="localhost", - port=1883, - ssl_context=ssl.create_default_context(), - connect_retries=1, - socket_timeout=1, - recv_timeout=recv_timeout, - keep_alive=keep_alive_timeout, - ) - - # patch is_connected() to avoid CONNECT/CONNACK handling. - mqtt_client.is_connected = lambda: True - mocket = Pingtet() - # pylint: disable=protected-access - mqtt_client._sock = mocket - - start = time.monotonic() - res = mqtt_client.loop(timeout=2 * keep_alive_timeout + recv_timeout) - assert time.monotonic() - start >= 2 * keep_alive_timeout - assert len(mocket.sent) > 0 - assert len(res) == 3 - assert set(res) == {int(0xD0)} - - # pylint: disable=no-self-use - def test_loop_ping_vs_msgs_sent(self): - """Verify that ping will not be sent unnecessarily.""" - - recv_timeout = 2 - keep_alive_timeout = recv_timeout * 2 - mqtt_client = MQTT.MQTT( - broker="localhost", - port=1883, - ssl_context=ssl.create_default_context(), - connect_retries=1, - socket_timeout=1, - recv_timeout=recv_timeout, - keep_alive=keep_alive_timeout, - ) - - # patch is_connected() to avoid CONNECT/CONNACK handling. - mqtt_client.is_connected = lambda: True - - # With QoS=0 no PUBACK message is sent, so Nulltet can be used. - mocket = Nulltet() - # pylint: disable=protected-access - mqtt_client._sock = mocket - - i = 0 - topic = "foo" - message = "bar" - for _ in range(3 * keep_alive_timeout): - mqtt_client.publish(topic, message, qos=0) - mqtt_client.loop(1) - i += 1 - - # This means no other messages than the PUBLISH messages generated by the code above. - assert len(mocket.sent) == i * (2 + 2 + len(topic) + len(message)) +# SPDX-FileCopyrightText: 2023 Vladimír Kotal +# +# SPDX-License-Identifier: Unlicense + +"""loop() tests""" + +import random +import socket +import ssl +import time +import errno + +from unittest.mock import patch +from unittest import mock + +import pytest +import adafruit_minimqtt.adafruit_minimqtt as MQTT + + +class Nulltet: + """ + Mock Socket that does nothing. + + Inspired by the Mocket class from Adafruit_CircuitPython_Requests + """ + + def __init__(self): + self.sent = bytearray() + + self.timeout = mock.Mock() + self.connect = mock.Mock() + self.close = mock.Mock() + + def send(self, bytes_to_send): + """ + Record the bytes. return the length of this bytearray. + """ + self.sent.extend(bytes_to_send) + return len(bytes_to_send) + + # MiniMQTT checks for the presence of "recv_into" and switches behavior based on that. + # pylint: disable=unused-argument,no-self-use + def recv_into(self, retbuf, bufsize): + """Always raise timeout exception.""" + exc = OSError() + exc.errno = errno.ETIMEDOUT + raise exc + + +class Pingtet: + """ + Mock Socket tailored for PINGREQ testing. + Records sent data, hands out PINGRESP for each PINGREQ received. + + Inspired by the Mocket class from Adafruit_CircuitPython_Requests + """ + + PINGRESP = bytearray([0xD0, 0x00]) + + def __init__(self): + self._to_send = self.PINGRESP + + self.sent = bytearray() + + self.timeout = mock.Mock() + self.connect = mock.Mock() + self.close = mock.Mock() + + self._got_pingreq = False + + def send(self, bytes_to_send): + """ + Recognize PINGREQ and record the indication that it was received. + Assumes it was sent in one chunk (of 2 bytes). + Also record the bytes. return the length of this bytearray. + """ + self.sent.extend(bytes_to_send) + if bytes_to_send == b"\xc0\0": + self._got_pingreq = True + return len(bytes_to_send) + + # MiniMQTT checks for the presence of "recv_into" and switches behavior based on that. + def recv_into(self, retbuf, bufsize): + """ + If the PINGREQ indication is on, return PINGRESP, otherwise raise timeout exception. + """ + if self._got_pingreq: + size = min(bufsize, len(self._to_send)) + if size == 0: + return size + chop = self._to_send[0:size] + retbuf[0:] = chop + self._to_send = self._to_send[size:] + if len(self._to_send) == 0: + self._got_pingreq = False + self._to_send = self.PINGRESP + return size + + exc = OSError() + exc.errno = errno.ETIMEDOUT + raise exc + + +class TestLoop: + """basic loop() test""" + + connect_times = [] + INITIAL_RCS_VAL = 42 + rcs_val = INITIAL_RCS_VAL + + def fake_wait_for_msg(self, timeout=1): + """_wait_for_msg() replacement. Sleeps for 1 second and returns an integer.""" + time.sleep(timeout) + retval = self.rcs_val + self.rcs_val += 1 + return retval + + def test_loop_basic(self) -> None: + """ + test that loop() returns only after the specified timeout, regardless whether + _wait_for_msg() returned repeatedly within that timeout. + """ + + host = "172.40.0.3" + port = 1883 + + mqtt_client = MQTT.MQTT( + broker=host, + port=port, + socket_pool=socket, + ssl_context=ssl.create_default_context(), + ) + + with patch.object( + mqtt_client, "_wait_for_msg" + ) as wait_for_msg_mock, patch.object( + mqtt_client, "is_connected" + ) as is_connected_mock: + wait_for_msg_mock.side_effect = self.fake_wait_for_msg + is_connected_mock.side_effect = lambda: True + + time_before = time.monotonic() + timeout = random.randint(3, 8) + # pylint: disable=protected-access + mqtt_client._last_msg_sent_timestamp = MQTT.ticks_ms() + rcs = mqtt_client.loop(timeout=timeout) + time_after = time.monotonic() + + assert time_after - time_before >= timeout + wait_for_msg_mock.assert_called() + + # Check the return value. + assert rcs is not None + assert len(rcs) >= 1 + expected_rc = self.INITIAL_RCS_VAL + # pylint: disable=not-an-iterable + for ret_code in rcs: + assert ret_code == expected_rc + expected_rc += 1 + + # pylint: disable=no-self-use + # pylint: disable=invalid-name + def test_loop_timeout_vs_socket_timeout(self): + """ + loop() should throw MMQTTException if the timeout argument + is bigger than the socket timeout. + """ + mqtt_client = MQTT.MQTT( + broker="127.0.0.1", + port=1883, + socket_pool=socket, + ssl_context=ssl.create_default_context(), + socket_timeout=1, + ) + + mqtt_client.is_connected = lambda: True + with pytest.raises(MQTT.MMQTTException) as context: + mqtt_client.loop(timeout=0.5) + + assert "loop timeout" in str(context) + + # pylint: disable=no-self-use + def test_loop_is_connected(self): + """ + loop() should throw MMQTTException if not connected + """ + mqtt_client = MQTT.MQTT( + broker="127.0.0.1", + port=1883, + socket_pool=socket, + ssl_context=ssl.create_default_context(), + ) + + with pytest.raises(MQTT.MMQTTException) as context: + mqtt_client.loop(timeout=1) + + assert "not connected" in str(context) + + # pylint: disable=no-self-use + def test_loop_ping_timeout(self): + """Verify that ping will be sent even with loop timeout bigger than keep alive timeout + and no outgoing messages are sent.""" + + recv_timeout = 2 + keep_alive_timeout = recv_timeout * 2 + mqtt_client = MQTT.MQTT( + broker="localhost", + port=1883, + ssl_context=ssl.create_default_context(), + connect_retries=1, + socket_timeout=1, + recv_timeout=recv_timeout, + keep_alive=keep_alive_timeout, + ) + + # patch is_connected() to avoid CONNECT/CONNACK handling. + mqtt_client.is_connected = lambda: True + mocket = Pingtet() + # pylint: disable=protected-access + mqtt_client._sock = mocket + + start = time.monotonic() + res = mqtt_client.loop(timeout=2 * keep_alive_timeout + recv_timeout) + assert time.monotonic() - start >= 2 * keep_alive_timeout + assert len(mocket.sent) > 0 + assert len(res) == 3 + assert set(res) == {int(0xD0)} + + # pylint: disable=no-self-use + def test_loop_ping_vs_msgs_sent(self): + """Verify that ping will not be sent unnecessarily.""" + + recv_timeout = 2 + keep_alive_timeout = recv_timeout * 2 + mqtt_client = MQTT.MQTT( + broker="localhost", + port=1883, + ssl_context=ssl.create_default_context(), + connect_retries=1, + socket_timeout=1, + recv_timeout=recv_timeout, + keep_alive=keep_alive_timeout, + ) + + # patch is_connected() to avoid CONNECT/CONNACK handling. + mqtt_client.is_connected = lambda: True + + # With QoS=0 no PUBACK message is sent, so Nulltet can be used. + mocket = Nulltet() + # pylint: disable=protected-access + mqtt_client._sock = mocket + + i = 0 + topic = "foo" + message = "bar" + for _ in range(3 * keep_alive_timeout): + mqtt_client.publish(topic, message, qos=0) + mqtt_client.loop(1) + i += 1 + + # This means no other messages than the PUBLISH messages generated by the code above. + assert len(mocket.sent) == i * (2 + 2 + len(topic) + len(message)) diff --git a/tests/test_port_ssl.py b/tests/test_port_ssl.py index 9ac154da..02ca7200 100644 --- a/tests/test_port_ssl.py +++ b/tests/test_port_ssl.py @@ -1,125 +1,125 @@ -# SPDX-FileCopyrightText: 2023 Vladimír Kotal -# -# SPDX-License-Identifier: Unlicense - -"""tests that verify the connect behavior w.r.t. port number and TLS""" - -import socket -import ssl -from unittest.mock import Mock, call, patch - -import pytest -import adafruit_minimqtt.adafruit_minimqtt as MQTT - - -class TestPortSslSetup: - """This class contains tests that verify how host/port and TLS is set for connect(). - These tests assume that there is no MQTT broker running on the hosts/ports they connect to. - """ - - # pylint: disable=no-self-use - def test_default_port(self) -> None: - """verify default port value and that TLS is not used""" - host = "127.0.0.1" - expected_port = 1883 - - with patch.object(socket.socket, "connect") as connect_mock: - ssl_context = ssl.create_default_context() - mqtt_client = MQTT.MQTT( - broker=host, - socket_pool=socket, - ssl_context=ssl_context, - connect_retries=1, - ) - - connect_mock.side_effect = OSError - ssl_mock = Mock() - ssl_context.wrap_socket = ssl_mock - - with pytest.raises(MQTT.MMQTTException): - mqtt_client.connect() - - ssl_mock.assert_not_called() - - connect_mock.assert_called() - # Assuming the repeated calls will have the same arguments. - connect_mock.assert_has_calls([call((host, expected_port))]) - - # pylint: disable=no-self-use - def test_connect_override(self): - """Test that connect() can override host and port.""" - host = "127.0.0.1" - port = 1883 - - with patch.object(socket.socket, "connect") as connect_mock: - connect_mock.side_effect = OSError("artificial error") - mqtt_client = MQTT.MQTT( - broker=host, - port=port, - socket_pool=socket, - connect_retries=1, - ) - - with pytest.raises(MQTT.MMQTTException): - expected_host = "127.0.0.2" - expected_port = 1884 - assert expected_port != port # port override should differ - assert expected_host != host # host override should differ - mqtt_client.connect(host=expected_host, port=expected_port) - - connect_mock.assert_called() - # Assuming the repeated calls will have the same arguments. - connect_mock.assert_has_calls([call((expected_host, expected_port))]) - - # pylint: disable=no-self-use - @pytest.mark.parametrize("port", (None, 8883)) - def test_tls_port(self, port) -> None: - """verify that when is_ssl=True is set, the default port is 8883 - and the socket is TLS wrapped. Also test that the TLS port can be overridden.""" - host = "127.0.0.1" - - if port is None: - expected_port = 8883 - else: - expected_port = port - - ssl_mock = Mock() - mqtt_client = MQTT.MQTT( - broker=host, - port=port, - socket_pool=socket, - is_ssl=True, - ssl_context=ssl_mock, - connect_retries=1, - ) - - socket_mock = Mock() - connect_mock = Mock(side_effect=OSError) - socket_mock.connect = connect_mock - ssl_mock.wrap_socket = Mock(return_value=socket_mock) - - with pytest.raises(MQTT.MMQTTException): - mqtt_client.connect() - - ssl_mock.wrap_socket.assert_called() - - connect_mock.assert_called() - # Assuming the repeated calls will have the same arguments. - connect_mock.assert_has_calls([call((host, expected_port))]) - - # pylint: disable=no-self-use - def test_tls_without_ssl_context(self) -> None: - """verify that when is_ssl=True is set, the code will check that ssl_context is not None""" - host = "127.0.0.1" - - mqtt_client = MQTT.MQTT( - broker=host, - socket_pool=socket, - is_ssl=True, - ssl_context=None, - connect_retries=1, - ) - - with pytest.raises(AttributeError) as context: - mqtt_client.connect() - assert "ssl_context must be set" in str(context) +# SPDX-FileCopyrightText: 2023 Vladimír Kotal +# +# SPDX-License-Identifier: Unlicense + +"""tests that verify the connect behavior w.r.t. port number and TLS""" + +import socket +import ssl +from unittest.mock import Mock, call, patch + +import pytest +import adafruit_minimqtt.adafruit_minimqtt as MQTT + + +class TestPortSslSetup: + """This class contains tests that verify how host/port and TLS is set for connect(). + These tests assume that there is no MQTT broker running on the hosts/ports they connect to. + """ + + # pylint: disable=no-self-use + def test_default_port(self) -> None: + """verify default port value and that TLS is not used""" + host = "127.0.0.1" + expected_port = 1883 + + with patch.object(socket.socket, "connect") as connect_mock: + ssl_context = ssl.create_default_context() + mqtt_client = MQTT.MQTT( + broker=host, + socket_pool=socket, + ssl_context=ssl_context, + connect_retries=1, + ) + + connect_mock.side_effect = OSError + ssl_mock = Mock() + ssl_context.wrap_socket = ssl_mock + + with pytest.raises(MQTT.MMQTTException): + mqtt_client.connect() + + ssl_mock.assert_not_called() + + connect_mock.assert_called() + # Assuming the repeated calls will have the same arguments. + connect_mock.assert_has_calls([call((host, expected_port))]) + + # pylint: disable=no-self-use + def test_connect_override(self): + """Test that connect() can override host and port.""" + host = "127.0.0.1" + port = 1883 + + with patch.object(socket.socket, "connect") as connect_mock: + connect_mock.side_effect = OSError("artificial error") + mqtt_client = MQTT.MQTT( + broker=host, + port=port, + socket_pool=socket, + connect_retries=1, + ) + + with pytest.raises(MQTT.MMQTTException): + expected_host = "127.0.0.2" + expected_port = 1884 + assert expected_port != port # port override should differ + assert expected_host != host # host override should differ + mqtt_client.connect(host=expected_host, port=expected_port) + + connect_mock.assert_called() + # Assuming the repeated calls will have the same arguments. + connect_mock.assert_has_calls([call((expected_host, expected_port))]) + + # pylint: disable=no-self-use + @pytest.mark.parametrize("port", (None, 8883)) + def test_tls_port(self, port) -> None: + """verify that when is_ssl=True is set, the default port is 8883 + and the socket is TLS wrapped. Also test that the TLS port can be overridden.""" + host = "127.0.0.1" + + if port is None: + expected_port = 8883 + else: + expected_port = port + + ssl_mock = Mock() + mqtt_client = MQTT.MQTT( + broker=host, + port=port, + socket_pool=socket, + is_ssl=True, + ssl_context=ssl_mock, + connect_retries=1, + ) + + socket_mock = Mock() + connect_mock = Mock(side_effect=OSError) + socket_mock.connect = connect_mock + ssl_mock.wrap_socket = Mock(return_value=socket_mock) + + with pytest.raises(MQTT.MMQTTException): + mqtt_client.connect() + + ssl_mock.wrap_socket.assert_called() + + connect_mock.assert_called() + # Assuming the repeated calls will have the same arguments. + connect_mock.assert_has_calls([call((host, expected_port))]) + + # pylint: disable=no-self-use + def test_tls_without_ssl_context(self) -> None: + """verify that when is_ssl=True is set, the code will check that ssl_context is not None""" + host = "127.0.0.1" + + mqtt_client = MQTT.MQTT( + broker=host, + socket_pool=socket, + is_ssl=True, + ssl_context=None, + connect_retries=1, + ) + + with pytest.raises(AttributeError) as context: + mqtt_client.connect() + assert "ssl_context must be set" in str(context) diff --git a/tests/test_subscribe.py b/tests/test_subscribe.py index a66e7a87..6998babc 100644 --- a/tests/test_subscribe.py +++ b/tests/test_subscribe.py @@ -1,228 +1,228 @@ -# SPDX-FileCopyrightText: 2023 Vladimír Kotal -# -# SPDX-License-Identifier: Unlicense - -"""subscribe tests""" - -import logging -import ssl - -import pytest -from mocket import Mocket - -import adafruit_minimqtt.adafruit_minimqtt as MQTT - - -# pylint: disable=unused-argument -def handle_subscribe(client, user_data, topic, qos): - """ - Record topics into user data. - """ - assert topic - assert qos == 0 - - user_data.append(topic) - - -# The MQTT packet contents below were captured using Mosquitto client+server. -testdata = [ - # short topic with remaining length encoded as single byte - ( - "foo/bar", - bytearray([0x90, 0x03, 0x00, 0x01, 0x00]), # SUBACK - bytearray( - [ - 0x82, # fixed header - 0x0C, # remaining length - 0x00, - 0x01, # message ID - 0x00, - 0x07, # topic length - 0x66, # topic - 0x6F, - 0x6F, - 0x2F, - 0x62, - 0x61, - 0x72, - 0x00, # QoS - ] - ), - ), - # same as before but with tuple - ( - ("foo/bar", 0), - bytearray([0x90, 0x03, 0x00, 0x01, 0x00]), # SUBACK - bytearray( - [ - 0x82, # fixed header - 0x0C, # remaining length - 0x00, - 0x01, # message ID - 0x00, - 0x07, # topic length - 0x66, # topic - 0x6F, - 0x6F, - 0x2F, - 0x62, - 0x61, - 0x72, - 0x00, # QoS - ] - ), - ), - # remaining length is encoded as 2 bytes due to long topic name. - ( - "f" + "o" * 257, - bytearray([0x90, 0x03, 0x00, 0x01, 0x00]), # SUBACK - bytearray( - [ - 0x82, # fixed header - 0x87, # remaining length - 0x02, - 0x00, # message ID - 0x01, - 0x01, # topic length - 0x02, - 0x66, # topic - ] - + [0x6F] * 257 - + [0x00] # QoS - ), - ), - # SUBSCRIBE responded to by PUBLISH followed by SUBACK - ( - "foo/bar", - bytearray( - [ - 0x30, # PUBLISH - 0x0C, - 0x00, - 0x07, - 0x66, - 0x6F, - 0x6F, - 0x2F, - 0x62, - 0x61, - 0x72, - 0x66, - 0x6F, - 0x6F, - 0x90, # SUBACK - 0x03, - 0x00, - 0x01, - 0x00, - ] - ), - bytearray( - [ - 0x82, # fixed header - 0x0C, # remaining length - 0x00, - 0x01, # message ID - 0x00, - 0x07, # topic length - 0x66, # topic - 0x6F, - 0x6F, - 0x2F, - 0x62, - 0x61, - 0x72, - 0x00, # QoS - ] - ), - ), - # use list of topics for more coverage. If the range was (1, 10000), that would be - # long enough to use 3 bytes for remaining length, however that would make the test - # run for many minutes even on modern systems, so 1001 is used instead. - # This results in 2 bytes for the remaining length. - ( - [(f"foo/bar{x:04}", 0) for x in range(1, 1001)], - bytearray( - [ - 0x90, - 0xEA, # remaining length - 0x07, - 0x00, # message ID - 0x01, - ] - + [0x00] * 1000 # success for all topics - ), - bytearray( - [ - 0x82, # fixed header - 0xB2, # remaining length - 0x6D, - 0x00, # message ID - 0x01, - ] - + sum( - [ - [0x00, 0x0B] + list(f"foo/bar{x:04}".encode("ascii")) + [0x00] - for x in range(1, 1001) - ], - [], - ) - ), - ), -] - - -@pytest.mark.parametrize( - "topic,to_send,exp_recv", - testdata, - ids=[ - "short_topic", - "short_topic_tuple", - "long_topic", - "publish_first", - "topic_list_long", - ], -) -def test_subscribe(topic, to_send, exp_recv) -> None: - """ - Protocol level testing of SUBSCRIBE and SUBACK packet handling. - - Nothing will travel over the wire, it is all fake. - """ - logging.basicConfig() - logger = logging.getLogger(__name__) - logger.setLevel(logging.DEBUG) - - host = "localhost" - port = 1883 - - subscribed_topics = [] - mqtt_client = MQTT.MQTT( - broker=host, - port=port, - ssl_context=ssl.create_default_context(), - connect_retries=1, - user_data=subscribed_topics, - ) - - mqtt_client.on_subscribe = handle_subscribe - - # patch is_connected() to avoid CONNECT/CONNACK handling. - mqtt_client.is_connected = lambda: True - mocket = Mocket(to_send) - # pylint: disable=protected-access - mqtt_client._sock = mocket - - mqtt_client.logger = logger - - # pylint: disable=logging-fstring-interpolation - logger.info(f"subscribing to {topic}") - mqtt_client.subscribe(topic) - - if isinstance(topic, str): - assert topic in subscribed_topics - elif isinstance(topic, list): - for topic_name, _ in topic: - assert topic_name in subscribed_topics - assert mocket.sent == exp_recv - assert len(mocket._to_send) == 0 +# SPDX-FileCopyrightText: 2023 Vladimír Kotal +# +# SPDX-License-Identifier: Unlicense + +"""subscribe tests""" + +import logging +import ssl + +import pytest +from mocket import Mocket + +import adafruit_minimqtt.adafruit_minimqtt as MQTT + + +# pylint: disable=unused-argument +def handle_subscribe(client, user_data, topic, qos): + """ + Record topics into user data. + """ + assert topic + assert qos == 0 + + user_data.append(topic) + + +# The MQTT packet contents below were captured using Mosquitto client+server. +testdata = [ + # short topic with remaining length encoded as single byte + ( + "foo/bar", + bytearray([0x90, 0x03, 0x00, 0x01, 0x00]), # SUBACK + bytearray( + [ + 0x82, # fixed header + 0x0C, # remaining length + 0x00, + 0x01, # message ID + 0x00, + 0x07, # topic length + 0x66, # topic + 0x6F, + 0x6F, + 0x2F, + 0x62, + 0x61, + 0x72, + 0x00, # QoS + ] + ), + ), + # same as before but with tuple + ( + ("foo/bar", 0), + bytearray([0x90, 0x03, 0x00, 0x01, 0x00]), # SUBACK + bytearray( + [ + 0x82, # fixed header + 0x0C, # remaining length + 0x00, + 0x01, # message ID + 0x00, + 0x07, # topic length + 0x66, # topic + 0x6F, + 0x6F, + 0x2F, + 0x62, + 0x61, + 0x72, + 0x00, # QoS + ] + ), + ), + # remaining length is encoded as 2 bytes due to long topic name. + ( + "f" + "o" * 257, + bytearray([0x90, 0x03, 0x00, 0x01, 0x00]), # SUBACK + bytearray( + [ + 0x82, # fixed header + 0x87, # remaining length + 0x02, + 0x00, # message ID + 0x01, + 0x01, # topic length + 0x02, + 0x66, # topic + ] + + [0x6F] * 257 + + [0x00] # QoS + ), + ), + # SUBSCRIBE responded to by PUBLISH followed by SUBACK + ( + "foo/bar", + bytearray( + [ + 0x30, # PUBLISH + 0x0C, + 0x00, + 0x07, + 0x66, + 0x6F, + 0x6F, + 0x2F, + 0x62, + 0x61, + 0x72, + 0x66, + 0x6F, + 0x6F, + 0x90, # SUBACK + 0x03, + 0x00, + 0x01, + 0x00, + ] + ), + bytearray( + [ + 0x82, # fixed header + 0x0C, # remaining length + 0x00, + 0x01, # message ID + 0x00, + 0x07, # topic length + 0x66, # topic + 0x6F, + 0x6F, + 0x2F, + 0x62, + 0x61, + 0x72, + 0x00, # QoS + ] + ), + ), + # use list of topics for more coverage. If the range was (1, 10000), that would be + # long enough to use 3 bytes for remaining length, however that would make the test + # run for many minutes even on modern systems, so 1001 is used instead. + # This results in 2 bytes for the remaining length. + ( + [(f"foo/bar{x:04}", 0) for x in range(1, 1001)], + bytearray( + [ + 0x90, + 0xEA, # remaining length + 0x07, + 0x00, # message ID + 0x01, + ] + + [0x00] * 1000 # success for all topics + ), + bytearray( + [ + 0x82, # fixed header + 0xB2, # remaining length + 0x6D, + 0x00, # message ID + 0x01, + ] + + sum( + [ + [0x00, 0x0B] + list(f"foo/bar{x:04}".encode("ascii")) + [0x00] + for x in range(1, 1001) + ], + [], + ) + ), + ), +] + + +@pytest.mark.parametrize( + "topic,to_send,exp_recv", + testdata, + ids=[ + "short_topic", + "short_topic_tuple", + "long_topic", + "publish_first", + "topic_list_long", + ], +) +def test_subscribe(topic, to_send, exp_recv) -> None: + """ + Protocol level testing of SUBSCRIBE and SUBACK packet handling. + + Nothing will travel over the wire, it is all fake. + """ + logging.basicConfig() + logger = logging.getLogger(__name__) + logger.setLevel(logging.DEBUG) + + host = "localhost" + port = 1883 + + subscribed_topics = [] + mqtt_client = MQTT.MQTT( + broker=host, + port=port, + ssl_context=ssl.create_default_context(), + connect_retries=1, + user_data=subscribed_topics, + ) + + mqtt_client.on_subscribe = handle_subscribe + + # patch is_connected() to avoid CONNECT/CONNACK handling. + mqtt_client.is_connected = lambda: True + mocket = Mocket(to_send) + # pylint: disable=protected-access + mqtt_client._sock = mocket + + mqtt_client.logger = logger + + # pylint: disable=logging-fstring-interpolation + logger.info(f"subscribing to {topic}") + mqtt_client.subscribe(topic) + + if isinstance(topic, str): + assert topic in subscribed_topics + elif isinstance(topic, list): + for topic_name, _ in topic: + assert topic_name in subscribed_topics + assert mocket.sent == exp_recv + assert len(mocket._to_send) == 0 diff --git a/tests/test_unsubscribe.py b/tests/test_unsubscribe.py index d5b67b65..7880a659 100644 --- a/tests/test_unsubscribe.py +++ b/tests/test_unsubscribe.py @@ -1,153 +1,153 @@ -# SPDX-FileCopyrightText: 2023 Vladimír Kotal -# -# SPDX-License-Identifier: Unlicense - -"""unsubscribe tests""" - -import logging -import ssl - -import pytest -from mocket import Mocket - -import adafruit_minimqtt.adafruit_minimqtt as MQTT - - -# pylint: disable=unused-argument -def handle_unsubscribe(client, user_data, topic, pid): - """ - Record topics into user data. - """ - assert topic - - user_data.append(topic) - - -# The MQTT packet contents below were captured using Mosquitto client+server. -# These are all verbatim, except: -# - message ID that was changed from 2 to 1 since in the real world -# the UNSUBSCRIBE packet followed the SUBSCRIBE packet. -# - the long list topics is sent as individual UNSUBSCRIBE packets by Mosquitto -testdata = [ - # short topic with remaining length encoded as single byte - ( - "foo/bar", - bytearray([0xB0, 0x02, 0x00, 0x01]), - bytearray( - [ - 0xA2, # fixed header - 0x0B, # remaining length - 0x00, # message ID - 0x01, - 0x00, # topic length - 0x07, - 0x66, # topic - 0x6F, - 0x6F, - 0x2F, - 0x62, - 0x61, - 0x72, - ] - ), - ), - # remaining length is encoded as 2 bytes due to long topic name. - ( - "f" + "o" * 257, - bytearray([0xB0, 0x02, 0x00, 0x01]), - bytearray( - [ - 0xA2, # fixed header - 0x86, # remaining length - 0x02, - 0x00, # message ID - 0x01, - 0x01, # topic length - 0x02, - 0x66, # topic - ] - + [0x6F] * 257 - ), - ), - # use list of topics for more coverage. If the range was (1, 10000), that would be - # long enough to use 3 bytes for remaining length, however that would make the test - # run for many minutes even on modern systems, so 1000 is used instead. - # This results in 2 bytes for the remaining length. - ( - [f"foo/bar{x:04}" for x in range(1, 1000)], - bytearray([0xB0, 0x02, 0x00, 0x01]), - bytearray( - [ - 0xA2, # fixed header - 0xBD, # remaining length - 0x65, - 0x00, # message ID - 0x01, - ] - + sum( - [ - [0x00, 0x0B] + list(f"foo/bar{x:04}".encode("ascii")) - for x in range(1, 1000) - ], - [], - ) - ), - ), -] - - -@pytest.mark.parametrize( - "topic,to_send,exp_recv", - testdata, - ids=["short_topic", "long_topic", "topic_list_long"], -) -def test_unsubscribe(topic, to_send, exp_recv) -> None: - """ - Protocol level testing of UNSUBSCRIBE and UNSUBACK packet handling. - - Nothing will travel over the wire, it is all fake. - Also, the topics are not subscribed into. - """ - logging.basicConfig() - logger = logging.getLogger(__name__) - logger.setLevel(logging.DEBUG) - - host = "localhost" - port = 1883 - - unsubscribed_topics = [] - mqtt_client = MQTT.MQTT( - broker=host, - port=port, - ssl_context=ssl.create_default_context(), - connect_retries=1, - user_data=unsubscribed_topics, - ) - - mqtt_client.on_unsubscribe = handle_unsubscribe - - # patch is_connected() to avoid CONNECT/CONNACK handling. - mqtt_client.is_connected = lambda: True - mocket = Mocket(to_send) - # pylint: disable=protected-access - mqtt_client._sock = mocket - - mqtt_client.logger = logger - - # pylint: disable=protected-access - if isinstance(topic, str): - mqtt_client._subscribed_topics = [topic] - elif isinstance(topic, list): - mqtt_client._subscribed_topics = topic - - # pylint: disable=logging-fstring-interpolation - logger.info(f"unsubscribing from {topic}") - mqtt_client.unsubscribe(topic) - - if isinstance(topic, str): - assert topic in unsubscribed_topics - elif isinstance(topic, list): - for topic_name in topic: - assert topic_name in unsubscribed_topics - assert mocket.sent == exp_recv - assert len(mocket._to_send) == 0 +# SPDX-FileCopyrightText: 2023 Vladimír Kotal +# +# SPDX-License-Identifier: Unlicense + +"""unsubscribe tests""" + +import logging +import ssl + +import pytest +from mocket import Mocket + +import adafruit_minimqtt.adafruit_minimqtt as MQTT + + +# pylint: disable=unused-argument +def handle_unsubscribe(client, user_data, topic, pid): + """ + Record topics into user data. + """ + assert topic + + user_data.append(topic) + + +# The MQTT packet contents below were captured using Mosquitto client+server. +# These are all verbatim, except: +# - message ID that was changed from 2 to 1 since in the real world +# the UNSUBSCRIBE packet followed the SUBSCRIBE packet. +# - the long list topics is sent as individual UNSUBSCRIBE packets by Mosquitto +testdata = [ + # short topic with remaining length encoded as single byte + ( + "foo/bar", + bytearray([0xB0, 0x02, 0x00, 0x01]), + bytearray( + [ + 0xA2, # fixed header + 0x0B, # remaining length + 0x00, # message ID + 0x01, + 0x00, # topic length + 0x07, + 0x66, # topic + 0x6F, + 0x6F, + 0x2F, + 0x62, + 0x61, + 0x72, + ] + ), + ), + # remaining length is encoded as 2 bytes due to long topic name. + ( + "f" + "o" * 257, + bytearray([0xB0, 0x02, 0x00, 0x01]), + bytearray( + [ + 0xA2, # fixed header + 0x86, # remaining length + 0x02, + 0x00, # message ID + 0x01, + 0x01, # topic length + 0x02, + 0x66, # topic + ] + + [0x6F] * 257 + ), + ), + # use list of topics for more coverage. If the range was (1, 10000), that would be + # long enough to use 3 bytes for remaining length, however that would make the test + # run for many minutes even on modern systems, so 1000 is used instead. + # This results in 2 bytes for the remaining length. + ( + [f"foo/bar{x:04}" for x in range(1, 1000)], + bytearray([0xB0, 0x02, 0x00, 0x01]), + bytearray( + [ + 0xA2, # fixed header + 0xBD, # remaining length + 0x65, + 0x00, # message ID + 0x01, + ] + + sum( + [ + [0x00, 0x0B] + list(f"foo/bar{x:04}".encode("ascii")) + for x in range(1, 1000) + ], + [], + ) + ), + ), +] + + +@pytest.mark.parametrize( + "topic,to_send,exp_recv", + testdata, + ids=["short_topic", "long_topic", "topic_list_long"], +) +def test_unsubscribe(topic, to_send, exp_recv) -> None: + """ + Protocol level testing of UNSUBSCRIBE and UNSUBACK packet handling. + + Nothing will travel over the wire, it is all fake. + Also, the topics are not subscribed into. + """ + logging.basicConfig() + logger = logging.getLogger(__name__) + logger.setLevel(logging.DEBUG) + + host = "localhost" + port = 1883 + + unsubscribed_topics = [] + mqtt_client = MQTT.MQTT( + broker=host, + port=port, + ssl_context=ssl.create_default_context(), + connect_retries=1, + user_data=unsubscribed_topics, + ) + + mqtt_client.on_unsubscribe = handle_unsubscribe + + # patch is_connected() to avoid CONNECT/CONNACK handling. + mqtt_client.is_connected = lambda: True + mocket = Mocket(to_send) + # pylint: disable=protected-access + mqtt_client._sock = mocket + + mqtt_client.logger = logger + + # pylint: disable=protected-access + if isinstance(topic, str): + mqtt_client._subscribed_topics = [topic] + elif isinstance(topic, list): + mqtt_client._subscribed_topics = topic + + # pylint: disable=logging-fstring-interpolation + logger.info(f"unsubscribing from {topic}") + mqtt_client.unsubscribe(topic) + + if isinstance(topic, str): + assert topic in unsubscribed_topics + elif isinstance(topic, list): + for topic_name in topic: + assert topic_name in unsubscribed_topics + assert mocket.sent == exp_recv + assert len(mocket._to_send) == 0 diff --git a/tox.ini b/tox.ini index d0cddcf3..2fc5fb8c 100644 --- a/tox.ini +++ b/tox.ini @@ -1,39 +1,39 @@ -# SPDX-FileCopyrightText: 2023 Vladimír Kotal -# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries -# -# SPDX-License-Identifier: MIT - -[tox] -envlist = py311 - -[testenv] -description = run tests -deps = - pytest==7.4.3 -commands = pytest - -[testenv:coverage] -description = run coverage -deps = - pytest==7.4.3 - pytest-cov==4.1.0 -package = editable -commands = - coverage run --source=. --omit=tests/* --branch {posargs} -m pytest - coverage report - coverage html - -[testenv:lint] -description = run linters -deps = - pre-commit==3.6.0 -skip_install = true -commands = pre-commit run {posargs} - -[testenv:docs] -description = build docs -deps = - -r requirements.txt - -r docs/requirements.txt -skip_install = true -commands = sphinx-build -E -W -b html docs/. _build/html +# SPDX-FileCopyrightText: 2023 Vladimír Kotal +# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +[tox] +envlist = py311 + +[testenv] +description = run tests +deps = + pytest==7.4.3 +commands = pytest + +[testenv:coverage] +description = run coverage +deps = + pytest==7.4.3 + pytest-cov==4.1.0 +package = editable +commands = + coverage run --source=. --omit=tests/* --branch {posargs} -m pytest + coverage report + coverage html + +[testenv:lint] +description = run linters +deps = + pre-commit==3.6.0 +skip_install = true +commands = pre-commit run {posargs} + +[testenv:docs] +description = build docs +deps = + -r requirements.txt + -r docs/requirements.txt +skip_install = true +commands = sphinx-build -E -W -b html docs/. _build/html