diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml new file mode 100644 index 0000000..fe7e0f6 --- /dev/null +++ b/.github/workflows/build.yml @@ -0,0 +1,57 @@ +name: Build CI + +on: [pull_request, push] + +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.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 dependencies + # (e.g. - apt-get: gettext, etc; pip: circuitpython-build-tools, requirements.txt; etc.) + run: | + source actions-ci/install.sh + - name: Pip install pylint, black, & Sphinx + run: | + pip install --force-reinstall pylint==1.9.2 black==19.10b0 Sphinx sphinx-rtd-theme + - name: Library version + run: git describe --dirty --always --tags + - name: PyLint + run: | + pylint $( find . -path './adafruit*.py' ) + ([[ ! -d "examples" ]] || pylint --disable=missing-docstring,invalid-name,bad-whitespace $( find . -path "./examples/*.py" )) + - name: Check formatting + run: | + black --check --target-version=py35 . + - name: Build assets + run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location . + - name: Build docs + working-directory: docs + run: sphinx-build -E -W -b html . _build/html diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..18efb9c --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,81 @@ +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/.gitignore b/.gitignore new file mode 100644 index 0000000..966df0f --- /dev/null +++ b/.gitignore @@ -0,0 +1,14 @@ +*.mpy +.idea +__pycache__ +_build +*.pyc +.env +.python-version +build*/ +bundles +*.DS_Store +.eggs +dist +**/*.egg-info +.vscode diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..d8f0ee8 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,433 @@ +[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 +jobs=2 + +# 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 + +# 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=no + +# 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.yml b/.readthedocs.yml new file mode 100644 index 0000000..f4243ad --- /dev/null +++ b/.readthedocs.yml @@ -0,0 +1,3 @@ +python: + version: 3 +requirements_file: requirements.txt diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..7ca3a1d --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,127 @@ +# Adafruit Community Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and leaders pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level or type of +experience, education, socio-economic status, nationality, personal appearance, +race, religion, or sexual identity and orientation. + +## Our Standards + +We are committed to providing a friendly, safe and welcoming environment for +all. + +Examples of behavior that contributes to creating a positive environment +include: + +* Be kind and courteous to others +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Collaborating with other community members +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and sexual attention or advances +* The use of inappropriate images, including in a community member's avatar +* The use of inappropriate language, including in a community member's nickname +* Any spamming, flaming, baiting or other attention-stealing behavior +* Excessive or unwelcome helping; answering outside the scope of the question + asked +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate + +The goal of the standards and moderation guidelines outlined here is to build +and maintain a respectful community. We ask that you don’t just aim to be +"technically unimpeachable", but rather try to be your best self. + +We value many things beyond technical expertise, including collaboration and +supporting others within our community. Providing a positive experience for +other community members can have a much more significant impact than simply +providing the correct answer. + +## Our Responsibilities + +Project leaders are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project leaders have the right and responsibility to remove, edit, or +reject messages, comments, commits, code, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any community member for other behaviors that they deem +inappropriate, threatening, offensive, or harmful. + +## Moderation + +Instances of behaviors that violate the Adafruit Community Code of Conduct +may be reported by any member of the community. Community members are +encouraged to report these situations, including situations they witness +involving other community members. + +You may report in the following ways: + +In any situation, you may send an email to . + +On the Adafruit Discord, you may send an open message from any channel +to all Community Helpers by tagging @community moderators. You may also send an +open message from any channel, or a direct message to @kattni#1507, +@tannewt#4653, @Dan Halbert#1614, @cater#2442, @sommersoft#0222, or +@Andon#8175. + +Email and direct message reports will be kept confidential. + +In situations on Discord where the issue is particularly egregious, possibly +illegal, requires immediate action, or violates the Discord terms of service, +you should also report the message directly to Discord. + +These are the steps for upholding our community’s standards of conduct. + +1. Any member of the community may report any situation that violates the +Adafruit Community Code of Conduct. All reports will be reviewed and +investigated. +2. If the behavior is an egregious violation, the community member who +committed the violation may be banned immediately, without warning. +3. Otherwise, moderators will first respond to such behavior with a warning. +4. Moderators follow a soft "three strikes" policy - the community member may +be given another chance, if they are receptive to the warning and change their +behavior. +5. If the community member is unreceptive or unreasonable when warned by a +moderator, or the warning goes unheeded, they may be banned for a first or +second offense. Repeated offenses will result in the community member being +banned. + +## Scope + +This Code of Conduct and the enforcement policies listed above apply to all +Adafruit Community venues. This includes but is not limited to any community +spaces (both public and private), the entire Adafruit Discord server, and +Adafruit GitHub repositories. Examples of Adafruit Community spaces include +but are not limited to meet-ups, audio chats on the Adafruit Discord, or +interaction at a conference. + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. As a community +member, you are representing our community, and are expected to behave +accordingly. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 1.4, available at +, +and the [Rust Code of Conduct](https://www.rust-lang.org/en-US/conduct.html). + +For other projects adopting the Adafruit Community Code of +Conduct, please contact the maintainers of those projects for enforcement. +If you wish to use this code of conduct for your own project, consider +explicitly mentioning your moderation policy or making a copy with your +own moderation policy so as to avoid confusion. diff --git a/LICENSE b/LICENSE index 4e961d0..a7005d5 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ -MIT License +The MIT License (MIT) -Copyright (c) 2020 Adafruit Industries +Copyright (c) 2020 Brent Rubell for Adafruit Industries Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md deleted file mode 100644 index 94a6177..0000000 --- a/README.md +++ /dev/null @@ -1,2 +0,0 @@ -# Adafruit_CircuitPython_FONA -CircuitPython Library for the Adafruit FONA diff --git a/README.rst b/README.rst new file mode 100644 index 0000000..a6f4611 --- /dev/null +++ b/README.rst @@ -0,0 +1,74 @@ +Introduction +============ + +.. image:: https://readthedocs.org/projects/adafruit-circuitpython-fona/badge/?version=latest + :target: https://circuitpython.readthedocs.io/projects/fona/en/latest/ + :alt: Documentation Status + +.. image:: https://img.shields.io/discord/327254708534116352.svg + :target: https://discord.gg/nBQh6qu + :alt: Discord + +.. image:: https://github.com/adafruit/Adafruit_CircuitPython_FONA/workflows/Build%20CI/badge.svg + :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 + +CircuitPython library for the `Adafruit FONA `_ cellular module. + + +Dependencies +============= +This driver depends on: + +* `Adafruit CircuitPython `_ +* `SimpleIO `_ + +Please ensure all dependencies are available on the CircuitPython filesystem. +This is easily achieved by downloading +`the Adafruit library and driver bundle `_. + +Installing from PyPI +===================== + +On supported GNU/Linux systems like the Raspberry Pi, you can install the driver locally `from +PyPI `_. To install for current user: + +.. code-block:: shell + + pip3 install adafruit-circuitpython-fona + +To install system-wide (this may be required in some cases): + +.. code-block:: shell + + sudo pip3 install adafruit-circuitpython-fona + +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 + pip3 install adafruit-circuitpython-fona + +Usage Example +============= + +Please see the examples directory for code usage. + +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/__init__.py b/adafruit_fona/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/adafruit_fona/adafruit_fona.py b/adafruit_fona/adafruit_fona.py new file mode 100644 index 0000000..b851bc6 --- /dev/null +++ b/adafruit_fona/adafruit_fona.py @@ -0,0 +1,892 @@ +# The MIT License (MIT) +# +# Copyright Limor Fried/Ladyada for Adafruit Industries +# Copyright (c) 2020 Brent Rubell for Adafruit Industries +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +""" +`adafruit_fona` +================================================================================ + +CircuitPython library for the Adafruit FONA cellular module + + +* Author(s): ladyada, Brent Rubell + +Implementation Notes +-------------------- + +**Software and Dependencies:** + +* Adafruit CircuitPython firmware for the supported boards: + https://github.com/adafruit/circuitpython/releases + +""" +import time +from micropython import const +from simpleio import map_range + +__version__ = "0.0.0-auto.0" +__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_FONA.git" + +# pylint: disable=bad-whitespace +FONA_DEFAULT_TIMEOUT_MS = 500 # TODO: Check this against arduino... + +# COMMANDS +CMD_AT = b"AT" +# REPLIES +REPLY_OK = b"OK" +REPLY_AT = b"AT" + +# FONA Versions +FONA_800_L = const(0x01) +FONA_800_H = const(0x6) +FONA_808_V1 = const(0x2) +FONA_808_V2 = const(0x3) +FONA_3G_A = const(0x4) +FONA_3G_E = const(0x5) + +# HTTP Actions +FONA_HTTP_GET = const(0x00) +FONA_HTTP_POST = const(0x01) +FONA_HTTP_HEAD = const(0x02) + +# TCP/IP +FONA_TCP_MODE = const(0) +FONA_UDP_MODE = const(1) +FONA_MAX_SOCKETS = const(6) +# pylint: enable=bad-whitespace + +# pylint: disable=too-many-instance-attributes +class FONA: + """CircuitPython FONA module interface. + :param ~busio.uart UART: FONA UART connection. + :param ~digialio RST: FONA RST Pin. + :param bool debug: Enable debugging output. + + """ + + # pylint: disable=too-many-arguments + def __init__(self, uart, rst, debug=False): + self._buf = b"" # shared buffer + self._fona_type = 0 + self._debug = debug + + self._uart = uart + self._rst = rst + if not self._init_fona(): + raise RuntimeError("Unable to find FONA. Please check connections.") + + # GPRS + self._apn = None + self._apn_username = None + self._apn_password = None + + @property + # pylint: disable=too-many-return-statements + def version(self): + """Returns FONA Version, as a string.""" + if self._fona_type == FONA_800_L: + return "FONA 800L" + if self._fona_type == FONA_800_H: + return "FONA 800H" + if self._fona_type == FONA_808_V1: + return "FONA 808 (v1)" + if self._fona_type == FONA_808_V2: + return "FONA 808 (v2)" + if self._fona_type == FONA_3G_A: + return "FONA 3G (US)" + if self._fona_type == FONA_3G_E: + return "FONA 3G (EU)" + return -1 + + @property + def iemi(self): + """Returns FONA module's IEMI number.""" + self._buf = b"" + self._uart.reset_input_buffer() + + if self._debug: + print("\t---> ", "AT+GSN") + self._uart.write(b"AT+GSN\r\n") + self._read_line(multiline=True) + iemi = self._buf[0:15] + return iemi.decode("utf-8") + + def pretty_ip(self, ip): # pylint: disable=no-self-use, invalid-name + """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]) + + @property + def local_ip(self): + """Returns the local IP Address.""" + if self._debug: + print("\t---> AT+CIFSR") + + self._uart.write(b"AT+CIFSR\r\n") + self._read_line() + return self.pretty_ip(self._buf) + + # pylint: disable=too-many-branches, too-many-statements + def _init_fona(self): + """Initializes FONA module.""" + # RST module + self._rst.switch_to_output() + self._rst.value = True + time.sleep(0.01) + self._rst.value = False + time.sleep(0.1) + self._rst.value = True + + if self._debug: + print("Attempting to open comm with ATs") + timeout = 7 + while timeout > 0: + if self._send_check_reply(CMD_AT, reply=REPLY_OK): + break + if self._send_check_reply(CMD_AT, reply=REPLY_AT): + break + time.sleep(0.5) + timeout -= 500 + + if timeout <= 0: + if self._debug: + print(" * Timeout: No response to AT. Last ditch attempt.") + self._send_check_reply(CMD_AT, reply=REPLY_OK) + time.sleep(0.1) + self._send_check_reply(CMD_AT, reply=REPLY_OK) + time.sleep(0.1) + self._send_check_reply(CMD_AT, reply=REPLY_OK) + time.sleep(0.1) + + # turn off echo + self._send_check_reply(b"ATE0", reply=REPLY_OK) + time.sleep(0.1) + + if not self._send_check_reply(b"ATE0", reply=REPLY_OK): + return False + time.sleep(0.1) + + # turn on hangupitude + self._send_check_reply(b"AT+CVHU=0", reply=REPLY_OK) + time.sleep(0.1) + + self._buf = b"" + self._uart.reset_input_buffer() + + if self._debug: + print("\t---> ", "ATI") + self._uart.write(b"ATI\r\n") + self._read_line(multiline=True) + + if self._buf.find(b"SIM808 R14") != -1: + self._fona_type = FONA_808_V2 + elif self._buf.find(b"SIM808 R13") != -1: + self._fona_type = FONA_808_V1 + elif self._buf.find(b"SIMCOM_SIM5320A") != -1: + 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 _H + if self._debug: + print("\t ---> AT+GMM") + self._uart.write(b"AT+GMM\r\n") + self._read_line(multiline=True) + if self._debug: + print("\t <---", self._buf) + + if self._buf.find(b"SIM800H") != -1: + self._fona_type = FONA_800_H + return True + + @property + def gprs(self): + """Returns module's GPRS state.""" + if self._debug: + print("* Check GPRS State") + if not self._send_parse_reply(b"AT+CGATT?", b"+CGATT: ", ":"): + return False + return self._buf + + def set_gprs(self, config): + """If config provided, sets GPRS configuration to provided tuple in format: + (apn_network, apn_username, apn_password) + + """ + if self._debug: + print("* Setting GPRS Config to: ", config) + apn, username, password = config + self._apn = apn.encode() + self._apn_username = username.encode() + self._apn_password = password.encode() + return self._apn, self._apn_username, self._apn_password + + # pylint: disable=too-many-return-statements + @gprs.setter + def gprs(self, gprs_on=True): + """Enables or disables GPRS configuration. + :param bool gprs_on: Turns on GPRS, enabled by default. + + """ + if gprs_on: + if self._debug: + print("* Enabling GPRS..") + + # enable multi connection mode (3,1) + if not self._send_check_reply(b"AT+CIPMUX=1", reply=REPLY_OK): + return False + + # enable receive data manually (7,2) + if not self._send_check_reply(b"AT+CIPRXGET=1", reply=REPLY_OK): + return False + + # disconnect all sockets + self._send_check_reply(b"AT+CIPSHUT", reply=b"SHUT OK", timeout=20000) + + if not self._send_check_reply(b"AT+CGATT=1", reply=REPLY_OK, timeout=10000): + return False + + # set bearer profile (APN) + if not self._send_check_reply( + b'AT+SAPBR=3,1,"CONTYPE","GPRS"', reply=REPLY_OK, timeout=10000 + ): + return False + + if self._apn is not None: + # Send command AT+SAPBR=3,1,"APN","" + # where is the configured APN value. + self._send_check_reply_quoted( + b'AT+SAPBR=3,1,"APN",', self._apn, REPLY_OK, 10000 + ) + + # send AT+CSTT,"apn","user","pass" + if self._debug: + print("setting APN...") + self._uart.reset_input_buffer() + + self._uart.write(b'AT+CSTT="' + self._apn) + + if self._apn_username is not None: + self._uart.write(b'","' + self._apn_username) + + if self._apn_password is not None: + self._uart.write(b'","' + self._apn_password) + self._uart.write(b'"\r\n') + + if not self._get_reply(REPLY_OK): + return False + + # Set username + if not self._send_check_reply_quoted( + b'AT+SAPBR=3,1,"USER",', self._apn_username, REPLY_OK, 10000 + ): + return False + + # Set password + if not self._send_check_reply_quoted( + b'AT+SAPBR=3,1,"PWD",', self._apn_password, REPLY_OK, 100000 + ): + return False + + # Open GPRS context + self._send_check_reply(b"AT+SAPBR=1,1", reply=b"", timeout=100000) + + # Bring up wireless connection + if not self._send_check_reply( + b"AT+CIICR", reply=REPLY_OK, timeout=10000 + ): + return False + + else: + # Disconnect all sockets + if not self._send_check_reply( + b"AT+CIPSHUT", reply=b"SHUT OK", timeout=20000 + ): + return False + + # Close GPRS context + if not self._send_check_reply( + b"AT+SAPBR=0,1", reply=REPLY_OK, timeout=10000 + ): + return False + if not self._send_check_reply( + b"AT+CGATT=0", reply=REPLY_OK, timeout=10000 + ): + return False + + return True + + @property + def network_status(self): + """Returns cellular/network status""" + if not self._send_parse_reply(b"AT+CREG?", b"+CREG: ", idx=1): + return False + if self._buf == 0: + # Not Registered + return self._buf + if self._buf == 1: + # Registered (home) + return self._buf + if self._buf == 2: + # Not Registered (searching) + return self._buf + if self._buf == 3: + # Denied + return self._buf + if self._buf == 4: + # Unknown + return self._buf + if self._buf == 5: + # Registered Roaming + return self._buf + # "Unknown" + return self._buf + + @property + def rssi(self): + """Returns cellular network's Received Signal Strength Indicator (RSSI).""" + if not self._send_parse_reply(b"AT+CSQ", b"+CSQ: "): + return False + + reply_num = self._buf + rssi = 0 + if reply_num == 0: + rssi = -115 + elif reply_num == 1: + rssi = -111 + elif reply_num == 31: + rssi = -52 + + if 2 <= reply_num <= 30: + rssi = map_range(reply_num, 2, 30, -110, -54) + + # read out the 'ok' + self._read_line() + return rssi + + @property + def gps(self): + """Returns the GPS status.""" + if self._debug: + print("GPS STATUS") + if self._fona_type == FONA_808_V2: + # 808 V2 uses GNS commands and doesn't have an explicit 2D/3D fix status. + # 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: + return False + + status = int(self._buf[10:11].decode("utf-8")) + if status == 1: + status = 3 # assume 3D fix + self._read_line() + elif self._fona_type == FONA_3G_A or self._fona_type == FONA_3G_E: + raise NotImplementedError( + "FONA 3G not currently supported by this library." + ) + else: + raise NotImplementedError( + "FONA 808 v1 not currently supported by this library." + ) + + return status + + @gps.setter + def gps(self, gps_on=False): + """Enables or disables the GPS module. + NOTE: This is only for FONA 3G or FONA808 modules. + :param bool gps_on: Enables the GPS module, disabled by default. + + """ + if self._debug: + print("* Setting GPS") + if not ( + self._fona_type == FONA_3G_A + or self._fona_type == FONA_3G_E + or self._fona_type == FONA_808_V1 + or self._fona_type == FONA_808_V2 + ): + raise TypeError("GPS unsupported for this FONA module.") + + # check if already enabled or disabled + if self._fona_type == FONA_808_V2: + if not self._send_parse_reply(b"AT+CGPSPWR?", b"+CGPSPWR: ", ":"): + return False + self._read_line() + if not self._send_parse_reply(b"AT+CGNSPWR?", b"+CGNSPWR: ", ":"): + return False + + state = self._buf + + if gps_on and not state: + self._read_line() + if self._fona_type == FONA_808_V2: + # try GNS + print("trying 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 + + return True + + def get_host_by_name(self, hostname): + """Converts a hostname to a packed 4-byte IP address. + Returns a 4 bytearray. + :param str hostname: Destination server. + + """ + self._read_line() + if self._debug: + print("*** get_host_by_name") + if isinstance(hostname, str): + hostname = bytes(hostname, "utf-8") + + self._uart.write(b'AT+CDNSGIP="' + hostname + b'"\r\n') + + if not self._expect_reply(REPLY_OK): + return False + # eat the blank line + self._read_line() + # parse the 3rd line + self._read_line() + + self._parse_reply(b"+CDNSGIP:", idx=2) + return self._buf + + ### Socket API (TCP, UDP) ### + + def get_socket(self, sockets): + """Returns the first avaliable (unused) socket + by the socket module. + + """ + if self._debug: + print("*** Allocating Socket") + sock = 0 + for sock in range(0, FONA_MAX_SOCKETS): + if sock not in sockets: + break + if self._debug: + print("Allocated socket #", sock) + return sock + + def remote_ip(self, sock_num): + """Returns the IP address of the host who sent the current incoming packet. + :param int sock_num: Desired socket. + + """ + 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) + + self._parse_reply(b"+CIPSTATUS:", idx=3) + if self._debug: + print("\t<--- ", self._buf) + return self._buf + + def socket_status(self, sock_num): + """Returns if socket is connected. + :param int sock_num: Desired socket number. + + """ + 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 + + # eat the 'STATE: ' message + self._read_line() + if self._debug: + print("\t<--- ", self._buf) + + # read "C: " for each active connection + for state in range(0, sock_num + 1): + self._read_line() + if state == sock_num: + break + self._parse_reply(b"C:", idx=5) + + state = self._buf + + # eat the rest of the sockets + for _ in range(sock_num, FONA_MAX_SOCKETS): + self._read_line() + + if not "CONNECTED" in state: + return False + + return True + + def socket_available(self, sock_num): + """Returns the amount of bytes to be read from the socket. + :param int sock_num: Desired socket to return bytes available from. + + """ + self._read_line() + 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(), + b"+CIPRXGET: 4," + str(sock_num).encode() + b",", + ): + return False + if self._debug: + print("\t {} bytes available.".format(self._buf)) + + return self._buf + + def socket_connect(self, sock_num, dest, port, conn_mode=FONA_TCP_MODE): + """Connects to a destination IP address or hostname. + By default, we use conn_mode FONA_TCP_MODE but we may also use FONA_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) + + """ + self._uart.reset_input_buffer() + assert ( + sock_num < FONA_MAX_SOCKETS + ), "Provided socket exceeds the maximum number of \ + sockets for the FONA module." + + if self._debug: + print( + "* FONA socket connect, socket={}, protocol={}, port={}, ip={}".format( + sock_num, conn_mode, port, dest + ) + ) + + # Start connection + self._uart.write(b"AT+CIPSTART=") + self._uart.write(str(sock_num).encode()) + if conn_mode == FONA_TCP_MODE: + if self._debug: + print('\t--->AT+CIPSTART="TCP","{}",{}'.format(dest, port)) + self._uart.write(b',"TCP","') + else: + if self._debug: + print('\t--->AT+CIPSTART="UDP","{}",{}'.format(dest, port)) + self._uart.write(b',"UDP","') + self._uart.write(dest.encode() + b'","') + self._uart.write(str(port).encode() + b'"') + self._uart.write(b"\r\n") + + if not self._expect_reply(REPLY_OK): + return False + + if not self._expect_reply(b"CONNECT OK"): + return False + + return True + + def socket_close(self, sock_num, quick_close=1): + """Close TCP or UDP connection + :param int sock_num: Desired socket number. + :param int quick_close: Quickly or slowly close the socket. Enabled by default + + """ + assert ( + sock_num < FONA_MAX_SOCKETS + ), "Provided socket exceeds the maximum number of \ + sockets for the FONA module." + # eat prv. response + self._read_line() + self._uart.write(b"AT+CIPCLOSE=" + str(sock_num).encode()) + self._uart.write(b"," + str(quick_close).encode() + b"\r\n") + + self._read_line() + self._parse_reply(b"", idx=1) + if not "CLOSE OK" in self._buf: + return False + return True + + def socket_read(self, sock_num, length): + """Read data from the network into a buffer. + Returns buffer and amount of bytes read. + :param int sock_num: Desired socket to read from. + :param int length: Desired length to read. + + """ + assert ( + sock_num < FONA_MAX_SOCKETS + ), "Provided socket exceeds the maximum number of \ + sockets for the FONA module." + self._read_line() + if self._debug: + print("* socket read") + print("\t ---> AT+CIPRXGET=2,{},{}".format(sock_num, length)) + self._uart.write(b"AT+CIPRXGET=2,") + self._uart.write(str(sock_num).encode()) + self._uart.write(b",") + self._uart.write(str(length).encode() + b"\r\n") + + self._read_line() + + if not self._parse_reply(b"+CIPRXGET:"): + return False + + self._buf = self._uart.read(length) + + return self._buf + + def socket_write(self, sock_num, buffer): + """Writes bytes to the socket. + :param int sock_num: Desired socket number to write to. + :param bytes buffer: Bytes to write to socket. + + """ + self._read_line() + assert ( + sock_num < FONA_MAX_SOCKETS + ), "Provided socket exceeds the maximum number of \ + sockets for the FONA module." + + if self._debug: + print("\t--->AT+CIPSEND={},{}".format(sock_num, len(buffer))) + + self._uart.reset_input_buffer() + self._uart.write(b"AT+CIPSEND=" + str(sock_num).encode()) + self._uart.write(b"," + str(len(buffer)).encode()) + self._uart.write(b"\r\n") + self._read_line() + + if self._debug: + print("\t<--- ", self._buf) + + if self._buf[0] != 62: + # promoting mark ('>') not found + return False + + self._uart.write(buffer + b"\r\n") + self._read_line(3000) + + if self._debug: + print("\t<--- ", self._buf) + + if "SEND OK" not in self._buf.decode(): + return False + + return True + + ### UART Reply/Response Helpers ### + + def _send_parse_reply(self, send_data, reply_data, divider=",", idx=0): + """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._get_reply(send_data) + + if not self._parse_reply(reply_data, divider, idx): + return False + return True + + def _get_reply( + self, data=None, prefix=None, suffix=None, timeout=FONA_DEFAULT_TIMEOUT_MS + ): + """Send data to FONA, read response into buffer. + :param bytes data: Data to send to FONA module. + :param int timeout: Time to wait for UART response. + + """ + self._uart.reset_input_buffer() + + if data is not None: + if self._debug: + print("\t---> ", data) + self._uart.write(data + "\r\n") + else: + if self._debug: + print("\t---> {}{}".format(prefix, suffix)) + self._uart.write(prefix + suffix + b"\r\n") + + self._buf = b"" + line = self._read_line(timeout) + + if self._debug: + print("\t<--- ", self._buf) + return line + + def _parse_reply(self, reply, divider=",", idx=0): + """Attempts to find reply in UART buffer, reads up to divider. + :param bytes reply: Expected response from FONA module. + :param str divider: Divider character. + + """ + # attempt to find reply in buffer + parsed_reply = self._buf.find(reply) + if parsed_reply == -1: + return False + parsed_reply = self._buf[parsed_reply:] + + parsed_reply = self._buf[len(reply) :] + parsed_reply = parsed_reply.decode("utf-8") + + parsed_reply = parsed_reply.split(divider) + parsed_reply = parsed_reply[idx] + + try: + self._buf = int(parsed_reply) + except ValueError: + self._buf = parsed_reply + + return True + + def _read_line(self, timeout=FONA_DEFAULT_TIMEOUT_MS, multiline=False): + """Reads one or multiple lines into the buffer. + :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 + while timeout: + if reply_idx >= 254: + break + + while self._uart.in_waiting: + char = self._uart.read(1) + # print(char) + if char == b"\r": + continue + if char == b"\n": + if reply_idx == 0: + # ignore first '\n' + continue + if not multiline: + # second '\n' is EOL + timeout = 0 + break + # print(char, self._buf) + self._buf += char + reply_idx += 1 + + if timeout == 0: + # if self._debug: + # print("* Timed out!") + break + timeout -= 1 + time.sleep(0.001) + + return reply_idx + + def _send_check_reply( + self, + send=None, + prefix=None, + suffix=None, + reply=None, + timeout=FONA_DEFAULT_TIMEOUT_MS, + ): + """Sends data to FONA, validates response. + :param bytes send: Command. + :param bytes reply: Expected response from module. + + """ + 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 + # validate response + if not reply in self._buf: + return False + + return True + + def _send_check_reply_quoted( + self, prefix, suffix, reply, timeout=FONA_DEFAULT_TIMEOUT_MS + ): + """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"" + + self._get_reply_quoted(prefix, suffix, timeout) + + # validate response + if reply not in self._buf: + return False + return True + + def _get_reply_quoted(self, prefix, suffix, timeout): + """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() + + if self._debug: + print("\t---> ", end="") + print(prefix, end="") + print('""', end="") + print(suffix, end="") + print('""') + + self._uart.write(prefix + b'"') + self._uart.write(suffix + b'"\r\n') + + line = self._read_line(timeout) + + if self._debug: + print("\t<--- ", self._buf) + + return line + + def _expect_reply(self, reply, timeout=10000): + """Reads line from FONA module and compares to reply from FONA module. + :param bytes reply: Expected reply from module. + + """ + self._read_line(timeout) + if self._debug: + print("\t<--- ", self._buf) + if reply not in self._buf: + return False + return True diff --git a/adafruit_fona/adafruit_fona_socket.py b/adafruit_fona/adafruit_fona_socket.py new file mode 100644 index 0000000..ad2d9b9 --- /dev/null +++ b/adafruit_fona/adafruit_fona_socket.py @@ -0,0 +1,248 @@ +# The MIT License (MIT) +# +# Copyright (c) 2019 ladyada for Adafruit Industries +# Modified by Brent Rubell for Adafruit Industries, 2020 +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +# THE SOFTWARE. +""" +`adafruit_fona_socket` +================================================================================ + +A socket compatible interface with the Adafruit FONA cellular module. + +* Author(s): ladyada, Brent Rubell + +""" +import gc +import time +from micropython import const + +_the_interface = None # pylint: disable=invalid-name + + +def set_interface(iface): + """Helper to set the global internet interface.""" + global _the_interface # pylint: disable=global-statement, invalid-name + _the_interface = iface + + +def htonl(x): + """Convert 32-bit positive integers from host to network byte order.""" + return ( + ((x) << 24 & 0xFF000000) + | ((x) << 8 & 0x00FF0000) + | ((x) >> 8 & 0x0000FF00) + | ((x) >> 24 & 0x000000FF) + ) + + +def htons(x): + """Convert 16-bit positive integers from host to network byte order.""" + return (((x) << 8) & 0xFF00) | (((x) >> 8) & 0xFF) + + +# pylint: disable=bad-whitespace +SOCK_STREAM = const(0x00) # TCP +TCP_MODE = 80 +SOCK_DGRAM = const(0x01) # UDP +AF_INET = const(3) +NO_SOCKET_AVAIL = const(255) +# pylint: enable=bad-whitespace + +# 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): + """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. + """ + if not isinstance(port, int): + raise RuntimeError("Port must be an integer") + return [(AF_INET, socktype, proto, "", (gethostbyname(host), port))] + + +def gethostbyname(hostname): + """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 + + +# 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 + ): + if family != AF_INET: + raise RuntimeError("Only AF_INET family supported by cellular sockets.") + self._sock_type = type + self._buffer = b"" + self._timeout = 0 + + self._socknum = _the_interface.get_socket(SOCKETS) + SOCKETS.append(self._socknum) + self.settimeout(self._timeout) + + @property + def socknum(self): + """Returns the socket object's socket number.""" + return self._socknum + + @property + def connected(self): + """Returns whether or not we are connected to the socket.""" + return _the_interface.socket_status(self.socknum) + + def getpeername(self): + """Return the remote address to which the socket is connected.""" + return _the_interface.remote_ip(self.socknum) + + def inet_aton(self, ip_string): + """Convert an IPv4 address from dotted-quad string format. + :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): + """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." + host, port = address + + 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): + """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. + + """ + _the_interface.socket_write(self._socknum, data) + gc.collect() + + def recv(self, bufsize=0): + """Reads some bytes from the connected remote address. + :param int bufsize: maximum number of bytes to receive + """ + # print("Socket read", bufsize) + if bufsize == 0: # read as much as we can at the moment + while True: + avail = self.available() + if avail: + self._buffer += _the_interface.socket_read(self._socknum, avail) + else: + break + gc.collect() + ret = self._buffer + self._buffer = b"" + gc.collect() + return ret + stamp = time.monotonic() + + to_read = bufsize - len(self._buffer) + received = [] + while to_read > 0: + # print("Bytes to read:", to_read) + avail = self.available() + if avail: + stamp = time.monotonic() + recv = _the_interface.socket_read(self._socknum, min(to_read, avail)) + received.append(recv) + to_read -= len(recv) + gc.collect() + if self._timeout > 0 and time.monotonic() - stamp > self._timeout: + break + # print(received) + self._buffer += b"".join(received) + + ret = None + if len(self._buffer) == bufsize: + ret = self._buffer + self._buffer = b"" + else: + ret = self._buffer[:bufsize] + self._buffer = self._buffer[bufsize:] + gc.collect() + return ret + + def readline(self): + """Attempt to return as many bytes as we can up to but not including '\r\n'""" + # print("Socket readline") + stamp = time.monotonic() + while b"\r\n" not in self._buffer: + # there's no line already in there, read some more + avail = self.available() + if avail: + self._buffer += _the_interface.socket_read(self._socknum, avail) + elif self._timeout > 0 and time.monotonic() - stamp > self._timeout: + self.close() # Make sure to close socket so that we don't exhaust sockets. + raise RuntimeError("Didn't receive full response, failing out") + firstline, self._buffer = self._buffer.split(b"\r\n", 1) + gc.collect() + return firstline + + def available(self): + """Returns how many bytes are available to be read from the socket. + + """ + return _the_interface.socket_available(self._socknum) + + def settimeout(self, value): + """Sets socket read timeout. + :param int value: Socket read timeout, in seconds. + + """ + if value < 0: + raise Exception("Timeout period should be non-negative.") + self._timeout = value + + def gettimeout(self): + """Return the timeout in seconds (float) associated + with socket operations, or None if no timeout is set. + + """ + return self._timeout + + def close(self): + """Closes the socket.""" + return _the_interface.socket_close(self._socknum) diff --git a/docs/_static/favicon.ico b/docs/_static/favicon.ico new file mode 100644 index 0000000..5aca983 Binary files /dev/null and b/docs/_static/favicon.ico differ diff --git a/docs/api.rst b/docs/api.rst new file mode 100644 index 0000000..30fd54d --- /dev/null +++ b/docs/api.rst @@ -0,0 +1,11 @@ + +.. If you created a package, create one automodule per module in the package. + +.. If your library file(s) are nested in a directory (e.g. /adafruit_foo/foo.py) +.. use this format as the module name: "adafruit_foo.foo" + +.. automodule:: adafruit_fona.adafruit_fona + :members: + +.. automodule:: adafruit_fona.adafruit_fona_socket + :members: \ No newline at end of file diff --git a/docs/conf.py b/docs/conf.py new file mode 100644 index 0000000..ac79ab7 --- /dev/null +++ b/docs/conf.py @@ -0,0 +1,182 @@ +# -*- coding: utf-8 -*- + +import os +import sys + +sys.path.insert(0, os.path.abspath("..")) + +# -- General configuration ------------------------------------------------ + +# Add any Sphinx extension module names here, as strings. They can be +# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom +# ones. +extensions = [ + "sphinx.ext.autodoc", + "sphinx.ext.intersphinx", + "sphinx.ext.napoleon", + "sphinx.ext.todo", +] + +# TODO: Please Read! +# Uncomment the below if you use native CircuitPython modules such as +# digitalio, micropython and busio. List the modules you use. Without it, the +# autodoc module docs will fail to generate with a warning. +autodoc_mock_imports = ["micropython", "simpleio"] + + +intersphinx_mapping = { + "python": ("https://docs.python.org/3.4", None), + "BusDevice": ( + "https://circuitpython.readthedocs.io/projects/busdevice/en/latest/", + None, + ), + "CircuitPython": ("https://circuitpython.readthedocs.io/en/latest/", None), +} + +# Add any paths that contain templates here, relative to this directory. +templates_path = ["_templates"] + +source_suffix = ".rst" + +# The master toctree document. +master_doc = "index" + +# General information about the project. +project = "Adafruit FONA Library" +copyright = "2020 Brent Rubell, ladyada" +author = "Brent Rubell, ladyada" + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = "1.0" +# The full version, including alpha/beta/rc tags. +release = "1.0" + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +# +# This is also used if you do content translation via gettext catalogs. +# Usually you set "language" from the command line for these cases. +language = None + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +# This patterns also effect to html_static_path and html_extra_path +exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", ".env", "CODE_OF_CONDUCT.md"] + +# The reST default role (used for this markup: `text`) to use for all +# documents. +# +default_role = "any" + +# If true, '()' will be appended to :func: etc. cross-reference text. +# +add_function_parentheses = True + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = "sphinx" + +# If true, `todo` and `todoList` produce output, else they produce nothing. +todo_include_todos = False + +# If this is True, todo emits a warning for each TODO entries. The default is False. +todo_emit_warnings = True + +napoleon_numpy_docstring = False + +# -- Options for HTML output ---------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +# +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 = ["."] + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ["_static"] + +# The name of an image file (relative to this directory) to use as a favicon of +# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +# +html_favicon = "_static/favicon.ico" + +# Output file base name for HTML help builder. +htmlhelp_basename = "AdafruitFonaLibrarydoc" + +# -- Options for LaTeX output --------------------------------------------- + +latex_elements = { + # The paper size ('letterpaper' or 'a4paper'). + # + # 'papersize': 'letterpaper', + # The font size ('10pt', '11pt' or '12pt'). + # + # 'pointsize': '10pt', + # Additional stuff for the LaTeX preamble. + # + # 'preamble': '', + # Latex figure (float) alignment + # + # 'figure_align': 'htbp', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, +# author, documentclass [howto, manual, or own class]). +latex_documents = [ + ( + master_doc, + "AdafruitFONALibrary.tex", + "AdafruitFONA Library Documentation", + author, + "manual", + ) +] + +# -- Options for manual page output --------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ( + master_doc, + "AdafruitFONAlibrary", + "Adafruit FONA Library Documentation", + [author], + 1, + ) +] + +# -- Options for Texinfo output ------------------------------------------- + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ( + master_doc, + "AdafruitFONALibrary", + "Adafruit FONA Library Documentation", + author, + "AdafruitFONALibrary", + "One line description of project.", + "Miscellaneous", + ) +] diff --git a/docs/examples.rst b/docs/examples.rst new file mode 100644 index 0000000..898070b --- /dev/null +++ b/docs/examples.rst @@ -0,0 +1,8 @@ +Simple test +------------ + +Ensure your device works with this simple test. + +.. literalinclude:: ../examples/fona_simpletest.py + :caption: examples/fona_simpletest.py + :linenos: diff --git a/docs/index.rst b/docs/index.rst new file mode 100644 index 0000000..f0dbc6f --- /dev/null +++ b/docs/index.rst @@ -0,0 +1,48 @@ +.. include:: ../README.rst + +Table of Contents +================= + +.. toctree:: + :maxdepth: 4 + :hidden: + + self + +.. toctree:: + :caption: Examples + + examples + +.. toctree:: + :caption: API Reference + :maxdepth: 3 + + api + +.. toctree:: + :caption: Tutorials + +.. toctree:: + :caption: Related Products + + Adafruit FONA808 Breakout + Adafruit FONA808 Shield + +.. toctree:: + :caption: Other Links + + Download + CircuitPython Reference Documentation + CircuitPython Support Forum + Discord Chat + Adafruit Learning System + Adafruit Blog + Adafruit Store + +Indices and tables +================== + +* :ref:`genindex` +* :ref:`modindex` +* :ref:`search` diff --git a/examples/fona_simpletest.py b/examples/fona_simpletest.py new file mode 100644 index 0000000..389b315 --- /dev/null +++ b/examples/fona_simpletest.py @@ -0,0 +1,74 @@ +import time +import board +import busio +import digitalio +from adafruit_fona.adafruit_fona import FONA +import adafruit_fona.adafruit_fona_socket as socket + +SERVER_ADDRESS = ("wifitest.adafruit.com", 80) + +# 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 + +# Create a serial connection for the FONA connection using 4800 baud. +# These are the defaults you should use for the FONA Shield. +# For other boards set RX = GPS module TX, and TX = GPS module RX pins. +uart = busio.UART(board.TX, board.RX, baudrate=4800) +rst = digitalio.DigitalInOut(board.D4) + +# Initialize FONA module (this may take a few seconds) +fona = FONA(uart, rst) + +print("Adafruit FONA WebClient Test") + +# Enable GPS +fona.gps = True +while fona.gps != 3: + print("Waiting for GPS fix, retrying...") + time.sleep(5) + +# Bring up cellular connection +fona.set_gprs((secrets["apn"], secrets["apn_username"], secrets["apn_password"])) +while fona.network_status != 1: + print("Not registered to a network, waiting...") + time.sleep(5) +time.sleep(5) + +# Bring up GPRS +fona.gprs = True +time.sleep(6) + +print("Local IP: ", fona.local_ip) + +# Set socket interface +socket.set_interface(fona) + +sock = socket.socket() + +print("Connecting to: ", SERVER_ADDRESS[0]) +sock.connect(SERVER_ADDRESS) + +print("Connected to:", sock.getpeername()) +time.sleep(7) + +# Make a HTTP Request +sock.send(b"GET /testwifi/index.html HTTP/1.1\n") +sock.send(b"Host: 104.236.193.178") +sock.send(b"Connection: close\n\n") + +bytes_avail = 0 +while not bytes_avail: + bytes_avail = sock.available() + if bytes_avail > 0: + print("bytes_avail: ", bytes_avail) + data = sock.recv(bytes_avail) + print(data.decode()) + break + time.sleep(0.05) + +sock.close() +print("Socket connected: ", sock.connected) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..20a172f --- /dev/null +++ b/requirements.txt @@ -0,0 +1,3 @@ +Adafruit-Blinka +adafruit-circuitpython-busdevice +adafruit-circuitpython-simpleio diff --git a/setup.py b/setup.py new file mode 100644 index 0000000..5e3f70b --- /dev/null +++ b/setup.py @@ -0,0 +1,53 @@ +"""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=['...']` + py_modules=["adafruit_fona"], +)