diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..21c125c --- /dev/null +++ b/.gitattributes @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense + +.py text eol=lf +.rst text eol=lf +.txt text eol=lf +.yaml text eol=lf +.toml text eol=lf +.license text eol=lf +.md text eol=lf diff --git a/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md b/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md index 71ef8f8..8de294e 100644 --- a/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md +++ b/.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md @@ -4,7 +4,7 @@ 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://circuitpython.readthedocs.io/en/latest/docs/design_guide.html +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 diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ca35544..041a337 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -10,66 +10,5 @@ jobs: test: runs-on: ubuntu-latest steps: - - name: Dump GitHub context - env: - GITHUB_CONTEXT: ${{ toJson(github) }} - run: echo "$GITHUB_CONTEXT" - - name: Translate Repo Name For Build Tools filename_prefix - id: repo-name - run: | - echo ::set-output name=repo-name::$( - echo ${{ github.repository }} | - awk -F '\/' '{ print tolower($2) }' | - tr '_' '-' - ) - - name: Set up Python 3.7 - uses: actions/setup-python@v1 - with: - python-version: 3.7 - - name: Versions - run: | - python3 --version - - name: Checkout Current Repo - uses: actions/checkout@v1 - with: - submodules: true - - name: Checkout tools repo - uses: actions/checkout@v2 - with: - repository: adafruit/actions-ci-circuitpython-libs - path: actions-ci - - name: Install dependencies - # (e.g. - apt-get: gettext, etc; pip: circuitpython-build-tools, requirements.txt; etc.) - run: | - source actions-ci/install.sh - - name: Pip install Sphinx, pre-commit - run: | - pip install --force-reinstall Sphinx sphinx-rtd-theme pre-commit - - name: Library version - run: git describe --dirty --always --tags - - name: Pre-commit hooks - run: | - pre-commit run --all-files - - name: Build assets - run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location . - - name: Archive bundles - uses: actions/upload-artifact@v2 - with: - name: bundles - path: ${{ github.workspace }}/bundles/ - - name: Build docs - working-directory: docs - run: sphinx-build -E -W -b html . _build/html - - name: Check For setup.py - id: need-pypi - run: | - echo ::set-output name=setup-py::$( find . -wholename './setup.py' ) - - name: Build Python package - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') - run: | - pip install --upgrade setuptools wheel twine readme_renderer testresources - python setup.py sdist - python setup.py bdist_wheel --universal - twine check dist/* - - name: Setup problem matchers - uses: adafruit/circuitpython-action-library-ci-problem-matchers@v1 + - name: Run Build CI workflow + uses: adafruit/workflows-circuitpython-libs/build@main diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml deleted file mode 100644 index 6d0015a..0000000 --- a/.github/workflows/release.yml +++ /dev/null @@ -1,85 +0,0 @@ -# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries -# -# SPDX-License-Identifier: MIT - -name: Release Actions - -on: - release: - types: [published] - -jobs: - upload-release-assets: - runs-on: ubuntu-latest - steps: - - name: Dump GitHub context - env: - GITHUB_CONTEXT: ${{ toJson(github) }} - run: echo "$GITHUB_CONTEXT" - - name: Translate Repo Name For Build Tools filename_prefix - id: repo-name - run: | - echo ::set-output name=repo-name::$( - echo ${{ github.repository }} | - awk -F '\/' '{ print tolower($2) }' | - tr '_' '-' - ) - - name: Set up Python 3.6 - uses: actions/setup-python@v1 - with: - python-version: 3.6 - - name: Versions - run: | - python3 --version - - name: Checkout Current Repo - uses: actions/checkout@v1 - with: - submodules: true - - name: Checkout tools repo - uses: actions/checkout@v2 - with: - repository: adafruit/actions-ci-circuitpython-libs - path: actions-ci - - name: Install deps - run: | - source actions-ci/install.sh - - name: Build assets - run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location . - - name: Upload Release Assets - # the 'official' actions version does not yet support dynamically - # supplying asset names to upload. @csexton's version chosen based on - # discussion in the issue below, as its the simplest to implement and - # allows for selecting files with a pattern. - # https://github.com/actions/upload-release-asset/issues/4 - #uses: actions/upload-release-asset@v1.0.1 - uses: csexton/release-asset-action@master - with: - pattern: "bundles/*" - github-token: ${{ secrets.GITHUB_TOKEN }} - - upload-pypi: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v1 - - name: Check For setup.py - id: need-pypi - run: | - echo ::set-output name=setup-py::$( find . -wholename './setup.py' ) - - name: Set up Python - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') - uses: actions/setup-python@v1 - with: - python-version: '3.x' - - name: Install dependencies - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') - run: | - python -m pip install --upgrade pip - pip install setuptools wheel twine - - name: Build and publish - if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') - env: - TWINE_USERNAME: ${{ secrets.pypi_username }} - TWINE_PASSWORD: ${{ secrets.pypi_password }} - run: | - python setup.py sdist - twine upload dist/* diff --git a/.github/workflows/release_gh.yml b/.github/workflows/release_gh.yml new file mode 100644 index 0000000..9acec60 --- /dev/null +++ b/.github/workflows/release_gh.yml @@ -0,0 +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 }} diff --git a/.github/workflows/release_pypi.yml b/.github/workflows/release_pypi.yml new file mode 100644 index 0000000..65775b7 --- /dev/null +++ b/.github/workflows/release_pypi.yml @@ -0,0 +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 }} diff --git a/.gitignore b/.gitignore index a966824..db3d538 100644 --- a/.gitignore +++ b/.gitignore @@ -1,18 +1,48 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-FileCopyrightText: 2022 Kattni Rembor, written for Adafruit Industries # -# SPDX-License-Identifier: Unlicense +# 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 -.idea + +# Python-specific files __pycache__ -_build *.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 -.python-version -build*/ -bundles +.venv + +# MacOS-specific files *.DS_Store -.eggs -dist -**/*.egg-info + +# IDE-specific files +.idea .vscode +*~ diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 43d1385..ff19dde 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,42 +1,21 @@ -# SPDX-FileCopyrightText: 2020 Diego Elio Pettenò +# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries # # SPDX-License-Identifier: Unlicense repos: -- repo: https://github.com/python/black - rev: 20.8b1 + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.5.0 hooks: - - id: black -- repo: https://github.com/fsfe/reuse-tool - rev: v0.12.1 + - id: check-yaml + - id: end-of-file-fixer + - id: trailing-whitespace + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.3.4 hooks: - - id: reuse -- repo: https://github.com/pre-commit/pre-commit-hooks - rev: v2.3.0 + - id: ruff-format + - id: ruff + args: ["--fix"] + - repo: https://github.com/fsfe/reuse-tool + rev: v3.0.1 hooks: - - id: check-yaml - - id: end-of-file-fixer - - id: trailing-whitespace -- repo: https://github.com/pycqa/pylint - rev: v2.11.1 - hooks: - - id: pylint - name: pylint (library code) - types: [python] - args: - - --disable=consider-using-f-string,duplicate-code - 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=missing-docstring,invalid-name,consider-using-f-string,duplicate-code - - id: pylint - name: pylint (test code) - description: Run pylint rules on "tests/*.py" files - types: [python] - files: "^tests/" - args: - - --disable=missing-docstring,consider-using-f-string,duplicate-code + - id: reuse diff --git a/.pylintrc b/.pylintrc deleted file mode 100644 index cfd1c41..0000000 --- a/.pylintrc +++ /dev/null @@ -1,436 +0,0 @@ -# SPDX-FileCopyrightText: 2021 ladyada 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 blacklist. They should be base names, not -# paths. -ignore=CVS - -# Add files or directories matching the regex patterns to the blacklist. 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= - -# 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,print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call -disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error,bad-continuation,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 - -# List of optional constructs for which whitespace checking is disabled. `dict- -# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. -# `trailing-comma` allows a space between comma and closing bracket: (a, ). -# `empty-line` allows space-only lines. -no-space-check=trailing-comma,dict-separator - -# 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=4 - - -[BASIC] - -# Naming hint for argument names -argument-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct argument names -argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Naming hint for attribute names -attr-name-hint=(([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 - -# Naming hint for class attribute names -class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ - -# Regular expression matching correct class attribute names -class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ - -# Naming hint for class names -# class-name-hint=[A-Z_][a-zA-Z0-9]+$ -class-name-hint=[A-Z_][a-zA-Z0-9_]+$ - -# Regular expression matching correct class names -# class-rgx=[A-Z_][a-zA-Z0-9]+$ -class-rgx=[A-Z_][a-zA-Z0-9_]+$ - -# Naming hint for constant names -const-name-hint=(([A-Z_][A-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 - -# Naming hint for function names -function-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# 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 - -# Naming hint for inline iteration names -inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$ - -# Regular expression matching correct inline iteration names -inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ - -# Naming hint for method names -method-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Regular expression matching correct method names -method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# Naming hint for module names -module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-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 - -# Naming hint for variable names -variable-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ - -# 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=Exception diff --git a/.readthedocs.yaml b/.readthedocs.yaml new file mode 100644 index 0000000..255dafd --- /dev/null +++ b/.readthedocs.yaml @@ -0,0 +1,22 @@ +# 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 + +sphinx: + configuration: docs/conf.py + +build: + os: ubuntu-lts-latest + tools: + python: "3" + +python: + install: + - requirements: docs/requirements.txt + - requirements: requirements.txt diff --git a/.readthedocs.yml b/.readthedocs.yml deleted file mode 100644 index 49dcab3..0000000 --- a/.readthedocs.yml +++ /dev/null @@ -1,7 +0,0 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# -# SPDX-License-Identifier: Unlicense - -python: - version: 3 -requirements_file: docs/requirements.txt diff --git a/README.rst b/README.rst index 34e640f..8b7f415 100644 --- a/README.rst +++ b/README.rst @@ -1,11 +1,11 @@ Introduction ============ -.. image:: https://readthedocs.org/projects/adafruit-circuitpython-fona/badge/?version=latest - :target: https://circuitpython.readthedocs.io/projects/fona/en/latest/ +.. image:: https://readthedocs.org/projects/fona/badge/?version=latest + :target: https://docs.circuitpython.org/projects/fona/en/latest/ :alt: Documentation Status -.. image:: https://img.shields.io/discord/327254708534116352.svg +.. image:: https://raw.githubusercontent.com/adafruit/Adafruit_CircuitPython_Bundle/main/badges/adafruit_discord.svg :target: https://adafru.it/discord :alt: Discord @@ -13,9 +13,9 @@ Introduction :target: https://github.com/adafruit/Adafruit_CircuitPython_FONA/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 +.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json + :target: https://github.com/astral-sh/ruff + :alt: Code Style: Ruff CircuitPython library for the `Adafruit FONA `_ cellular module. @@ -52,8 +52,8 @@ To install in a virtual environment in your current project: .. code-block:: shell mkdir project-name && cd project-name - python3 -m venv .env - source .env/bin/activate + python3 -m venv .venv + source .venv/bin/activate pip3 install adafruit-circuitpython-fona Usage Example @@ -64,7 +64,9 @@ Please see the examples directory for code usage. Documentation ============= -API documentation for this library can be found on `Read the Docs `_. +API documentation for this library can be found on `Read the Docs `_. + +For information on building library documentation, please check out `this guide `_. Contributing ============ @@ -72,8 +74,3 @@ Contributing Contributions are welcome! Please read our `Code of Conduct `_ before contributing to help this project stay welcoming. - -Documentation -============= - -For information on building library documentation, please check out `this guide `_. diff --git a/adafruit_fona/adafruit_fona.py b/adafruit_fona/adafruit_fona.py index 4a71c84..c69c691 100644 --- a/adafruit_fona/adafruit_fona.py +++ b/adafruit_fona/adafruit_fona.py @@ -20,11 +20,27 @@ https://github.com/adafruit/circuitpython/releases """ + import time + from micropython import const from simpleio import map_range -__version__ = "0.0.0-auto.0" +try: + from typing import Optional, Tuple, Union + + from busio import UART + from circuitpython_typing import ReadableBuffer + from digitalio import DigitalInOut + + try: + from typing import Literal + except ImportError: + from typing_extensions import Literal +except ImportError: + pass + +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_FONA.git" FONA_DEFAULT_TIMEOUT_MS = 500 # TODO: Check this against arduino... @@ -41,6 +57,7 @@ # FONA Versions FONA_800_L = const(0x01) FONA_800_H = const(0x6) +FONA_800_C = const(0x7) FONA_808_V1 = const(0x2) FONA_808_V2 = const(0x3) FONA_3G_A = const(0x4) @@ -51,21 +68,25 @@ FONA_SMS_STORAGE_INTERNAL = b'"ME"' # Internal storage on the FONA -# pylint: disable=too-many-instance-attributes, too-many-public-methods class FONA: """CircuitPython FONA module interface. - :param ~busio.uart UART: FONA UART connection. - :param ~digialio RST: FONA RST pin. - :param ~digialio RI: Optional FONA Ring Interrupt (RI) pin. - :param bool debug: Enable debugging output. + :param ~busio.UART uart: FONA UART connection. + :param ~digitalio.DigitalInOut rst: FONA RST pin. + :param ~digitalio.DigitalInOut ri: Optional FONA Ring Interrupt (RI) pin. + :param bool debug: Enable debugging output. """ TCP_MODE = const(0) # TCP socket UDP_MODE = const(1) # UDP socket - # pylint: disable=too-many-arguments - def __init__(self, uart, rst, ri=None, debug=False): + def __init__( + self, + uart: UART, + rst: DigitalInOut, + ri: Optional[DigitalInOut] = None, + debug: bool = False, + ) -> None: self._buf = b"" # shared buffer self._fona_type = 0 self._debug = debug @@ -78,8 +99,7 @@ def __init__(self, uart, rst, ri=None, debug=False): if not self._init_fona(): raise RuntimeError("Unable to find FONA. Please check connections.") - # pylint: disable=too-many-branches, too-many-statements - def _init_fona(self): + def _init_fona(self) -> bool: """Initializes FONA module.""" self.reset() @@ -126,17 +146,23 @@ def _init_fona(self): self._fona_type = FONA_3G_A elif self._buf.find(b"SIMCOM_SIM5320E") != -1: self._fona_type = FONA_3G_E - - if self._fona_type == FONA_800_L: - # determine if SIM800H + elif self._buf.find(b"SIM800") != -1: self._uart_write(b"AT+GMM\r\n") self._read_line(multiline=True) if self._buf.find(b"SIM800H") != -1: self._fona_type = FONA_800_H + elif self._buf.find(b"SIM800L") != -1: + self._fona_type = FONA_800_L + elif self._buf.find(b"SIM800C") != -1: + self._fona_type = FONA_800_C + + if self._debug and self._fona_type == 0: + print(f"Unsupported module: {self._buf}") + return True - def factory_reset(self): + def factory_reset(self) -> bool: """Resets modem to factory configuration.""" self._uart_write(b"ATZ\r\n") @@ -144,7 +170,7 @@ def factory_reset(self): return False return True - def reset(self): + def reset(self) -> None: """Performs a hardware reset on the modem.""" if self._debug: print("* Reset FONA") @@ -156,15 +182,14 @@ def reset(self): self._rst.value = True @property - # pylint: disable=too-many-return-statements - def version(self): + def version(self) -> int: """The version of the FONA module. Can be FONA_800_L, FONA_800_H, FONA_808_V1, FONA_808_V2, FONA_3G_A, FONA3G_E. """ return self._fona_type @property - def iemi(self): + def iemi(self) -> str: """FONA Module's IEMI (International Mobile Equipment Identity) number.""" if self._debug: print("FONA IEMI") @@ -176,7 +201,7 @@ def iemi(self): return iemi.decode("utf-8") @property - def local_ip(self): + def local_ip(self) -> Optional[str]: """Module's local IP address, None if not set.""" self._uart_write(b"AT+CIFSR\r\n") self._read_line() @@ -187,7 +212,7 @@ def local_ip(self): return ip_addr @property - def iccid(self): + def iccid(self) -> str: """SIM Card's unique ICCID (Integrated Circuit Card Identifier).""" if self._debug: print("ICCID") @@ -197,7 +222,7 @@ def iccid(self): return iccid @property - def gprs(self): + def gprs(self) -> bool: """GPRS (General Packet Radio Services) power status.""" if not self._send_parse_reply(b"AT+CGATT?", b"+CGATT: ", ":"): return False @@ -205,11 +230,15 @@ def gprs(self): return False return True - # pylint: disable=too-many-return-statements - def set_gprs(self, apn=None, enable=True): + def set_gprs( + self, + apn: Optional[Tuple[str, Optional[str], Optional[str]]] = None, + enable: bool = True, + ) -> bool: """Configures and brings up GPRS. - :param bool enable: Enables or disables GPRS. + :param tuple apn: The APN information + :param bool enable: Enables or disables GPRS. """ if enable: apn_name, apn_user, apn_pass = apn @@ -224,9 +253,7 @@ def set_gprs(self, apn=None, enable=True): return False # disconnect all sockets - if not self._send_check_reply( - b"AT+CIPSHUT", reply=b"SHUT OK", timeout=20000 - ): + if not self._send_check_reply(b"AT+CIPSHUT", reply=b"SHUT OK", timeout=20000): return False if not self._send_check_reply(b"AT+CGATT=1", reply=REPLY_OK, timeout=10000): @@ -272,9 +299,7 @@ def set_gprs(self, apn=None, enable=True): return False # Open GPRS context - if not self._send_check_reply( - b"AT+SAPBR=1,1", reply=REPLY_OK, timeout=1850 - ): + if not self._send_check_reply(b"AT+SAPBR=1,1", reply=REPLY_OK, timeout=1850): return False # Bring up wireless connection @@ -283,17 +308,13 @@ def set_gprs(self, apn=None, enable=True): if not self.local_ip: return False - else: - # reset PDP state - if not self._send_check_reply( - b"AT+CIPSHUT", reply=b"SHUT OK", timeout=20000 - ): - return False + elif not self._send_check_reply(b"AT+CIPSHUT", reply=b"SHUT OK", timeout=20000): + return False return True @property - def network_status(self): + def network_status(self) -> int: """The status of the cellular network.""" self._read_line() if self._debug: @@ -306,7 +327,7 @@ def network_status(self): return status @property - def rssi(self): + def rssi(self) -> float: """The received signal strength indicator for the cellular network we are connected to. """ @@ -331,7 +352,7 @@ def rssi(self): return rssi @property - def gps(self): + def gps(self) -> int: """Module's GPS status.""" if self._debug: print("GPS Fix") @@ -340,7 +361,7 @@ def gps(self): # Instead just look for a fix and if found assume it's a 3D fix. self._get_reply(b"AT+CGNSINF") - if not b"+CGNSINF: " in self._buf: + if b"+CGNSINF: " not in self._buf: return False status = int(self._buf[10:11].decode("utf-8")) @@ -348,14 +369,12 @@ def gps(self): status = 3 # assume 3D fix self._read_line() else: - raise NotImplementedError( - "FONA 808 v1 not currently supported by this library." - ) + raise NotImplementedError("FONA 808 v1 not currently supported by this library.") return status @gps.setter - def gps(self, gps_on=False): - if self._fona_type not in (FONA_3G_A, FONA_3G_E, FONA_808_V1, FONA_808_V2): + def gps(self, gps_on: bool = False) -> bool: + if self._fona_type not in {FONA_3G_A, FONA_3G_E, FONA_808_V1, FONA_808_V2}: raise TypeError("GPS unsupported for this FONA module.") # check if already enabled or disabled @@ -373,23 +392,21 @@ def gps(self, gps_on=False): if self._fona_type == FONA_808_V2: # try GNS if not self._send_check_reply(b"AT+CGNSPWR=1", reply=REPLY_OK): return False - else: - if not self._send_parse_reply(b"AT+CGPSPWR=1", reply_data=REPLY_OK): - return False - else: - if self._fona_type == FONA_808_V2: # try GNS - if not self._send_check_reply(b"AT+CGNSPWR=0", reply=REPLY_OK): - return False - if not self._send_check_reply(b"AT+CGPSPWR=0", reply=REPLY_OK): - return False + elif not self._send_parse_reply(b"AT+CGPSPWR=1", reply_data=REPLY_OK): + return False + elif self._fona_type == FONA_808_V2: # try GNS + if not self._send_check_reply(b"AT+CGNSPWR=0", reply=REPLY_OK): + return False + if not self._send_check_reply(b"AT+CGPSPWR=0", reply=REPLY_OK): + return False return True - def pretty_ip(self, ip): # pylint: disable=no-self-use, invalid-name + def pretty_ip(self, ip: ReadableBuffer) -> str: """Converts a bytearray IP address to a dotted-quad string for printing""" return "%d.%d.%d.%d" % (ip[0], ip[1], ip[2], ip[3]) - def unpretty_ip(self, ip): # pylint: disable=no-self-use, invalid-name + def unpretty_ip(self, ip: str) -> bytes: """Converts a dotted-quad string to a bytearray IP address""" octets = [int(x) for x in ip.split(".")] return bytes(octets) @@ -397,28 +414,27 @@ def unpretty_ip(self, ip): # pylint: disable=no-self-use, invalid-name ### SMS ### @property - def enable_sms_notification(self): + def enable_sms_notification(self) -> bool: """Checks if SMS notifications are enabled.""" if not self._send_parse_reply(b"AT+CNMI?\r\n", b"+CNMI:", idx=1): return False return self._buf @enable_sms_notification.setter - def enable_sms_notification(self, enable=True): + def enable_sms_notification(self, enable: bool = True) -> bool: if enable: if not self._send_check_reply(b"AT+CNMI=2,1\r\n", reply=REPLY_OK): return False - else: - if not self._send_check_reply(b"AT+CNMI=2,0\r\n", reply=REPLY_OK): - return False + elif not self._send_check_reply(b"AT+CNMI=2,0\r\n", reply=REPLY_OK): + return False return True - def receive_sms(self): + def receive_sms(self) -> Tuple[str, str]: """Checks for a message notification from the FONA module, replies back with the a tuple containing (sender, message). - NOTE: This method needs to be polled consistently due to the lack - of hw-based interrupts in CircuitPython. + :note: This method needs to be polled consistently due to the lack + of hw-based interrupts in CircuitPython. """ if self._ri is not None: # poll the RI pin if self._ri.value: @@ -437,11 +453,11 @@ def receive_sms(self): return sender, message.strip() - def send_sms(self, phone_number, message): + def send_sms(self, phone_number: int, message: str) -> bool: """Sends a message SMS to a phone number. + :param int phone_number: Destination phone number. :param str message: Message to send to the phone number. - """ if not hasattr(phone_number, "to_bytes"): raise TypeError("Phone number must be integer") @@ -461,7 +477,7 @@ def send_sms(self, phone_number, message): # write out message and ^z self._uart_write((message + chr(26)).encode()) - if self._fona_type in (FONA_3G_A, FONA_3G_E): + if self._fona_type in {FONA_3G_A, FONA_3G_E}: self._read_line(200) # eat first 'CRLF' self._read_line(200) # eat second 'CRLF' @@ -474,10 +490,10 @@ def send_sms(self, phone_number, message): return False return True - def num_sms(self, sim_storage=True): + def num_sms(self, sim_storage: bool = True) -> int: """Returns the number of SMS messages stored in memory. - :param bool sim_storage: SMS storage on the SIM, otherwise internal storage on FONA chip. + :param bool sim_storage: SMS storage on the SIM, otherwise internal storage on FONA chip. """ if not self._send_check_reply(b"AT+CMGF=1", reply=REPLY_OK): raise RuntimeError("Operating mode not supported by FONA module.") @@ -485,11 +501,8 @@ def num_sms(self, sim_storage=True): if sim_storage: # ask how many SMS are stored if self._send_parse_reply(b"AT+CPMS?", FONA_SMS_STORAGE_SIM + b",", idx=1): return self._buf - else: - if self._send_parse_reply( - b"AT+CPMS?", FONA_SMS_STORAGE_INTERNAL + b",", idx=1 - ): - return self._buf + elif self._send_parse_reply(b"AT+CPMS?", FONA_SMS_STORAGE_INTERNAL + b",", idx=1): + return self._buf self._read_line() # eat OK if self._send_parse_reply(b"AT+CPMS?", b'"SM",', idx=1): @@ -500,44 +513,39 @@ def num_sms(self, sim_storage=True): return self._buf return 0 - def delete_sms(self, sms_slot): + def delete_sms(self, sms_slot: int) -> bool: """Deletes a SMS message from a storage (internal or sim) slot - :param int sms_slot: SMS SIM or FONA memory slot number. + :param int sms_slot: SMS SIM or FONA memory slot number. """ if not self._send_check_reply(b"AT+CMGF=1", reply=REPLY_OK): return False - if not self._send_check_reply( - b"AT+CMGD=" + str(sms_slot).encode(), reply=REPLY_OK - ): + if not self._send_check_reply(b"AT+CMGD=" + str(sms_slot).encode(), reply=REPLY_OK): return False return True - def delete_all_sms(self): + def delete_all_sms(self) -> bool: """Deletes all SMS messages on the FONA SIM.""" self._read_line() if not self._send_check_reply(b"AT+CMGF=1", reply=REPLY_OK): return False - if self._fona_type in (FONA_3G_A, FONA_3G_E): + if self._fona_type in {FONA_3G_A, FONA_3G_E}: num_sms = self.num_sms() for slot in range(0, num_sms): if not self.delete_sms(slot): return False - else: # DEL ALL on 808 - if not self._send_check_reply( - b'AT+CMGDA="DEL ALL"', reply=REPLY_OK, timeout=25000 - ): - return False + elif not self._send_check_reply(b'AT+CMGDA="DEL ALL"', reply=REPLY_OK, timeout=25000): + return False return True - def read_sms(self, sms_slot): + def read_sms(self, sms_slot: int) -> Tuple[str, str]: """Reads and parses SMS messages from FONA device. Returns the SMS sender's phone number and the message contents as a tuple. - :param int sms_slot: SMS SIM or FONA memory slot number. + :param int sms_slot: SMS SIM or FONA memory slot number. """ if not self._send_check_reply(b"AT+CMGF=1", reply=REPLY_OK): return False @@ -569,10 +577,10 @@ def read_sms(self, sms_slot): ### Socket API (TCP, UDP) ### - def get_host_by_name(self, hostname): + def get_host_by_name(self, hostname: str) -> Union[str, Literal[False]]: """Converts a hostname to a packed 4-byte IP address. - :param str hostname: Destination server. + :param str hostname: Destination server. """ self._read_line() if self._debug: @@ -580,9 +588,7 @@ def get_host_by_name(self, hostname): if isinstance(hostname, str): hostname = bytes(hostname, "utf-8") - if not self._send_check_reply( - b'AT+CDNSGIP="' + hostname + b'"\r\n', reply=REPLY_OK - ): + if not self._send_check_reply(b'AT+CDNSGIP="' + hostname + b'"\r\n', reply=REPLY_OK): return False self._read_line() @@ -590,7 +596,7 @@ def get_host_by_name(self, hostname): self._read_line() return self._buf - def get_socket(self): + def get_socket(self) -> int: """Obtains a socket, if available.""" if self._debug: print("*** Get socket") @@ -613,14 +619,12 @@ def get_socket(self): print("Allocated socket #%d" % allocated_socket) return allocated_socket - def remote_ip(self, sock_num): + def remote_ip(self, sock_num: int) -> str: """Returns the IP address of the remote server. - :param int sock_num: Desired socket. + :param int sock_num: Desired socket. """ - assert ( - sock_num < FONA_MAX_SOCKETS - ), "Provided socket exceeds the maximum number of \ + assert sock_num < FONA_MAX_SOCKETS, "Provided socket exceeds the maximum number of \ sockets for the FONA module." self._uart_write(b"AT+CIPSTATUS=" + str(sock_num).encode() + b"\r\n") self._read_line(100) @@ -628,14 +632,12 @@ def remote_ip(self, sock_num): self._parse_reply(b"+CIPSTATUS:", idx=3) return self._buf - def socket_status(self, sock_num): + def socket_status(self, sock_num: int) -> bool: """Returns the socket connection status, False if not connected. - :param int sock_num: Desired socket number. + :param int sock_num: Desired socket number. """ - assert ( - sock_num < FONA_MAX_SOCKETS - ), "Provided socket exceeds the maximum number of \ + assert sock_num < FONA_MAX_SOCKETS, "Provided socket exceeds the maximum number of \ sockets for the FONA module." if not self._send_check_reply(b"AT+CIPSTATUS", reply=REPLY_OK, timeout=100): return False @@ -658,14 +660,12 @@ def socket_status(self, sock_num): return True - def socket_available(self, sock_num): + def socket_available(self, sock_num: int) -> int: """Returns the amount of bytes available to be read from the socket. - :param int sock_num: Desired socket to return bytes available from. + :param int sock_num: Desired socket to return bytes available from. """ - assert ( - sock_num < FONA_MAX_SOCKETS - ), "Provided socket exceeds the maximum number of \ + assert sock_num < FONA_MAX_SOCKETS, "Provided socket exceeds the maximum number of \ sockets for the FONA module." if not self._send_parse_reply( b"AT+CIPRXGET=4," + str(sock_num).encode(), @@ -674,33 +674,29 @@ def socket_available(self, sock_num): return False data = self._buf if self._debug: - print("\t {} bytes available.".format(self._buf)) + print(f"\t {self._buf} bytes available.") self._read_line() self._read_line() return data - def socket_connect(self, sock_num, dest, port, conn_mode=TCP_MODE): + def socket_connect( + self, sock_num: int, dest: str, port: int, conn_mode: int = TCP_MODE + ) -> bool: """Connects to a destination IP address or hostname. By default, we use conn_mode TCP_MODE but we may also use UDP_MODE. + :param int sock_num: Desired socket number :param str dest: Destination dest address. :param int port: Destination dest port. :param int conn_mode: Connection mode (TCP/UDP) - """ if self._debug: - print( - "*** Socket connect, protocol={}, port={}, ip={}".format( - conn_mode, port, dest - ) - ) + print(f"*** Socket connect, protocol={conn_mode}, port={port}, ip={dest}") self._uart.reset_input_buffer() - assert ( - sock_num < FONA_MAX_SOCKETS - ), "Provided socket exceeds the maximum number of \ + assert sock_num < FONA_MAX_SOCKETS, "Provided socket exceeds the maximum number of \ sockets for the FONA module." # Query local IP Address @@ -722,40 +718,35 @@ def socket_connect(self, sock_num, dest, port, conn_mode=TCP_MODE): return False return True - def socket_close(self, sock_num): + def socket_close(self, sock_num: int) -> bool: """Close TCP or UDP connection - :param int sock_num: Desired socket number. + :param int sock_num: Desired socket number. """ if self._debug: print("*** Closing socket #%d" % sock_num) - assert ( - sock_num < FONA_MAX_SOCKETS - ), "Provided socket exceeds the maximum number of \ + assert sock_num < FONA_MAX_SOCKETS, "Provided socket exceeds the maximum number of \ sockets for the FONA module." self._uart_write(b"AT+CIPCLOSE=" + str(sock_num).encode() + b"\r\n") self._read_line(3000) - if self._fona_type in (FONA_3G_A, FONA_3G_E): + if self._fona_type in {FONA_3G_A, FONA_3G_E}: if not self._expect_reply(REPLY_OK): return False - else: - if not self._expect_reply(b"CLOSE OK"): - return False + elif not self._expect_reply(b"CLOSE OK"): + return False return True - def socket_read(self, sock_num, length): + def socket_read(self, sock_num: int, length: int) -> bytearray: """Read data from the network into a buffer. - Returns buffer and amount of bytes read. + Returns bytes read. + :param int sock_num: Desired socket to read from. :param int length: Desired length to read. - """ self._read_line() - assert ( - sock_num < FONA_MAX_SOCKETS - ), "Provided socket exceeds the maximum number of \ + assert sock_num < FONA_MAX_SOCKETS, "Provided socket exceeds the maximum number of \ sockets for the FONA module." if self._debug: print("* socket read") @@ -769,17 +760,15 @@ def socket_read(self, sock_num, length): return self._uart.read(length) - def socket_write(self, sock_num, buffer, timeout=3000): + def socket_write(self, sock_num: int, buffer: bytes, timeout: int = 3000) -> bool: """Writes bytes to the socket. + :param int sock_num: Desired socket number to write to. :param bytes buffer: Bytes to write to socket. :param int timeout: Socket write timeout, in milliseconds. - """ self._read_line() - assert ( - sock_num < FONA_MAX_SOCKETS - ), "Provided socket exceeds the maximum number of \ + assert sock_num < FONA_MAX_SOCKETS, "Provided socket exceeds the maximum number of \ sockets for the FONA module." self._uart.reset_input_buffer() @@ -801,22 +790,24 @@ def socket_write(self, sock_num, buffer, timeout=3000): ### UART Reply/Response Helpers ### - def _uart_write(self, buffer): + def _uart_write(self, buffer: bytes) -> None: """UART ``write`` with optional debug that prints the buffer before sending. - :param bytes buffer: Buffer of bytes to send to the bus. + :param bytes buffer: Buffer of bytes to send to the bus. """ if self._debug: print("\tUARTWRITE ::", buffer.decode()) self._uart.write(buffer) - def _send_parse_reply(self, send_data, reply_data, divider=",", idx=0): + def _send_parse_reply( + self, send_data: bytes, reply_data: bytes, divider: str = ",", idx: int = 0 + ) -> bool: """Sends data to FONA module, parses reply data returned. + :param bytes send_data: Data to send to the module. :param bytes send_data: Data received by the FONA module. :param str divider: Separator - """ self._read_line() self._get_reply(send_data) @@ -826,12 +817,18 @@ def _send_parse_reply(self, send_data, reply_data, divider=",", idx=0): return True def _get_reply( - self, data=None, prefix=None, suffix=None, timeout=FONA_DEFAULT_TIMEOUT_MS - ): + self, + data: Optional[bytes] = None, + prefix: Optional[bytes] = None, + suffix: Optional[bytes] = None, + timeout: int = FONA_DEFAULT_TIMEOUT_MS, + ) -> Tuple[int, bytes]: """Send data to FONA, read response into buffer. + :param bytes data: Data to send to FONA module. + :param bytes prefix: Data to write if ``data`` is not provided + :param bytes suffix: Data to write following ``prefix`` if ``data is not provided :param int timeout: Time to wait for UART response. - """ self._uart.reset_input_buffer() @@ -842,11 +839,11 @@ def _get_reply( return self._read_line(timeout) - def _parse_reply(self, reply, divider=",", idx=0): + def _parse_reply(self, reply: bytes, divider: str = ",", idx: int = 0) -> bool: """Attempts to find reply in UART buffer, reads up to divider. + :param bytes reply: Expected response from FONA module. :param str divider: Divider character. - """ parsed_reply = self._buf.find(reply) if parsed_reply == -1: @@ -866,12 +863,14 @@ def _parse_reply(self, reply, divider=",", idx=0): return True - def _read_line(self, timeout=FONA_DEFAULT_TIMEOUT_MS, multiline=False): + def _read_line( + self, timeout: int = FONA_DEFAULT_TIMEOUT_MS, multiline: bool = False + ) -> Tuple[int, bytes]: """Reads one or multiple lines into the buffer. Optionally prints the buffer after reading. + :param int timeout: Time to wait for UART serial to reply, in seconds. :param bool multiline: Read multiple lines. - """ self._buf = b"" reply_idx = 0 @@ -904,24 +903,26 @@ def _read_line(self, timeout=FONA_DEFAULT_TIMEOUT_MS, multiline=False): def _send_check_reply( self, - send=None, - prefix=None, - suffix=None, - reply=None, + send: Optional[bytes] = None, + prefix: Optional[bytes] = None, + suffix: Optional[bytes] = None, + reply: Optional[bytes] = None, timeout=FONA_DEFAULT_TIMEOUT_MS, - ): + ) -> bool: """Sends data to FONA, validates response. + :param bytes send: Command. + :param bytes prefix: Data to send if ``send`` not provided + :param bytes suffix: Data to send after ``prefix`` if ``send`` not provided :param bytes reply: Expected response from module. - + :param int timeout: Time to wait for UART serial to reply, in seconds. """ self._read_line() if send is None: if not self._get_reply(prefix=prefix, suffix=suffix, timeout=timeout): return False - else: - if not self._get_reply(send, timeout=timeout): - return False + elif not self._get_reply(send, timeout=timeout): + return False if not self._buf == reply: return False @@ -929,14 +930,18 @@ def _send_check_reply( return True def _send_check_reply_quoted( - self, prefix, suffix, reply, timeout=FONA_DEFAULT_TIMEOUT_MS - ): + self, + prefix: bytes, + suffix: bytes, + reply: bytes, + timeout: int = FONA_DEFAULT_TIMEOUT_MS, + ) -> bool: """Send prefix, ", suffix, ", and a newline. Verify response against reply. + :param bytes prefix: Command prefix. :param bytes prefix: Command ", suffix, ". :param bytes reply: Expected response from module. :param int timeout: Time to expect reply back from FONA, in milliseconds. - """ self._buf = b"" @@ -946,13 +951,13 @@ def _send_check_reply_quoted( return False return True - def _get_reply_quoted(self, prefix, suffix, timeout): + def _get_reply_quoted(self, prefix: bytes, suffix: bytes, timeout: int) -> Tuple[int, bytes]: """Send prefix, ", suffix, ", and newline. Returns: Response (and also fills buffer with response). + :param bytes prefix: Command prefix. :param bytes prefix: Command ", suffix, ". :param int timeout: Time to expect reply back from FONA, in milliseconds. - """ self._uart.reset_input_buffer() @@ -960,10 +965,11 @@ def _get_reply_quoted(self, prefix, suffix, timeout): return self._read_line(timeout) - def _expect_reply(self, reply, timeout=10000): + def _expect_reply(self, reply: bytes, timeout: int = 10000) -> bool: """Reads line from FONA module and compares to reply from FONA module. - :param bytes reply: Expected reply from module. + :param bytes reply: Expected reply from module. + :param int timeout: Time to wait for UART serial to reply, in seconds. """ self._read_line(timeout) if reply not in self._buf: diff --git a/adafruit_fona/adafruit_fona_network.py b/adafruit_fona/adafruit_fona_network.py index fd79183..050e7c5 100755 --- a/adafruit_fona/adafruit_fona_network.py +++ b/adafruit_fona/adafruit_fona_network.py @@ -12,55 +12,79 @@ """ +try: + from types import TracebackType + from typing import Optional, Tuple, Type + + from adafruit_fona.adafruit_fona import FONA +except ImportError: + pass + +__version__ = "0.0.0+auto.0" +__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_FONA.git" + # Network types NET_GSM = 0x01 NET_CDMA = 0x02 class CELLULAR: - """Interface for connecting to and interacting with GSM and CDMA cellular networks.""" + """Interface for connecting to and interacting with GSM and CDMA cellular networks. - def __init__(self, fona, apn): - """Initializes interface with cellular network. - :param adafruit_fona fona: The Adafruit FONA module we are using. - :param tuple apn: Tuple containing APN name, (optional) APN username, - and APN password. + :param FONA fona: The Adafruit FONA module we are using. + :param tuple apn: Tuple containing APN name, (optional) APN username, + and APN password. + """ - """ + def __init__(self, fona: FONA, apn: Tuple[str, Optional[str], Optional[str]]) -> None: self._iface = fona self._apn = apn self._network_connected = False - self._network_type = NET_CDMA + self._network_type = NET_GSM + self._has_gps = False - if not self._iface.version == 0x4 or self._iface.version == 0x5: - self._network_type = NET_GSM + # These are numbers defined in adafruit_fona FONA versions + # For some reason, we can't import them from the adafruit_fona file + + if self._iface.version in {0x4, 0x5}: + self._network_type = NET_CDMA + + if self._iface.version in {0x2, 0x3, 0x4, 0x5}: self._iface.gps = True + self._has_gps = True - def __enter__(self): + def __enter__(self) -> "CELLULAR": return self - def __exit__(self, exception_type, exception_value, traceback): + def __exit__( + self, + exception_type: Optional[Type[type]], + exception_value: Optional[BaseException], + traceback: Optional[TracebackType], + ) -> None: self.disconnect() @property - def imei(self): + def imei(self) -> str: """Returns the modem's IEMI number, as a string.""" return self._iface.iemi @property - def iccid(self): + def iccid(self) -> str: """Returns the SIM card's ICCID, as a string.""" return self._iface.iccid @property - def is_attached(self): + def is_attached(self) -> bool: """Returns if the modem is attached to the network.""" if self._network_type == NET_GSM: - if self._iface.gps == 3 and self._iface.network_status == 1: + if self._has_gps and self._iface.gps == 3 and self._iface.network_status == 1: return True - else: # Attach CDMA network - if self._iface.ue_system_info == 1 and self._iface.network_status == 1: + + if not self._has_gps and self._iface.network_status == 1: return True + elif self._iface.ue_system_info == 1 and self._iface.network_status == 1: + return True return False @property @@ -70,7 +94,7 @@ def is_connected(self): return False return True - def connect(self): + def connect(self) -> None: """Connect to cellular network.""" if self._iface.set_gprs(self._apn, True): self._network_connected = True @@ -78,7 +102,7 @@ def connect(self): # reset context for next connection attempt self._iface.set_gprs(self._apn, False) - def disconnect(self): + def disconnect(self) -> None: """Disconnect from cellular network.""" self._iface.set_gprs(self._apn, False) self._network_connected = False diff --git a/adafruit_fona/adafruit_fona_socket.py b/adafruit_fona/adafruit_fona_socket.py index 16034e6..2de6825 100644 --- a/adafruit_fona/adafruit_fona_socket.py +++ b/adafruit_fona/adafruit_fona_socket.py @@ -12,20 +12,29 @@ * Author(s): ladyada, Brent Rubell """ + import gc import time + from micropython import const -_the_interface = None # pylint: disable=invalid-name +try: + from typing import Optional, Sequence, Tuple + + from adafruit_fona.adafruit_fona import FONA +except ImportError: + pass +_the_interface = None -def set_interface(iface): + +def set_interface(iface: FONA) -> None: """Helper to set the global internet interface.""" - global _the_interface # pylint: disable=global-statement, invalid-name + global _the_interface _the_interface = iface -def htonl(x): +def htonl(x: int) -> int: """Convert 32-bit positive integers from host to network byte order.""" return ( ((x) << 24 & 0xFF000000) @@ -35,7 +44,7 @@ def htonl(x): ) -def htons(x): +def htons(x: int) -> int: """Convert 16-bit positive integers from host to network byte order.""" return (((x) << 8) & 0xFF00) | (((x) >> 8) & 0xFF) @@ -49,8 +58,8 @@ def htons(x): # keep track of sockets we allocate SOCKETS = [] -# pylint: disable=too-many-arguments, unused-argument -def getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0): + +def getaddrinfo(host, port: int, family=0, socktype=0, proto=0, flags=0): """Translate the host/port argument into a sequence of 5-tuples that contain all the necessary arguments for creating a socket connected to that service. """ @@ -59,27 +68,32 @@ def getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0): return [(AF_INET, socktype, proto, "", (gethostbyname(host), port))] -def gethostbyname(hostname): +def gethostbyname(hostname: str) -> str: """Translate a host name to IPv4 address format. The IPv4 address is returned as a string. + :param str hostname: Desired hostname. """ addr = _the_interface.get_host_by_name(hostname) return addr.strip('"') -# pylint: disable=invalid-name, redefined-builtin class socket: """A simplified implementation of the Python 'socket' class for connecting to a FONA cellular module. + :param int family: Socket address (and protocol) family. :param int type: Socket type. - """ def __init__( - self, family=AF_INET, type=SOCK_STREAM, proto=0, fileno=None, socknum=None - ): + self, + family: int = AF_INET, + type: int = SOCK_STREAM, + proto: int = 0, + fileno: Optional[int] = None, + socknum: Optional[int] = None, + ) -> None: if family != AF_INET: raise RuntimeError("Only AF_INET family supported by cellular sockets.") self._sock_type = type @@ -94,58 +108,55 @@ def __init__( self.settimeout(self._timeout) @property - def socknum(self): + def socknum(self) -> int: """Returns the socket object's socket number.""" return self._socknum @property - def connected(self): + def connected(self) -> bool: """Returns whether or not we are connected to the socket.""" return _the_interface.socket_status(self.socknum) - def getpeername(self): + def getpeername(self) -> str: """Return the remote address to which the socket is connected.""" return _the_interface.remote_ip(self.socknum) - def inet_aton(self, ip_string): + def inet_aton(self, ip_string: str) -> bytearray: """Convert an IPv4 address from dotted-quad string format. - :param str ip_string: IP Address, as a dotted-quad string. + :param str ip_string: IP Address, as a dotted-quad string. """ self._buffer = b"" self._buffer = [int(item) for item in ip_string.split(".")] self._buffer = bytearray(self._buffer) return self._buffer - def connect(self, address, conn_mode=None): + def connect(self, address: Tuple[str, int], conn_mode: Optional[int] = None) -> None: """Connect to a remote socket at address. (The format of address depends on the address family — see above.) + :param tuple address: Remote socket as a (host, port) tuple. :param int conn_mode: Connection mode (TCP/UDP) - """ - assert ( - conn_mode != 0x03 - ), "Error: SSL/TLS is not currently supported by CircuitPython." + assert conn_mode != 0x03, "Error: SSL/TLS is not currently supported by CircuitPython." host, port = address - if not _the_interface.socket_connect( - self.socknum, host, port, conn_mode=self._sock_type - ): + if not _the_interface.socket_connect(self.socknum, host, port, conn_mode=self._sock_type): raise RuntimeError("Failed to connect to host", host) self._buffer = b"" - def send(self, data): + def send(self, data: bytes) -> None: """Send data to the socket. The socket must be connected to a remote socket prior to calling this method. - :param bytes data: Desired data to send to the socket. + :param bytes data: Desired data to send to the socket. """ _the_interface.socket_write(self._socknum, data, self._timeout) gc.collect() - def recv(self, bufsize=0): + def recv(self, bufsize: int = 0) -> Sequence[int]: """Reads some bytes from the connected remote address. + :param int bufsize: maximum number of bytes to receive """ # print("Socket read", bufsize) @@ -189,7 +200,7 @@ def recv(self, bufsize=0): gc.collect() return ret - def readline(self): + def readline(self) -> Sequence[int]: """Attempt to return as many bytes as we can up to but not including '\r\n'""" # print("Socket readline") stamp = time.monotonic() @@ -205,26 +216,25 @@ def readline(self): gc.collect() return firstline - def available(self): + def available(self) -> int: """Returns how many bytes are available to be read from the socket.""" return _the_interface.socket_available(self._socknum) - def settimeout(self, value): + def settimeout(self, value: int) -> None: """Sets socket read timeout. - :param int value: Socket read timeout, in seconds. + :param int value: Socket read timeout, in seconds. """ if value < 0: - raise Exception("Timeout period should be non-negative.") + raise ValueError("Timeout period should be non-negative.") self._timeout = value - def gettimeout(self): + def gettimeout(self) -> int: """Return the timeout in seconds (float) associated with socket operations, or None if no timeout is set. - """ return self._timeout - def close(self): + def close(self) -> bool: """Closes the socket.""" return _the_interface.socket_close(self._socknum) diff --git a/adafruit_fona/fona_3g.py b/adafruit_fona/fona_3g.py index a16c9d3..4515660 100755 --- a/adafruit_fona/fona_3g.py +++ b/adafruit_fona/fona_3g.py @@ -4,8 +4,7 @@ # SPDX-License-Identifier: MIT """ -:py:class:`~adafruit_fona.fona_3g.FONA3G` -`adafruit_fona_3g` +`fona_3g` ================================================================================ FONA3G cellular module instance. @@ -21,10 +20,25 @@ https://github.com/adafruit/circuitpython/releases """ + from micropython import const + from .adafruit_fona import FONA, REPLY_OK -__version__ = "0.0.0-auto.0" +try: + from typing import Optional, Tuple, Union + + from busio import UART + from digitalio import DigitalInOut + + try: + from typing import Literal + except ImportError: + from typing_extensions import Literal +except ImportError: + pass + +__version__ = "0.0.0+auto.0" __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_FONA.git" FONA_MAX_SOCKETS = const(10) @@ -32,34 +46,38 @@ class FONA3G(FONA): """FONA 3G module interface. - :param ~busio.uart UART: FONA UART connection. - :param ~digialio RST: FONA RST pin. - :param ~digialio RI: Optional FONA Ring Interrupt (RI) pin. - :param bool debug: Enable debugging output. + :param ~busio.UART uart: FONA UART connection. + :param ~digitalio.DigitalInOut rst: FONA RST pin. + :param ~digitalio.DigitalInOut ri: Optional FONA Ring Interrupt (RI) pin. + :param bool debug: Enable debugging output. """ - def __init__(self, uart, rst, ri=None, debug=False): + def __init__( + self, + uart: UART, + rst: DigitalInOut, + ri: Optional[DigitalInOut] = None, + debug: bool = False, + ) -> None: uart.baudrate = 4800 super().__init__(uart, rst, ri, debug) - def set_baudrate(self, baudrate): + def set_baudrate(self, baudrate: int) -> bool: """Sets the FONA's UART baudrate.""" - if not self._send_check_reply( - b"AT+IPREX=" + str(baudrate).encode(), reply=REPLY_OK - ): + if not self._send_check_reply(b"AT+IPREX=" + str(baudrate).encode(), reply=REPLY_OK): return False return True @property - def gps(self): + def gps(self) -> bool: """Module's GPS status.""" if not self._send_check_reply(b"AT+CGPS?", reply=b"+CGPS: 1,1"): return False return True @gps.setter - def gps(self, gps_on=False): + def gps(self, gps_on: bool = False) -> bool: # check if GPS is already enabled if not self._send_parse_reply(b"AT+CGPS?", b"+CGPS: "): return False @@ -77,7 +95,7 @@ def gps(self, gps_on=False): return True @property - def ue_system_info(self): + def ue_system_info(self) -> bool: """UE System status.""" self._send_parse_reply(b"AT+CPSI?\r\n", b"+CPSI: ") if not self._buf == "GSM" or self._buf == "WCDMA": # 5.15 @@ -85,17 +103,21 @@ def ue_system_info(self): return True @property - def local_ip(self): + def local_ip(self) -> Optional[str]: """Module's local IP address, None if not set.""" if not self._send_parse_reply(b"AT+IPADDR", b"+IPADDR:"): return None return self._buf - # pylint: disable=too-many-return-statements - def set_gprs(self, apn=None, enable=True): + def set_gprs( + self, + apn: Optional[Tuple[str, Optional[str], Optional[str]]] = None, + enable: bool = True, + ) -> bool: """Configures and brings up GPRS. - :param bool enable: Enables or disables GPRS. + :param tuple apn: APN configuration settings + :param bool enable: Enables or disables GPRS. """ if enable: if not self._send_check_reply(b"AT+CGATT=1", reply=REPLY_OK, timeout=10000): @@ -131,18 +153,14 @@ def set_gprs(self, apn=None, enable=True): if not self.local_ip: return True - else: - # reset PDP state - if not self._send_check_reply( - b"AT+NETCLOSE", reply=b"Network closed", timeout=20000 - ): - return False + elif not self._send_check_reply(b"AT+NETCLOSE", reply=b"Network closed", timeout=20000): + return False return True ### Socket API (TCP, UDP) ### @property - def tx_timeout(self): + def tx_timeout(self) -> bool: """CIPSEND timeout, in milliseconds.""" self._read_line() if not self._send_parse_reply(b"AT+CIPTIMEOUT?", b"+CIPTIMEOUT:", idx=2): @@ -150,16 +168,15 @@ def tx_timeout(self): return True @tx_timeout.setter - def tx_timeout(self, timeout): + def tx_timeout(self, timeout: int) -> bool: self._read_line() - if not self._send_check_reply( - b"AT+CIPTIMEOUT=" + str(timeout).encode(), reply=REPLY_OK - ): + if not self._send_check_reply(b"AT+CIPTIMEOUT=" + str(timeout).encode(), reply=REPLY_OK): return False return True - def get_host_by_name(self, hostname): + def get_host_by_name(self, hostname: str) -> Union[str, Literal[False]]: """Converts a hostname to a 4-byte IP address. + :param str hostname: Domain name. """ self._read_line() @@ -175,7 +192,7 @@ def get_host_by_name(self, hostname): return False return self._buf - def get_socket(self): + def get_socket(self) -> int: """Returns an unused socket.""" if self._debug: print("*** Get socket") @@ -198,31 +215,23 @@ def get_socket(self): print("Allocated socket #%d" % socket) return socket - def socket_connect(self, sock_num, dest, port, conn_mode=0): + def socket_connect(self, sock_num: int, dest: str, port: int, conn_mode: int = 0) -> bool: """Connects to a destination IP address or hostname. By default, we use conn_mode TCP_MODE but we may also use UDP_MODE. + :param int sock_num: Desired socket number :param str dest: Destination dest address. :param int port: Destination dest port. :param int conn_mode: Connection mode (TCP/UDP) - """ if self._debug: - print( - "*** Socket connect, protocol={}, port={}, ip={}".format( - conn_mode, port, dest - ) - ) + print(f"*** Socket connect, protocol={conn_mode}, port={port}, ip={dest}") self._uart.reset_input_buffer() - assert ( - sock_num < FONA_MAX_SOCKETS - ), "Provided socket exceeds the maximum number of \ + assert sock_num < FONA_MAX_SOCKETS, "Provided socket exceeds the maximum number of \ sockets for the FONA module." self._send_check_reply(b"AT+CIPHEAD=0", reply=REPLY_OK) # do not show ip header - self._send_check_reply( - b"AT+CIPSRIP=0", reply=REPLY_OK - ) # do not show remote ip/port + self._send_check_reply(b"AT+CIPSRIP=0", reply=REPLY_OK) # do not show remote ip/port self._send_check_reply(b"AT+CIPRXGET=1", reply=REPLY_OK) # manually get data self._uart_write(b"AT+CIPOPEN=" + str(sock_num).encode()) @@ -236,12 +245,13 @@ def socket_connect(self, sock_num, dest, port, conn_mode=0): return False return True - def remote_ip(self, sock_num): - """Returns the IP address of the remote connection.""" + def remote_ip(self, sock_num: int) -> str: + """Returns the IP address of the remote connection. + + :param int sock_num: Desired socket number + """ self._read_line() - assert ( - sock_num < FONA_MAX_SOCKETS - ), "Provided socket exceeds the maximum number of \ + assert sock_num < FONA_MAX_SOCKETS, "Provided socket exceeds the maximum number of \ sockets for the FONA module." self._uart_write(b"AT+CIPOPEN?\r\n") @@ -254,27 +264,21 @@ def remote_ip(self, sock_num): self._read_line() # eat the rest of '+CIPOPEN' responses return ip_addr - def socket_write(self, sock_num, buffer, timeout=120000): + def socket_write(self, sock_num: int, buffer: bytes, timeout: int = 120000) -> bool: """Writes len(buffer) bytes to the socket. + :param int sock_num: Desired socket number to write to. :param bytes buffer: Bytes to write to socket. :param int timeout: Socket write timeout, in milliseconds. Defaults to 120000ms. - """ self._read_line() - assert ( - sock_num < FONA_MAX_SOCKETS - ), "Provided socket exceeds the maximum number of \ + assert sock_num < FONA_MAX_SOCKETS, "Provided socket exceeds the maximum number of \ sockets for the FONA module." self._uart.reset_input_buffer() self._uart_write( - b"AT+CIPSEND=" - + str(sock_num).encode() - + b"," - + str(len(buffer)).encode() - + b"\r\n" + b"AT+CIPSEND=" + str(sock_num).encode() + b"," + str(len(buffer)).encode() + b"\r\n" ) self._read_line() if self._buf[0] != 62: @@ -295,10 +299,10 @@ def socket_write(self, sock_num, buffer, timeout=120000): return False return True - def socket_status(self, sock_num): + def socket_status(self, sock_num: int) -> bool: """Returns socket status, True if connected. False otherwise. - :param int sock_num: Desired socket number. + :param int sock_num: Desired socket number. """ if not self._send_parse_reply(b"AT+CIPCLOSE?", b"+CIPCLOSE:", idx=sock_num): return False diff --git a/docs/api.rst b/docs/api.rst index 280ec86..1e1d2e5 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -4,8 +4,17 @@ .. 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" +API Reference +############# + .. automodule:: adafruit_fona.adafruit_fona :members: .. automodule:: adafruit_fona.adafruit_fona_socket :members: + +.. automodule:: adafruit_fona.adafruit_fona_network + :members: + +.. automodule:: adafruit_fona.fona_3g + :members: diff --git a/docs/conf.py b/docs/conf.py index 857e60e..b700101 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,9 +1,8 @@ -# -*- coding: utf-8 -*- - # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # # SPDX-License-Identifier: MIT +import datetime import os import sys @@ -16,6 +15,7 @@ # ones. extensions = [ "sphinx.ext.autodoc", + "sphinxcontrib.jquery", "sphinx.ext.intersphinx", "sphinx.ext.napoleon", "sphinx.ext.todo", @@ -29,12 +29,12 @@ intersphinx_mapping = { - "python": ("https://docs.python.org/3.4", None), + "python": ("https://docs.python.org/3", None), "BusDevice": ( - "https://circuitpython.readthedocs.io/projects/busdevice/en/latest/", + "https://docs.circuitpython.org/projects/busdevice/en/latest/", None, ), - "CircuitPython": ("https://circuitpython.readthedocs.io/en/latest/", None), + "CircuitPython": ("https://docs.circuitpython.org/en/latest/", None), } # Add any paths that contain templates here, relative to this directory. @@ -47,7 +47,12 @@ # General information about the project. project = "Adafruit FONA Library" -copyright = "2020 Brent Rubell, ladyada" +creation_year = "2020" +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, ladyada" author = "Brent Rubell, ladyada" # The version info for the project you're documenting, acts as replacement for @@ -64,7 +69,7 @@ # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. -language = None +language = "en" # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. @@ -96,19 +101,9 @@ # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # -on_rtd = os.environ.get("READTHEDOCS", None) == "True" - -if not on_rtd: # only import and set the theme if we're building docs locally - try: - import sphinx_rtd_theme - - html_theme = "sphinx_rtd_theme" - html_theme_path = [sphinx_rtd_theme.get_html_theme_path(), "."] - except: - html_theme = "default" - html_theme_path = ["."] -else: - html_theme_path = ["."] +import sphinx_rtd_theme + +html_theme = "sphinx_rtd_theme" # 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, diff --git a/docs/index.rst b/docs/index.rst index f0dbc6f..eca939e 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -32,8 +32,9 @@ Table of Contents .. toctree:: :caption: Other Links - Download - CircuitPython Reference Documentation + Download from GitHub + Download Library Bundle + CircuitPython Reference Documentation CircuitPython Support Forum Discord Chat Adafruit Learning System diff --git a/docs/requirements.txt b/docs/requirements.txt index 88e6733..979f568 100644 --- a/docs/requirements.txt +++ b/docs/requirements.txt @@ -2,4 +2,6 @@ # # SPDX-License-Identifier: Unlicense -sphinx>=4.0.0 +sphinx +sphinxcontrib-jquery +sphinx-rtd-theme diff --git a/examples/fona_aio_post.py b/examples/fona_aio_post.py index 8c7d780..28e79c3 100644 --- a/examples/fona_aio_post.py +++ b/examples/fona_aio_post.py @@ -1,23 +1,27 @@ # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT -# pylint: disable=unused-import import time +from os import getenv + +import adafruit_connection_manager +import adafruit_requests import board import busio import digitalio -import adafruit_requests as requests + +import adafruit_fona.adafruit_fona_network as network +import adafruit_fona.adafruit_fona_socket as pool from adafruit_fona.adafruit_fona import FONA from adafruit_fona.fona_3g import FONA3G -import adafruit_fona.adafruit_fona_network as network -import adafruit_fona.adafruit_fona_socket as cellular_socket -# Get GPRS details and more from a secrets.py file -try: - from secrets import secrets -except ImportError: - print("GPRS secrets are kept in secrets.py, please add them there!") - raise +# Get FONA details and Adafruit IO keys, ensure these are setup in settings.toml +# (visit io.adafruit.com if you need to create an account, or if you need your Adafruit IO key.) +apn = getenv("apn") +apn_username = getenv("apn_username") +apn_password = getenv("apn_password") +aio_username = getenv("ADAFRUIT_AIO_USERNAME") +aio_key = getenv("ADAFRUIT_AIO_KEY") # Create a serial connection for the FONA uart = busio.UART(board.TX, board.RX) @@ -30,9 +34,7 @@ # fona = FONA3G(uart, rst) # Initialize cellular data network -network = network.CELLULAR( - fona, (secrets["apn"], secrets["apn_username"], secrets["apn_password"]) -) +network = network.CELLULAR(fona, (apn, apn_username, apn_password)) while not network.is_attached: print("Attaching to network...") @@ -45,8 +47,9 @@ time.sleep(0.5) print("Network Connected!") -# Initialize a requests object with a socket and cellular interface -requests.set_socket(cellular_socket, fona) +# create requests session +ssl_context = adafruit_connection_manager.create_fake_ssl_context(pool, fona) +requests = adafruit_requests.Session(pool, ssl_context) counter = 0 @@ -56,13 +59,9 @@ feed = "test" payload = {"value": data} response = requests.post( - "http://io.adafruit.com/api/v2/" - + secrets["aio_username"] - + "/feeds/" - + feed - + "/data", + "http://io.adafruit.com/api/v2/" + aio_username + "/feeds/" + feed + "/data", json=payload, - headers={"X-AIO-KEY": secrets["aio_key"]}, + headers={"X-AIO-KEY": aio_key}, ) print(response.json()) response.close() diff --git a/examples/fona_cheerlights.py b/examples/fona_cheerlights.py index a94ed0a..68fc4d9 100755 --- a/examples/fona_cheerlights.py +++ b/examples/fona_cheerlights.py @@ -1,25 +1,26 @@ # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT -# pylint: disable=unused-import import time +from os import getenv + +import adafruit_connection_manager +import adafruit_fancyled.adafruit_fancyled as fancy +import adafruit_requests import board import busio import digitalio import neopixel -import adafruit_requests as requests -import adafruit_fancyled.adafruit_fancyled as fancy + +import adafruit_fona.adafruit_fona_network as network +import adafruit_fona.adafruit_fona_socket as pool from adafruit_fona.adafruit_fona import FONA from adafruit_fona.fona_3g import FONA3G -import adafruit_fona.adafruit_fona_network as network -import adafruit_fona.adafruit_fona_socket as cellular_socket -# Get GPRS details and more from a secrets.py file -try: - from secrets import secrets -except ImportError: - print("GPRS secrets are kept in secrets.py, please add them there!") - raise +# Get FONA details, ensure these are setup in settings.toml +apn = getenv("apn") +apn_username = getenv("apn_username") +apn_password = getenv("apn_password") # Create a serial connection for the FONA uart = busio.UART(board.TX, board.RX) @@ -32,9 +33,7 @@ # fona = FONA3G(uart, rst) # Initialize cellular data network -network = network.CELLULAR( - fona, (secrets["apn"], secrets["apn_username"], secrets["apn_password"]) -) +network = network.CELLULAR(fona, (apn, apn_username, apn_password)) while not network.is_attached: print("Attaching to network...") @@ -47,8 +46,9 @@ time.sleep(0.5) print("Network Connected!") -# Initialize a requests object with a socket and cellular interface -requests.set_socket(cellular_socket, fona) +# create requests session +ssl_context = adafruit_connection_manager.create_fake_ssl_context(pool, fona) +requests = adafruit_requests.Session(pool, ssl_context) DATA_SOURCE = "http://api.thingspeak.com/channels/1417/feeds.json?results=1" DATA_LOCATION = ["feeds", 0, "field2"] diff --git a/examples/fona_simpletest.py b/examples/fona_simpletest.py index 07b7154..11af0a5 100644 --- a/examples/fona_simpletest.py +++ b/examples/fona_simpletest.py @@ -1,28 +1,29 @@ # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT -# pylint: disable=unused-import import time +from os import getenv + +import adafruit_connection_manager +import adafruit_requests import board import busio import digitalio -import adafruit_requests as requests + +import adafruit_fona.adafruit_fona_network as network +import adafruit_fona.adafruit_fona_socket as pool from adafruit_fona.adafruit_fona import FONA from adafruit_fona.fona_3g import FONA3G -import adafruit_fona.adafruit_fona_network as network -import adafruit_fona.adafruit_fona_socket as cellular_socket print("FONA Webclient Test") TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html" JSON_URL = "http://api.coindesk.com/v1/bpi/currentprice/USD.json" -# Get GPRS details and more from a secrets.py file -try: - from secrets import secrets -except ImportError: - print("GPRS secrets are kept in secrets.py, please add them there!") - raise +# Get FONA details, ensure these are setup in settings.toml +apn = getenv("apn") +apn_username = getenv("apn_username") +apn_password = getenv("apn_password") # Create a serial connection for the FONA connection uart = busio.UART(board.TX, board.RX) @@ -35,9 +36,7 @@ # fona = FONA3G(uart, rst) # Initialize cellular data network -network = network.CELLULAR( - fona, (secrets["apn"], secrets["apn_username"], secrets["apn_password"]) -) +network = network.CELLULAR(fona, (apn, apn_username, apn_password)) while not network.is_attached: print("Attaching to network...") @@ -53,8 +52,9 @@ print("My IP address is:", fona.local_ip) print("IP lookup adafruit.com: %s" % fona.get_host_by_name("adafruit.com")) -# Initialize a requests object with a socket and cellular interface -requests.set_socket(cellular_socket, fona) +# create requests session +ssl_context = adafruit_connection_manager.create_fake_ssl_context(pool, fona) +requests = adafruit_requests.Session(pool, ssl_context) # fona._debug = True print("Fetching text from", TEXT_URL) diff --git a/examples/fona_sms.py b/examples/fona_sms.py index a516265..18a9436 100755 --- a/examples/fona_sms.py +++ b/examples/fona_sms.py @@ -1,11 +1,12 @@ # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT -# pylint: disable=unused-import import time + import board import busio import digitalio + from adafruit_fona.adafruit_fona import FONA, FONA_3G_A, FONA_3G_E from adafruit_fona.fona_3g import FONA3G @@ -39,7 +40,7 @@ print("%d SMS's on SIM Card" % num_sms) # FONA3G SMS memory slots start at 0 -if fona.version in (FONA_3G_A, FONA_3G_E): +if fona.version in {FONA_3G_A, FONA_3G_E}: sms_idx = 0 else: # FONA800 and FONA808 SMS slots start at 1 sms_idx = 1 diff --git a/examples/fona_sms_response.py b/examples/fona_sms_response.py index 5595d19..b073832 100755 --- a/examples/fona_sms_response.py +++ b/examples/fona_sms_response.py @@ -1,11 +1,12 @@ # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT -# pylint: disable=unused-import import time + import board import busio import digitalio + from adafruit_fona.adafruit_fona import FONA from adafruit_fona.fona_3g import FONA3G @@ -38,7 +39,7 @@ sender, message = fona.receive_sms() if message: - print("Incoming SMS from {}: {}".format(sender, message)) + print(f"Incoming SMS from {sender}: {message}") # Reply back! print("Sending response...") diff --git a/optional_requirements.txt b/optional_requirements.txt new file mode 100644 index 0000000..d4e27c4 --- /dev/null +++ b/optional_requirements.txt @@ -0,0 +1,3 @@ +# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries +# +# SPDX-License-Identifier: Unlicense diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..a43b25e --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,46 @@ +# SPDX-FileCopyrightText: 2022 Alec Delaney for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +[build-system] +requires = [ + "setuptools", + "wheel", + "setuptools-scm", +] + +[project] +name = "adafruit-circuitpython-fona" +description = "CircuitPython library for the Adafruit FONAA" +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_FONA"} +keywords = [ + "adafruit", + "blinka", + "circuitpython", + "micropython", + "fona", + "fona,", + "cellular", +] +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_fona"] + +[tool.setuptools.dynamic] +dependencies = {file = ["requirements.txt"]} +optional-dependencies = {optional = {file = ["optional_requirements.txt"]}} diff --git a/requirements.txt b/requirements.txt index 593c9d9..c8bf6e2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,7 +1,7 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries +# SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries # # SPDX-License-Identifier: Unlicense Adafruit-Blinka -adafruit-circuitpython-busdevice adafruit-circuitpython-simpleio +adafruit-circuitpython-busdevice diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..b45e467 --- /dev/null +++ b/ruff.toml @@ -0,0 +1,108 @@ +# SPDX-FileCopyrightText: 2024 Tim Cocks for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +target-version = "py38" +line-length = 100 + +[lint] +preview = true +select = ["I", "PL", "UP"] + +extend-select = [ + "D419", # empty-docstring + "E501", # line-too-long + "W291", # trailing-whitespace + "PLC0414", # useless-import-alias + "PLC2401", # non-ascii-name + "PLC2801", # unnecessary-dunder-call + "PLC3002", # unnecessary-direct-lambda-call + "E999", # syntax-error + "PLE0101", # return-in-init + "F706", # return-outside-function + "F704", # yield-outside-function + "PLE0116", # continue-in-finally + "PLE0117", # nonlocal-without-binding + "PLE0241", # duplicate-bases + "PLE0302", # unexpected-special-method-signature + "PLE0604", # invalid-all-object + "PLE0605", # invalid-all-format + "PLE0643", # potential-index-error + "PLE0704", # misplaced-bare-raise + "PLE1141", # dict-iter-missing-items + "PLE1142", # await-outside-async + "PLE1205", # logging-too-many-args + "PLE1206", # logging-too-few-args + "PLE1307", # bad-string-format-type + "PLE1310", # bad-str-strip-call + "PLE1507", # invalid-envvar-value + "PLE2502", # bidirectional-unicode + "PLE2510", # invalid-character-backspace + "PLE2512", # invalid-character-sub + "PLE2513", # invalid-character-esc + "PLE2514", # invalid-character-nul + "PLE2515", # invalid-character-zero-width-space + "PLR0124", # comparison-with-itself + "PLR0202", # no-classmethod-decorator + "PLR0203", # no-staticmethod-decorator + "UP004", # useless-object-inheritance + "PLR0206", # property-with-parameters + "PLR0904", # too-many-public-methods + "PLR0911", # too-many-return-statements + "PLR0912", # too-many-branches + "PLR0913", # too-many-arguments + "PLR0914", # too-many-locals + "PLR0915", # too-many-statements + "PLR0916", # too-many-boolean-expressions + "PLR1702", # too-many-nested-blocks + "PLR1704", # redefined-argument-from-local + "PLR1711", # useless-return + "C416", # unnecessary-comprehension + "PLR1733", # unnecessary-dict-index-lookup + "PLR1736", # unnecessary-list-index-lookup + + # ruff reports this rule is unstable + #"PLR6301", # no-self-use + + "PLW0108", # unnecessary-lambda + "PLW0120", # useless-else-on-loop + "PLW0127", # self-assigning-variable + "PLW0129", # assert-on-string-literal + "B033", # duplicate-value + "PLW0131", # named-expr-without-context + "PLW0245", # super-without-brackets + "PLW0406", # import-self + "PLW0602", # global-variable-not-assigned + "PLW0603", # global-statement + "PLW0604", # global-at-module-level + + # fails on the try: import typing used by libraries + #"F401", # unused-import + + "F841", # unused-variable + "E722", # bare-except + "PLW0711", # binary-op-exception + "PLW1501", # bad-open-mode + "PLW1508", # invalid-envvar-default + "PLW1509", # subprocess-popen-preexec-fn + "PLW2101", # useless-with-lock + "PLW3301", # nested-min-max +] + +ignore = [ + "PLR2004", # magic-value-comparison + "UP030", # format literals + "PLW1514", # unspecified-encoding + "PLR0913", # too-many-arguments + "PLR0915", # too-many-statements + "PLR0917", # too-many-positional-arguments + "PLR0904", # too-many-public-methods + "PLR0912", # too-many-branches + "PLR0916", # too-many-boolean-expressions + "PLR6301", # method-could-be-function + "PLR0911", # too-many-return-statements + "PLW0603", # global-statement +] + +[format] +line-ending = "lf" diff --git a/setup.py b/setup.py deleted file mode 100644 index 9b238e3..0000000 --- a/setup.py +++ /dev/null @@ -1,57 +0,0 @@ -# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries -# -# SPDX-License-Identifier: MIT - -"""A setuptools based setup module. - -See: -https://packaging.python.org/en/latest/distributing.html -https://github.com/pypa/sampleproject -""" - -from setuptools import setup, find_packages - -# To use a consistent encoding -from codecs import open -from os import path - -here = path.abspath(path.dirname(__file__)) - -# Get the long description from the README file -with open(path.join(here, "README.rst"), encoding="utf-8") as f: - long_description = f.read() - -setup( - name="adafruit-circuitpython-fona", - use_scm_version=True, - setup_requires=["setuptools_scm"], - description="CircuitPython library for the Adafruit FONAA", - long_description=long_description, - long_description_content_type="text/x-rst", - # The project's main homepage. - url="https://github.com/adafruit/Adafruit_CircuitPython_FONA", - # Author details - author="Adafruit Industries", - author_email="circuitpython@adafruit.com", - install_requires=["Adafruit-Blinka", "adafruit-circuitpython-busdevice"], - # Choose your license - license="MIT", - # See https://pypi.python.org/pypi?%3Aaction=list_classifiers - classifiers=[ - "Development Status :: 3 - Alpha", - "Intended Audience :: Developers", - "Topic :: Software Development :: Libraries", - "Topic :: System :: Hardware", - "License :: OSI Approved :: MIT License", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.4", - "Programming Language :: Python :: 3.5", - ], - # What does your project relate to? - keywords="adafruit blinka circuitpython micropython fona fona, cellular", - # You can just specify the packages manually here if your project is - # simple. Or you can use find_packages(). - # TODO: IF LIBRARY FILES ARE A PACKAGE FOLDER, - # CHANGE `py_modules=['...']` TO `packages=['...']` - packages=["adafruit_fona"], -) pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy