├── .github ├── PULL_REQUEST_TEMPLATE │ └── adafruit_circuitpython_pr.md └── workflows │ ├── build.yml │ ├── failure-help-text.yml │ └── release.yml ├── .gitignore ├── .pre-commit-config.yaml ├── .pylintrc ├── CODE_OF_CONDUCT.md ├── CircuitPython_websockets ├── examples │ └── websockets_simpletest.py └── requirements.txt ├── LICENSE ├── LICENSES ├── CC-BY-4.0.txt ├── MIT.txt └── Unlicense.txt ├── README.md ├── README.rst ├── README.rst.license ├── examples ├── connect_circuitpython.py ├── cpython_server │ ├── README.md │ ├── client.py │ ├── echo.py │ └── server.py ├── obs_remote_demo │ ├── README.md │ ├── code.py │ ├── obs_colors.py │ ├── obs_pins.py │ └── obsws.py ├── secrets.py ├── status_led.py └── test_all_wsorg.py ├── pyproject.toml ├── requirements.txt ├── setup.py.disabled └── websockets ├── __init__.py ├── client.py ├── protocol.py └── socket.py /.github/PULL_REQUEST_TEMPLATE/adafruit_circuitpython_pr.md: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | Thank you for contributing! Before you submit a pull request, please read the following. 6 | 7 | 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 8 | 9 | If your changes are to documentation, please verify that the documentation builds locally by following the steps found here: https://adafru.it/build-docs 10 | 11 | Before submitting the pull request, make sure you've run Pylint and Black locally on your code. You can do this manually or using pre-commit. Instructions are available here: https://adafru.it/check-your-code 12 | 13 | Please remove all of this text before submitting. Include an explanation or list of changes included in your PR, as well as, if applicable, a link to any related issues. 14 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | name: Build CI 6 | 7 | on: [pull_request, push] 8 | 9 | jobs: 10 | test: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Dump GitHub context 14 | env: 15 | GITHUB_CONTEXT: ${{ toJson(github) }} 16 | run: echo "$GITHUB_CONTEXT" 17 | - name: Translate Repo Name For Build Tools filename_prefix 18 | id: repo-name 19 | run: | 20 | echo ::set-output name=repo-name::$( 21 | echo ${{ github.repository }} | 22 | awk -F '\/' '{ print tolower($2) }' | 23 | tr '_' '-' 24 | ) 25 | - name: Set up Python 3.x 26 | uses: actions/setup-python@v2 27 | with: 28 | python-version: "3.x" 29 | - name: Versions 30 | run: | 31 | python3 --version 32 | - name: Checkout Current Repo 33 | uses: actions/checkout@v1 34 | with: 35 | submodules: true 36 | - name: Checkout tools repo 37 | uses: actions/checkout@v2 38 | with: 39 | repository: adafruit/actions-ci-circuitpython-libs 40 | path: actions-ci 41 | - name: Install dependencies 42 | # (e.g. - apt-get: gettext, etc; pip: circuitpython-build-tools, requirements.txt; etc.) 43 | run: | 44 | source actions-ci/install.sh 45 | - name: Pip install Sphinx, pre-commit 46 | run: | 47 | pip install --force-reinstall Sphinx sphinx-rtd-theme pre-commit 48 | - name: Library version 49 | run: git describe --dirty --always --tags 50 | - name: Setup problem matchers 51 | uses: adafruit/circuitpython-action-library-ci-problem-matchers@v1 52 | - name: Pre-commit hooks 53 | run: | 54 | pre-commit run --all-files 55 | - name: Build assets 56 | run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location . 57 | - name: Archive bundles 58 | uses: actions/upload-artifact@v2 59 | with: 60 | name: bundles 61 | path: ${{ github.workspace }}/bundles/ 62 | # - name: Build docs 63 | # working-directory: docs 64 | # run: sphinx-build -E -W -b html . _build/html 65 | # - name: Check For pyproject.toml 66 | # id: need-pypi 67 | # run: | 68 | # echo ::set-output name=pyproject-toml::$( find . -wholename './pyproject.toml' ) 69 | # - name: Build Python package 70 | # if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') 71 | # run: | 72 | # pip install --upgrade build twine 73 | # for file in $(find -not -path "./.*" -not -path "./docs*" \( -name "*.py" -o -name "*.toml" \) ); do 74 | # sed -i -e "s/0.0.0+auto.0/1.2.3/" $file; 75 | # done; 76 | # python -m build 77 | # twine check dist/* 78 | -------------------------------------------------------------------------------- /.github/workflows/failure-help-text.yml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 Scott Shawcroft for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | name: Failure help text 6 | 7 | on: 8 | workflow_run: 9 | workflows: ["Build CI"] 10 | types: 11 | - completed 12 | 13 | jobs: 14 | post-help: 15 | runs-on: ubuntu-latest 16 | if: ${{ github.event.workflow_run.conclusion == 'failure' && github.event.workflow_run.event == 'pull_request' }} 17 | steps: 18 | - name: Post comment to help 19 | uses: adafruit/circuitpython-action-library-ci-failed@v1 20 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | name: Release Actions 6 | 7 | on: 8 | release: 9 | types: [published] 10 | 11 | jobs: 12 | upload-release-assets: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Dump GitHub context 16 | env: 17 | GITHUB_CONTEXT: ${{ toJson(github) }} 18 | run: echo "$GITHUB_CONTEXT" 19 | - name: Translate Repo Name For Build Tools filename_prefix 20 | id: repo-name 21 | run: | 22 | echo ::set-output name=repo-name::$( 23 | echo ${{ github.repository }} | 24 | awk -F '\/' '{ print tolower($2) }' | 25 | tr '_' '-' 26 | ) 27 | - name: Set up Python 3.x 28 | uses: actions/setup-python@v2 29 | with: 30 | python-version: "3.x" 31 | - name: Versions 32 | run: | 33 | python3 --version 34 | - name: Checkout Current Repo 35 | uses: actions/checkout@v1 36 | with: 37 | submodules: true 38 | - name: Checkout tools repo 39 | uses: actions/checkout@v2 40 | with: 41 | repository: adafruit/actions-ci-circuitpython-libs 42 | path: actions-ci 43 | - name: Install deps 44 | run: | 45 | source actions-ci/install.sh 46 | - name: Build assets 47 | run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location . 48 | - name: Upload Release Assets 49 | # the 'official' actions version does not yet support dynamically 50 | # supplying asset names to upload. @csexton's version chosen based on 51 | # discussion in the issue below, as its the simplest to implement and 52 | # allows for selecting files with a pattern. 53 | # https://github.com/actions/upload-release-asset/issues/4 54 | #uses: actions/upload-release-asset@v1.0.1 55 | uses: csexton/release-asset-action@master 56 | with: 57 | pattern: "bundles/*" 58 | github-token: ${{ secrets.GITHUB_TOKEN }} 59 | 60 | # upload-pypi: 61 | # runs-on: ubuntu-latest 62 | # steps: 63 | # - uses: actions/checkout@v1 64 | # - name: Check For pyproject.toml 65 | # id: need-pypi 66 | # run: | 67 | # echo ::set-output name=pyproject-toml::$( find . -wholename './pyproject.toml' ) 68 | # - name: Set up Python 69 | # if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') 70 | # uses: actions/setup-python@v2 71 | # with: 72 | # python-version: '3.x' 73 | # - name: Install dependencies 74 | # if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') 75 | # run: | 76 | # python -m pip install --upgrade pip 77 | # pip install --upgrade build twine 78 | # - name: Build and publish 79 | # if: contains(steps.need-pypi.outputs.pyproject-toml, 'pyproject.toml') 80 | # env: 81 | # TWINE_USERNAME: ${{ secrets.pypi_username }} 82 | # TWINE_PASSWORD: ${{ secrets.pypi_password }} 83 | # run: | 84 | # for file in $(find -not -path "./.*" -not -path "./docs*" \( -name "*.py" -o -name "*.toml" \) ); do 85 | # sed -i -e "s/0.0.0+auto.0/${{github.event.release.tag_name}}/" $file; 86 | # done; 87 | # python -m build 88 | # twine upload dist/* 89 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2022 Kattni Rembor, written for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | # Do not include files and directories created by your personal work environment, such as the IDE 6 | # you use, except for those already listed here. Pull requests including changes to this file will 7 | # not be accepted. 8 | 9 | # This .gitignore file contains rules for files generated by working with CircuitPython libraries, 10 | # including building Sphinx, testing with pip, and creating a virual environment, as well as the 11 | # MacOS and IDE-specific files generated by using MacOS in general, or the PyCharm or VSCode IDEs. 12 | 13 | # If you find that there are files being generated on your machine that should not be included in 14 | # your git commit, you should create a .gitignore_global file on your computer to include the 15 | # files created by your personal setup. To do so, follow the two steps below. 16 | 17 | # First, create a file called .gitignore_global somewhere convenient for you, and add rules for 18 | # the files you want to exclude from git commits. 19 | 20 | # Second, configure Git to use the exclude file for all Git repositories by running the 21 | # following via commandline, replacing "path/to/your/" with the actual path to your newly created 22 | # .gitignore_global file: 23 | # git config --global core.excludesfile path/to/your/.gitignore_global 24 | 25 | # CircuitPython-specific files 26 | *.mpy 27 | 28 | # Python-specific files 29 | __pycache__ 30 | *.pyc 31 | 32 | # Sphinx build-specific files 33 | _build 34 | 35 | # This file results from running `pip -e install .` in a local repository 36 | *.egg-info 37 | 38 | # Virtual environment-specific files 39 | .env 40 | .venv 41 | 42 | # MacOS-specific files 43 | *.DS_Store 44 | 45 | # IDE-specific files 46 | .idea 47 | .vscode 48 | *~ 49 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2020 Diego Elio Pettenò 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | 5 | repos: 6 | - repo: https://github.com/python/black 7 | rev: 22.3.0 8 | hooks: 9 | - id: black 10 | - repo: https://github.com/fsfe/reuse-tool 11 | rev: v0.14.0 12 | hooks: 13 | - id: reuse 14 | - repo: https://github.com/pre-commit/pre-commit-hooks 15 | rev: v4.2.0 16 | hooks: 17 | - id: check-yaml 18 | - id: end-of-file-fixer 19 | - id: trailing-whitespace 20 | - repo: https://github.com/pycqa/pylint 21 | rev: v2.15.5 22 | hooks: 23 | - id: pylint 24 | name: pylint (library code) 25 | types: [python] 26 | args: 27 | - --disable=consider-using-f-string 28 | exclude: "^(docs/|examples/|tests/|setup.py$)" 29 | # - id: pylint 30 | # name: pylint (example code) 31 | # description: Run pylint rules on "examples/*.py" files 32 | # types: [python] 33 | # files: "^examples/" 34 | # args: 35 | # - --disable=missing-docstring,invalid-name,consider-using-f-string,duplicate-code 36 | - id: pylint 37 | name: pylint (test code) 38 | description: Run pylint rules on "tests/*.py" files 39 | types: [python] 40 | files: "^tests/" 41 | args: 42 | - --disable=missing-docstring,consider-using-f-string,duplicate-code 43 | -------------------------------------------------------------------------------- /.pylintrc: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | 5 | [MASTER] 6 | 7 | # A comma-separated list of package or module names from where C extensions may 8 | # be loaded. Extensions are loading into the active Python interpreter and may 9 | # run arbitrary code 10 | extension-pkg-whitelist= 11 | 12 | # Add files or directories to the ignore-list. They should be base names, not 13 | # paths. 14 | ignore=CVS 15 | 16 | # Add files or directories matching the regex patterns to the ignore-list. The 17 | # regex matches against base names, not paths. 18 | ignore-patterns= 19 | 20 | # Python code to execute, usually for sys.path manipulation such as 21 | # pygtk.require(). 22 | #init-hook= 23 | 24 | # Use multiple processes to speed up Pylint. 25 | jobs=1 26 | 27 | # List of plugins (as comma separated values of python modules names) to load, 28 | # usually to register additional checkers. 29 | load-plugins=pylint.extensions.no_self_use 30 | 31 | # Pickle collected data for later comparisons. 32 | persistent=yes 33 | 34 | # Specify a configuration file. 35 | #rcfile= 36 | 37 | # Allow loading of arbitrary C extensions. Extensions are imported into the 38 | # active Python interpreter and may run arbitrary code. 39 | unsafe-load-any-extension=no 40 | 41 | 42 | [MESSAGES CONTROL] 43 | 44 | # Only show warnings with the listed confidence levels. Leave empty to show 45 | # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED 46 | confidence= 47 | 48 | # Disable the message, report, category or checker with the given id(s). You 49 | # can either give multiple identifiers separated by comma (,) or put this 50 | # option multiple times (only on the command line, not in the configuration 51 | # file where it should appear only once).You can also use "--disable=all" to 52 | # disable everything first and then reenable specific checks. For example, if 53 | # you want to run only the similarities checker, you can use "--disable=all 54 | # --enable=similarities". If you want to run only the classes checker, but have 55 | # no Warning level messages displayed, use"--disable=all --enable=classes 56 | # --disable=W" 57 | # disable=import-error,raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,deprecated-str-translate-call 58 | disable=raw-checker-failed,bad-inline-option,locally-disabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,import-error,pointless-string-statement,unspecified-encoding 59 | 60 | # Enable the message, report, category or checker with the given id(s). You can 61 | # either give multiple identifier separated by comma (,) or put this option 62 | # multiple time (only on the command line, not in the configuration file where 63 | # it should appear only once). See also the "--disable" option for examples. 64 | enable= 65 | 66 | 67 | [REPORTS] 68 | 69 | # Python expression which should return a note less than 10 (10 is the highest 70 | # note). You have access to the variables errors warning, statement which 71 | # respectively contain the number of errors / warnings messages and the total 72 | # number of statements analyzed. This is used by the global evaluation report 73 | # (RP0004). 74 | evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) 75 | 76 | # Template used to display messages. This is a python new-style format string 77 | # used to format the message information. See doc for all details 78 | #msg-template= 79 | 80 | # Set the output format. Available formats are text, parseable, colorized, json 81 | # and msvs (visual studio).You can also give a reporter class, eg 82 | # mypackage.mymodule.MyReporterClass. 83 | output-format=text 84 | 85 | # Tells whether to display a full report or only the messages 86 | reports=no 87 | 88 | # Activate the evaluation score. 89 | score=yes 90 | 91 | 92 | [REFACTORING] 93 | 94 | # Maximum number of nested blocks for function / method body 95 | max-nested-blocks=5 96 | 97 | 98 | [LOGGING] 99 | 100 | # Logging modules to check that the string format arguments are in logging 101 | # function parameter format 102 | logging-modules=logging 103 | 104 | 105 | [SPELLING] 106 | 107 | # Spelling dictionary name. Available dictionaries: none. To make it working 108 | # install python-enchant package. 109 | spelling-dict= 110 | 111 | # List of comma separated words that should not be checked. 112 | spelling-ignore-words= 113 | 114 | # A path to a file that contains private dictionary; one word per line. 115 | spelling-private-dict-file= 116 | 117 | # Tells whether to store unknown words to indicated private dictionary in 118 | # --spelling-private-dict-file option instead of raising a message. 119 | spelling-store-unknown-words=no 120 | 121 | 122 | [MISCELLANEOUS] 123 | 124 | # List of note tags to take in consideration, separated by a comma. 125 | # notes=FIXME,XXX,TODO 126 | notes=FIXME,XXX 127 | 128 | 129 | [TYPECHECK] 130 | 131 | # List of decorators that produce context managers, such as 132 | # contextlib.contextmanager. Add to this list to register other decorators that 133 | # produce valid context managers. 134 | contextmanager-decorators=contextlib.contextmanager 135 | 136 | # List of members which are set dynamically and missed by pylint inference 137 | # system, and so shouldn't trigger E1101 when accessed. Python regular 138 | # expressions are accepted. 139 | generated-members= 140 | 141 | # Tells whether missing members accessed in mixin class should be ignored. A 142 | # mixin class is detected if its name ends with "mixin" (case insensitive). 143 | ignore-mixin-members=yes 144 | 145 | # This flag controls whether pylint should warn about no-member and similar 146 | # checks whenever an opaque object is returned when inferring. The inference 147 | # can return multiple potential results while evaluating a Python object, but 148 | # some branches might not be evaluated, which results in partial inference. In 149 | # that case, it might be useful to still emit no-member and other checks for 150 | # the rest of the inferred objects. 151 | ignore-on-opaque-inference=yes 152 | 153 | # List of class names for which member attributes should not be checked (useful 154 | # for classes with dynamically set attributes). This supports the use of 155 | # qualified names. 156 | ignored-classes=optparse.Values,thread._local,_thread._local 157 | 158 | # List of module names for which member attributes should not be checked 159 | # (useful for modules/projects where namespaces are manipulated during runtime 160 | # and thus existing member attributes cannot be deduced by static analysis. It 161 | # supports qualified module names, as well as Unix pattern matching. 162 | ignored-modules=board 163 | 164 | # Show a hint with possible names when a member name was not found. The aspect 165 | # of finding the hint is based on edit distance. 166 | missing-member-hint=yes 167 | 168 | # The minimum edit distance a name should have in order to be considered a 169 | # similar match for a missing member name. 170 | missing-member-hint-distance=1 171 | 172 | # The total number of similar names that should be taken in consideration when 173 | # showing a hint for a missing member. 174 | missing-member-max-choices=1 175 | 176 | 177 | [VARIABLES] 178 | 179 | # List of additional names supposed to be defined in builtins. Remember that 180 | # you should avoid to define new builtins when possible. 181 | additional-builtins= 182 | 183 | # Tells whether unused global variables should be treated as a violation. 184 | allow-global-unused-variables=yes 185 | 186 | # List of strings which can identify a callback function by name. A callback 187 | # name must start or end with one of those strings. 188 | callbacks=cb_,_cb 189 | 190 | # A regular expression matching the name of dummy variables (i.e. expectedly 191 | # not used). 192 | dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ 193 | 194 | # Argument names that match this expression will be ignored. Default to name 195 | # with leading underscore 196 | ignored-argument-names=_.*|^ignored_|^unused_ 197 | 198 | # Tells whether we should check for unused import in __init__ files. 199 | init-import=no 200 | 201 | # List of qualified module names which can have objects that can redefine 202 | # builtins. 203 | redefining-builtins-modules=six.moves,future.builtins 204 | 205 | 206 | [FORMAT] 207 | 208 | # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. 209 | # expected-line-ending-format= 210 | expected-line-ending-format=LF 211 | 212 | # Regexp for a line that is allowed to be longer than the limit. 213 | ignore-long-lines=^\s*(# )??$ 214 | 215 | # Number of spaces of indent required inside a hanging or continued line. 216 | indent-after-paren=4 217 | 218 | # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 219 | # tab). 220 | indent-string=' ' 221 | 222 | # Maximum number of characters on a single line. 223 | max-line-length=100 224 | 225 | # Maximum number of lines in a module 226 | max-module-lines=1000 227 | 228 | # Allow the body of a class to be on the same line as the declaration if body 229 | # contains single statement. 230 | single-line-class-stmt=no 231 | 232 | # Allow the body of an if to be on the same line as the test if there is no 233 | # else. 234 | single-line-if-stmt=no 235 | 236 | 237 | [SIMILARITIES] 238 | 239 | # Ignore comments when computing similarities. 240 | ignore-comments=yes 241 | 242 | # Ignore docstrings when computing similarities. 243 | ignore-docstrings=yes 244 | 245 | # Ignore imports when computing similarities. 246 | ignore-imports=yes 247 | 248 | # Minimum lines number of a similarity. 249 | min-similarity-lines=12 250 | 251 | 252 | [BASIC] 253 | 254 | # Regular expression matching correct argument names 255 | argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ 256 | 257 | # Regular expression matching correct attribute names 258 | attr-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ 259 | 260 | # Bad variable names which should always be refused, separated by a comma 261 | bad-names=foo,bar,baz,toto,tutu,tata 262 | 263 | # Regular expression matching correct class attribute names 264 | class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ 265 | 266 | # Regular expression matching correct class names 267 | # class-rgx=[A-Z_][a-zA-Z0-9]+$ 268 | class-rgx=[A-Z_][a-zA-Z0-9_]+$ 269 | 270 | # Regular expression matching correct constant names 271 | const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ 272 | 273 | # Minimum line length for functions/classes that require docstrings, shorter 274 | # ones are exempt. 275 | docstring-min-length=-1 276 | 277 | # Regular expression matching correct function names 278 | function-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ 279 | 280 | # Good variable names which should always be accepted, separated by a comma 281 | # good-names=i,j,k,ex,Run,_ 282 | good-names=r,g,b,w,i,j,k,n,x,y,z,ex,ok,Run,_ 283 | 284 | # Include a hint for the correct naming format with invalid-name 285 | include-naming-hint=no 286 | 287 | # Regular expression matching correct inline iteration names 288 | inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ 289 | 290 | # Regular expression matching correct method names 291 | method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ 292 | 293 | # Regular expression matching correct module names 294 | module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ 295 | 296 | # Colon-delimited sets of names that determine each other's naming style when 297 | # the name regexes allow several styles. 298 | name-group= 299 | 300 | # Regular expression which should only match function or class names that do 301 | # not require a docstring. 302 | no-docstring-rgx=^_ 303 | 304 | # List of decorators that produce properties, such as abc.abstractproperty. Add 305 | # to this list to register other decorators that produce valid properties. 306 | property-classes=abc.abstractproperty 307 | 308 | # Regular expression matching correct variable names 309 | variable-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ 310 | 311 | 312 | [IMPORTS] 313 | 314 | # Allow wildcard imports from modules that define __all__. 315 | allow-wildcard-with-all=no 316 | 317 | # Analyse import fallback blocks. This can be used to support both Python 2 and 318 | # 3 compatible code, which means that the block might have code that exists 319 | # only in one or another interpreter, leading to false positives when analysed. 320 | analyse-fallback-blocks=no 321 | 322 | # Deprecated modules which should not be used, separated by a comma 323 | deprecated-modules=optparse,tkinter.tix 324 | 325 | # Create a graph of external dependencies in the given file (report RP0402 must 326 | # not be disabled) 327 | ext-import-graph= 328 | 329 | # Create a graph of every (i.e. internal and external) dependencies in the 330 | # given file (report RP0402 must not be disabled) 331 | import-graph= 332 | 333 | # Create a graph of internal dependencies in the given file (report RP0402 must 334 | # not be disabled) 335 | int-import-graph= 336 | 337 | # Force import order to recognize a module as part of the standard 338 | # compatibility libraries. 339 | known-standard-library= 340 | 341 | # Force import order to recognize a module as part of a third party library. 342 | known-third-party=enchant 343 | 344 | 345 | [CLASSES] 346 | 347 | # List of method names used to declare (i.e. assign) instance attributes. 348 | defining-attr-methods=__init__,__new__,setUp 349 | 350 | # List of member names, which should be excluded from the protected access 351 | # warning. 352 | exclude-protected=_asdict,_fields,_replace,_source,_make 353 | 354 | # List of valid names for the first argument in a class method. 355 | valid-classmethod-first-arg=cls 356 | 357 | # List of valid names for the first argument in a metaclass class method. 358 | valid-metaclass-classmethod-first-arg=mcs 359 | 360 | 361 | [DESIGN] 362 | 363 | # Maximum number of arguments for function / method 364 | max-args=5 365 | 366 | # Maximum number of attributes for a class (see R0902). 367 | # max-attributes=7 368 | max-attributes=11 369 | 370 | # Maximum number of boolean expressions in a if statement 371 | max-bool-expr=5 372 | 373 | # Maximum number of branch for function / method body 374 | max-branches=12 375 | 376 | # Maximum number of locals for function / method body 377 | max-locals=15 378 | 379 | # Maximum number of parents for a class (see R0901). 380 | max-parents=7 381 | 382 | # Maximum number of public methods for a class (see R0904). 383 | max-public-methods=20 384 | 385 | # Maximum number of return / yield for function / method body 386 | max-returns=6 387 | 388 | # Maximum number of statements in function / method body 389 | max-statements=50 390 | 391 | # Minimum number of public methods for a class (see R0903). 392 | min-public-methods=1 393 | 394 | 395 | [EXCEPTIONS] 396 | 397 | # Exceptions that will emit a warning when being caught. Defaults to 398 | # "Exception" 399 | overgeneral-exceptions=Exception 400 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | 7 | # CircuitPython Community Code of Conduct 8 | 9 | ## Our Pledge 10 | 11 | In the interest of fostering an open and welcoming environment, we as 12 | contributors and leaders pledge to making participation in our project and 13 | our community a harassment-free experience for everyone, regardless of age, body 14 | size, disability, ethnicity, gender identity and expression, level or type of 15 | experience, education, socio-economic status, nationality, personal appearance, 16 | race, religion, or sexual identity and orientation. 17 | 18 | ## Our Standards 19 | 20 | We are committed to providing a friendly, safe and welcoming environment for 21 | all. 22 | 23 | Examples of behavior that contributes to creating a positive environment 24 | include: 25 | 26 | * Be kind and courteous to others 27 | * Using welcoming and inclusive language 28 | * Being respectful of differing viewpoints and experiences 29 | * Collaborating with other community members 30 | * Gracefully accepting constructive criticism 31 | * Focusing on what is best for the community 32 | * Showing empathy towards other community members 33 | 34 | Examples of unacceptable behavior by participants include: 35 | 36 | * The use of sexualized language or imagery and sexual attention or advances 37 | * The use of inappropriate images, including in a community member's avatar 38 | * The use of inappropriate language, including in a community member's nickname 39 | * Any spamming, flaming, baiting or other attention-stealing behavior 40 | * Excessive or unwelcome helping; answering outside the scope of the question 41 | asked 42 | * Discussion or promotion of activities or projects that intend or pose a risk of 43 | significant harm 44 | * Trolling, insulting/derogatory comments, and personal or political attacks 45 | * Promoting or spreading disinformation, lies, or conspiracy theories against 46 | a person, group, organisation, project, or community 47 | * Public or private harassment 48 | * Publishing others' private information, such as a physical or electronic 49 | address, without explicit permission 50 | * Other conduct which could reasonably be considered inappropriate 51 | 52 | The goal of the standards and moderation guidelines outlined here is to build 53 | and maintain a respectful community. We ask that you don’t just aim to be 54 | "technically unimpeachable", but rather try to be your best self. 55 | 56 | We value many things beyond technical expertise, including collaboration and 57 | supporting others within our community. Providing a positive experience for 58 | other community members can have a much more significant impact than simply 59 | providing the correct answer. 60 | 61 | ## Our Responsibilities 62 | 63 | Project leaders are responsible for clarifying the standards of acceptable 64 | behavior and are expected to take appropriate and fair corrective action in 65 | response to any instances of unacceptable behavior. 66 | 67 | Project leaders have the right and responsibility to remove, edit, or 68 | reject messages, comments, commits, code, issues, and other contributions 69 | that are not aligned to this Code of Conduct, or to ban temporarily or 70 | permanently any community member for other behaviors that they deem 71 | inappropriate, threatening, offensive, or harmful. 72 | 73 | ## Moderation 74 | 75 | Instances of behaviors that violate the CircuitPython Community Code of Conduct 76 | may be reported by any member of the community. Community members are 77 | encouraged to report these situations, including situations they witness 78 | involving other community members. 79 | 80 | You may report in the following ways: 81 | 82 | In any situation, you may email the project maintainer. 83 | 84 | Email reports will be kept confidential. 85 | 86 | In situations on GitHub where the issue is particularly offensive, possibly 87 | illegal, requires immediate action, or violates the GitHub terms of service, 88 | you should also report the message directly to GitHub via the comment, or via 89 | [GitHub Support](https://support.github.com/contact/report-abuse?category=report-abuse&report=other&report_type=unspecified). 90 | 91 | These are the steps for upholding our community’s standards of conduct. 92 | 93 | 1. Any member of the community may report any situation that violates the 94 | CircuitPython Community Code of Conduct. All reports will be reviewed and 95 | investigated. 96 | 2. If the behavior is a severe violation, the community member who 97 | committed the violation may be banned immediately, without warning. 98 | 3. Otherwise, moderators will first respond to such behavior with a warning. 99 | 4. Moderators follow a soft "three strikes" policy - the community member may 100 | be given another chance, if they are receptive to the warning and change their 101 | behavior. 102 | 5. If the community member is unreceptive or unreasonable when warned by a 103 | moderator, or the warning goes unheeded, they may be banned for a first or 104 | second offense. Repeated offenses will result in the community member being 105 | banned. 106 | 6. Disciplinary actions (warnings, bans, etc) for Code of Conduct violations apply 107 | to the platform where the violation occurred. However, depending on the severity 108 | of the violation, the disciplinary action may be applied across CircuitPython's 109 | other community platforms. For example, a severe violation in one Community forum 110 | may result in a ban on not only the CircuitPython GitHub organisation, 111 | but also on the CircuitPython Twitter, live stream text chats, etc. 112 | 113 | ## Scope 114 | 115 | This Code of Conduct and the enforcement policies listed above apply to all 116 | CircuitPython Community venues. This includes but is not limited to any community 117 | spaces (both public and private), and CircuitPython repositories. Examples of 118 | CircuitPython Community spaces include but are not limited to meet-ups, issue 119 | threads on GitHub, text chats during a live stream, or interaction at a conference. 120 | 121 | This Code of Conduct applies both within project spaces and in public spaces 122 | when an individual is representing the project or its community. As a community 123 | member, you are representing our community, and are expected to behave 124 | accordingly. 125 | 126 | ## Attribution 127 | 128 | This Code of Conduct is adapted from the 129 | [Adafruit Community Code of Conduct](https://github.com/adafruit/Adafruit_Community_Code_of_Conduct), 130 | which is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/), 131 | version 1.4, available on [contributor-covenant.org](https://www.contributor-covenant.org/version/1/4/code-of-conduct.html), 132 | and the [Rust Code of Conduct](https://www.rust-lang.org/en-US/conduct.html). 133 | 134 | For other projects adopting the CircuitPython Community Code of 135 | Conduct, please contact the maintainers of those projects for enforcement. 136 | If you wish to use this code of conduct for your own project, consider 137 | explicitly mentioning your moderation policy or making a copy with your 138 | own moderation policy so as to avoid confusion. 139 | -------------------------------------------------------------------------------- /CircuitPython_websockets/examples/websockets_simpletest.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 3 | # 4 | # SPDX-License-Identifier: Unlicense 5 | -------------------------------------------------------------------------------- /CircuitPython_websockets/requirements.txt: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 3 | # 4 | # SPDX-License-Identifier: MIT 5 | 6 | Adafruit-Blinka 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2022 Neradoc 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LICENSES/CC-BY-4.0.txt: -------------------------------------------------------------------------------- 1 | Creative Commons Attribution 4.0 International Creative Commons Corporation 2 | ("Creative Commons") is not a law firm and does not provide legal services 3 | or legal advice. Distribution of Creative Commons public licenses does not 4 | create a lawyer-client or other relationship. Creative Commons makes its licenses 5 | and related information available on an "as-is" basis. Creative Commons gives 6 | no warranties regarding its licenses, any material licensed under their terms 7 | and conditions, or any related information. Creative Commons disclaims all 8 | liability for damages resulting from their use to the fullest extent possible. 9 | 10 | Using Creative Commons Public Licenses 11 | 12 | Creative Commons public licenses provide a standard set of terms and conditions 13 | that creators and other rights holders may use to share original works of 14 | authorship and other material subject to copyright and certain other rights 15 | specified in the public license below. The following considerations are for 16 | informational purposes only, are not exhaustive, and do not form part of our 17 | licenses. 18 | 19 | Considerations for licensors: Our public licenses are intended for use by 20 | those authorized to give the public permission to use material in ways otherwise 21 | restricted by copyright and certain other rights. Our licenses are irrevocable. 22 | Licensors should read and understand the terms and conditions of the license 23 | they choose before applying it. Licensors should also secure all rights necessary 24 | before applying our licenses so that the public can reuse the material as 25 | expected. Licensors should clearly mark any material not subject to the license. 26 | This includes other CC-licensed material, or material used under an exception 27 | or limitation to copyright. More considerations for licensors : wiki.creativecommons.org/Considerations_for_licensors 28 | 29 | Considerations for the public: By using one of our public licenses, a licensor 30 | grants the public permission to use the licensed material under specified 31 | terms and conditions. If the licensor's permission is not necessary for any 32 | reason–for example, because of any applicable exception or limitation to copyright–then 33 | that use is not regulated by the license. Our licenses grant only permissions 34 | under copyright and certain other rights that a licensor has authority to 35 | grant. Use of the licensed material may still be restricted for other reasons, 36 | including because others have copyright or other rights in the material. A 37 | licensor may make special requests, such as asking that all changes be marked 38 | or described. Although not required by our licenses, you are encouraged to 39 | respect those requests where reasonable. More considerations for the public 40 | : wiki.creativecommons.org/Considerations_for_licensees Creative Commons Attribution 41 | 4.0 International Public License 42 | 43 | By exercising the Licensed Rights (defined below), You accept and agree to 44 | be bound by the terms and conditions of this Creative Commons Attribution 45 | 4.0 International Public License ("Public License"). To the extent this Public 46 | License may be interpreted as a contract, You are granted the Licensed Rights 47 | in consideration of Your acceptance of these terms and conditions, and the 48 | Licensor grants You such rights in consideration of benefits the Licensor 49 | receives from making the Licensed Material available under these terms and 50 | conditions. 51 | 52 | Section 1 – Definitions. 53 | 54 | a. Adapted Material means material subject to Copyright and Similar Rights 55 | that is derived from or based upon the Licensed Material and in which the 56 | Licensed Material is translated, altered, arranged, transformed, or otherwise 57 | modified in a manner requiring permission under the Copyright and Similar 58 | Rights held by the Licensor. For purposes of this Public License, where the 59 | Licensed Material is a musical work, performance, or sound recording, Adapted 60 | Material is always produced where the Licensed Material is synched in timed 61 | relation with a moving image. 62 | 63 | b. Adapter's License means the license You apply to Your Copyright and Similar 64 | Rights in Your contributions to Adapted Material in accordance with the terms 65 | and conditions of this Public License. 66 | 67 | c. Copyright and Similar Rights means copyright and/or similar rights closely 68 | related to copyright including, without limitation, performance, broadcast, 69 | sound recording, and Sui Generis Database Rights, without regard to how the 70 | rights are labeled or categorized. For purposes of this Public License, the 71 | rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. 72 | 73 | d. Effective Technological Measures means those measures that, in the absence 74 | of proper authority, may not be circumvented under laws fulfilling obligations 75 | under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, 76 | and/or similar international agreements. 77 | 78 | e. Exceptions and Limitations means fair use, fair dealing, and/or any other 79 | exception or limitation to Copyright and Similar Rights that applies to Your 80 | use of the Licensed Material. 81 | 82 | f. Licensed Material means the artistic or literary work, database, or other 83 | material to which the Licensor applied this Public License. 84 | 85 | g. Licensed Rights means the rights granted to You subject to the terms and 86 | conditions of this Public License, which are limited to all Copyright and 87 | Similar Rights that apply to Your use of the Licensed Material and that the 88 | Licensor has authority to license. 89 | 90 | h. Licensor means the individual(s) or entity(ies) granting rights under this 91 | Public License. 92 | 93 | i. Share means to provide material to the public by any means or process that 94 | requires permission under the Licensed Rights, such as reproduction, public 95 | display, public performance, distribution, dissemination, communication, or 96 | importation, and to make material available to the public including in ways 97 | that members of the public may access the material from a place and at a time 98 | individually chosen by them. 99 | 100 | j. Sui Generis Database Rights means rights other than copyright resulting 101 | from Directive 96/9/EC of the European Parliament and of the Council of 11 102 | March 1996 on the legal protection of databases, as amended and/or succeeded, 103 | as well as other essentially equivalent rights anywhere in the world. 104 | 105 | k. You means the individual or entity exercising the Licensed Rights under 106 | this Public License. Your has a corresponding meaning. 107 | 108 | Section 2 – Scope. 109 | 110 | a. License grant. 111 | 112 | 1. Subject to the terms and conditions of this Public License, the Licensor 113 | hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, 114 | irrevocable license to exercise the Licensed Rights in the Licensed Material 115 | to: 116 | 117 | A. reproduce and Share the Licensed Material, in whole or in part; and 118 | 119 | B. produce, reproduce, and Share Adapted Material. 120 | 121 | 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions 122 | and Limitations apply to Your use, this Public License does not apply, and 123 | You do not need to comply with its terms and conditions. 124 | 125 | 3. Term. The term of this Public License is specified in Section 6(a). 126 | 127 | 4. Media and formats; technical modifications allowed. The Licensor authorizes 128 | You to exercise the Licensed Rights in all media and formats whether now known 129 | or hereafter created, and to make technical modifications necessary to do 130 | so. The Licensor waives and/or agrees not to assert any right or authority 131 | to forbid You from making technical modifications necessary to exercise the 132 | Licensed Rights, including technical modifications necessary to circumvent 133 | Effective Technological Measures. For purposes of this Public License, simply 134 | making modifications authorized by this Section 2(a)(4) never produces Adapted 135 | Material. 136 | 137 | 5. Downstream recipients. 138 | 139 | A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed 140 | Material automatically receives an offer from the Licensor to exercise the 141 | Licensed Rights under the terms and conditions of this Public License. 142 | 143 | B. No downstream restrictions. You may not offer or impose any additional 144 | or different terms or conditions on, or apply any Effective Technological 145 | Measures to, the Licensed Material if doing so restricts exercise of the Licensed 146 | Rights by any recipient of the Licensed Material. 147 | 148 | 6. No endorsement. Nothing in this Public License constitutes or may be construed 149 | as permission to assert or imply that You are, or that Your use of the Licensed 150 | Material is, connected with, or sponsored, endorsed, or granted official status 151 | by, the Licensor or others designated to receive attribution as provided in 152 | Section 3(a)(1)(A)(i). 153 | 154 | b. Other rights. 155 | 156 | 1. Moral rights, such as the right of integrity, are not licensed under this 157 | Public License, nor are publicity, privacy, and/or other similar personality 158 | rights; however, to the extent possible, the Licensor waives and/or agrees 159 | not to assert any such rights held by the Licensor to the limited extent necessary 160 | to allow You to exercise the Licensed Rights, but not otherwise. 161 | 162 | 2. Patent and trademark rights are not licensed under this Public License. 163 | 164 | 3. To the extent possible, the Licensor waives any right to collect royalties 165 | from You for the exercise of the Licensed Rights, whether directly or through 166 | a collecting society under any voluntary or waivable statutory or compulsory 167 | licensing scheme. In all other cases the Licensor expressly reserves any right 168 | to collect such royalties. 169 | 170 | Section 3 – License Conditions. 171 | 172 | Your exercise of the Licensed Rights is expressly made subject to the following 173 | conditions. 174 | 175 | a. Attribution. 176 | 177 | 1. If You Share the Licensed Material (including in modified form), You must: 178 | 179 | A. retain the following if it is supplied by the Licensor with the Licensed 180 | Material: 181 | 182 | i. identification of the creator(s) of the Licensed Material and any others 183 | designated to receive attribution, in any reasonable manner requested by the 184 | Licensor (including by pseudonym if designated); 185 | 186 | ii. a copyright notice; 187 | 188 | iii. a notice that refers to this Public License; 189 | 190 | iv. a notice that refers to the disclaimer of warranties; 191 | 192 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 193 | 194 | B. indicate if You modified the Licensed Material and retain an indication 195 | of any previous modifications; and 196 | 197 | C. indicate the Licensed Material is licensed under this Public License, and 198 | include the text of, or the URI or hyperlink to, this Public License. 199 | 200 | 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner 201 | based on the medium, means, and context in which You Share the Licensed Material. 202 | For example, it may be reasonable to satisfy the conditions by providing a 203 | URI or hyperlink to a resource that includes the required information. 204 | 205 | 3. If requested by the Licensor, You must remove any of the information required 206 | by Section 3(a)(1)(A) to the extent reasonably practicable. 207 | 208 | 4. If You Share Adapted Material You produce, the Adapter's License You apply 209 | must not prevent recipients of the Adapted Material from complying with this 210 | Public License. 211 | 212 | Section 4 – Sui Generis Database Rights. 213 | 214 | Where the Licensed Rights include Sui Generis Database Rights that apply to 215 | Your use of the Licensed Material: 216 | 217 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, 218 | reuse, reproduce, and Share all or a substantial portion of the contents of 219 | the database; 220 | 221 | b. if You include all or a substantial portion of the database contents in 222 | a database in which You have Sui Generis Database Rights, then the database 223 | in which You have Sui Generis Database Rights (but not its individual contents) 224 | is Adapted Material; and 225 | 226 | c. You must comply with the conditions in Section 3(a) if You Share all or 227 | a substantial portion of the contents of the database. 228 | 229 | For the avoidance of doubt, this Section 4 supplements and does not replace 230 | Your obligations under this Public License where the Licensed Rights include 231 | other Copyright and Similar Rights. 232 | 233 | Section 5 – Disclaimer of Warranties and Limitation of Liability. 234 | 235 | a. Unless otherwise separately undertaken by the Licensor, to the extent possible, 236 | the Licensor offers the Licensed Material as-is and as-available, and makes 237 | no representations or warranties of any kind concerning the Licensed Material, 238 | whether express, implied, statutory, or other. This includes, without limitation, 239 | warranties of title, merchantability, fitness for a particular purpose, non-infringement, 240 | absence of latent or other defects, accuracy, or the presence or absence of 241 | errors, whether or not known or discoverable. Where disclaimers of warranties 242 | are not allowed in full or in part, this disclaimer may not apply to You. 243 | 244 | b. To the extent possible, in no event will the Licensor be liable to You 245 | on any legal theory (including, without limitation, negligence) or otherwise 246 | for any direct, special, indirect, incidental, consequential, punitive, exemplary, 247 | or other losses, costs, expenses, or damages arising out of this Public License 248 | or use of the Licensed Material, even if the Licensor has been advised of 249 | the possibility of such losses, costs, expenses, or damages. Where a limitation 250 | of liability is not allowed in full or in part, this limitation may not apply 251 | to You. 252 | 253 | c. The disclaimer of warranties and limitation of liability provided above 254 | shall be interpreted in a manner that, to the extent possible, most closely 255 | approximates an absolute disclaimer and waiver of all liability. 256 | 257 | Section 6 – Term and Termination. 258 | 259 | a. This Public License applies for the term of the Copyright and Similar Rights 260 | licensed here. However, if You fail to comply with this Public License, then 261 | Your rights under this Public License terminate automatically. 262 | 263 | b. Where Your right to use the Licensed Material has terminated under Section 264 | 6(a), it reinstates: 265 | 266 | 1. automatically as of the date the violation is cured, provided it is cured 267 | within 30 days of Your discovery of the violation; or 268 | 269 | 2. upon express reinstatement by the Licensor. 270 | 271 | c. For the avoidance of doubt, this Section 6(b) does not affect any right 272 | the Licensor may have to seek remedies for Your violations of this Public 273 | License. 274 | 275 | d. For the avoidance of doubt, the Licensor may also offer the Licensed Material 276 | under separate terms or conditions or stop distributing the Licensed Material 277 | at any time; however, doing so will not terminate this Public License. 278 | 279 | e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 280 | 281 | Section 7 – Other Terms and Conditions. 282 | 283 | a. The Licensor shall not be bound by any additional or different terms or 284 | conditions communicated by You unless expressly agreed. 285 | 286 | b. Any arrangements, understandings, or agreements regarding the Licensed 287 | Material not stated herein are separate from and independent of the terms 288 | and conditions of this Public License. 289 | 290 | Section 8 – Interpretation. 291 | 292 | a. For the avoidance of doubt, this Public License does not, and shall not 293 | be interpreted to, reduce, limit, restrict, or impose conditions on any use 294 | of the Licensed Material that could lawfully be made without permission under 295 | this Public License. 296 | 297 | b. To the extent possible, if any provision of this Public License is deemed 298 | unenforceable, it shall be automatically reformed to the minimum extent necessary 299 | to make it enforceable. If the provision cannot be reformed, it shall be severed 300 | from this Public License without affecting the enforceability of the remaining 301 | terms and conditions. 302 | 303 | c. No term or condition of this Public License will be waived and no failure 304 | to comply consented to unless expressly agreed to by the Licensor. 305 | 306 | d. Nothing in this Public License constitutes or may be interpreted as a limitation 307 | upon, or waiver of, any privileges and immunities that apply to the Licensor 308 | or You, including from the legal processes of any jurisdiction or authority. 309 | 310 | Creative Commons is not a party to its public licenses. Notwithstanding, Creative 311 | Commons may elect to apply one of its public licenses to material it publishes 312 | and in those instances will be considered the "Licensor." The text of the 313 | Creative Commons public licenses is dedicated to the public domain under the 314 | CC0 Public Domain Dedication. Except for the limited purpose of indicating 315 | that material is shared under a Creative Commons public license or as otherwise 316 | permitted by the Creative Commons policies published at creativecommons.org/policies, 317 | Creative Commons does not authorize the use of the trademark "Creative Commons" 318 | or any other trademark or logo of Creative Commons without its prior written 319 | consent including, without limitation, in connection with any unauthorized 320 | modifications to any of its public licenses or any other arrangements, understandings, 321 | or agreements concerning use of licensed material. For the avoidance of doubt, 322 | this paragraph does not form part of the public licenses. 323 | 324 | Creative Commons may be contacted at creativecommons.org. 325 | -------------------------------------------------------------------------------- /LICENSES/MIT.txt: -------------------------------------------------------------------------------- 1 | MIT License Copyright (c) 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is furnished 8 | to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice (including the next 11 | paragraph) shall be included in all copies or substantial portions of the 12 | Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 16 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 17 | OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 18 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF 19 | OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /LICENSES/Unlicense.txt: -------------------------------------------------------------------------------- 1 | This is free and unencumbered software released into the public domain. 2 | 3 | Anyone is free to copy, modify, publish, use, compile, sell, or distribute 4 | this software, either in source code form or as a compiled binary, for any 5 | purpose, commercial or non-commercial, and by any means. 6 | 7 | In jurisdictions that recognize copyright laws, the author or authors of this 8 | software dedicate any and all copyright interest in the software to the public 9 | domain. We make this dedication for the benefit of the public at large and 10 | to the detriment of our heirs and successors. We intend this dedication to 11 | be an overt act of relinquishment in perpetuity of all present and future 12 | rights to this software under copyright law. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 16 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 17 | BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 18 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH 19 | THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, 20 | please refer to 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Websockets For Circuitpython 2 | My tests with uwebsockets on circuitpython before maybe making a genuine fork/port. 3 | 4 | The code has been adpated to the ESP32S2 firt, then back to using socket.recv and such. It is not currently based on the latest uwebsockets, but an older version that I was using and worked with my code. *Don't forget to fill in the wifi SSID and password in secrets.py*. 5 | 6 | ### Universal Sockets branch for ESP32S2 and Airlift 7 | - Create a `websockets.Session` with: 8 | - **socket** the socket module. 9 | - **ssl=** the `ssl_context` for S2 (optional). 10 | - **iface=** the `ESP_SPIcontrol` interface object (optional). 11 | - `with session.client(url) as ws` 12 | - Connect as a client and return the WebSockets object. 13 | - Url is `ws://server:port` or `wss://server:port` 14 | - Use `ws.send` and `ws.recv` to exchange data with the server. 15 | - Uses a UniversalSocket abstraction class to encapsulate the differences. 16 | - `uwebsockets` client and protocol are left as unchanged as possible. 17 | - *(For now)* 18 | 19 | - Tested on FeatherS2. 20 | - Tested on nrf52840 Feather + Airflit Featherwing. 21 | 22 | Original uwebsockets implementation: 23 | https://github.com/danni/uwebsockets 24 | 25 | 26 | SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 27 | SPDX-License-Identifier: MIT 28 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Introduction 2 | ============ 3 | 4 | 5 | 6 | .. image:: https://img.shields.io/discord/327254708534116352.svg 7 | :target: https://adafru.it/discord 8 | :alt: Discord 9 | 10 | 11 | .. image:: https://github.com/Neradoc/CircuitPython_websockets/workflows/Build%20CI/badge.svg 12 | :target: https://github.com/Neradoc/CircuitPython_websockets/actions 13 | :alt: Build Status 14 | 15 | 16 | .. image:: https://img.shields.io/badge/code%20style-black-000000.svg 17 | :target: https://github.com/psf/black 18 | :alt: Code Style: Black 19 | 20 | A library to connect to a websockets server 21 | 22 | 23 | Dependencies 24 | ============= 25 | This driver depends on: 26 | 27 | * `Adafruit CircuitPython `_ 28 | 29 | Please ensure all dependencies are available on the CircuitPython filesystem. 30 | This is easily achieved by downloading 31 | `the Adafruit library and driver bundle `_ 32 | or individual libraries can be installed using 33 | `circup `_. 34 | 35 | Installing to a Connected CircuitPython Device with Circup 36 | ========================================================== 37 | 38 | Make sure that you have ``circup`` installed in your Python environment. 39 | Install it with the following command if necessary: 40 | 41 | .. code-block:: shell 42 | 43 | pip3 install circup 44 | 45 | With ``circup`` installed and your CircuitPython device connected use the 46 | following command to install: 47 | 48 | .. code-block:: shell 49 | 50 | circup install websockets 51 | 52 | Or the following command to update an existing version: 53 | 54 | .. code-block:: shell 55 | 56 | circup update 57 | 58 | Usage Example 59 | ============= 60 | 61 | .. todo:: Add a quick, simple example. It and other examples should live in the 62 | examples folder and be included in docs/examples.rst. 63 | 64 | Documentation 65 | ============= 66 | API documentation for this library can be found on `Read the Docs `_. 67 | 68 | For information on building library documentation, please check out 69 | `this guide `_. 70 | 71 | Contributing 72 | ============ 73 | 74 | Contributions are welcome! Please read our `Code of Conduct 75 | `_ 76 | before contributing to help this project stay welcoming. 77 | -------------------------------------------------------------------------------- /README.rst.license: -------------------------------------------------------------------------------- 1 | SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 3 | SPDX-License-Identifier: MIT 4 | -------------------------------------------------------------------------------- /examples/connect_circuitpython.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 2 | # SPDX-License-Identifier: MIT 3 | 4 | from secrets import secrets 5 | 6 | 7 | def connect_wifi(): 8 | try: 9 | import wifi 10 | 11 | native_wifi = True 12 | except: 13 | native_wifi = False 14 | 15 | if native_wifi: 16 | """ 17 | That's for native wifi. 18 | """ 19 | import socketpool 20 | import ssl 21 | 22 | print("CONNECT WIFI") 23 | wifi.radio.connect(secrets["ssid"], secrets["password"]) 24 | socket = socketpool.SocketPool(wifi.radio) 25 | ssl_context = ssl.create_default_context() 26 | return (socket, ssl_context, None) 27 | 28 | else: 29 | """ 30 | That's for an ESP32 wifi coprocessor (airlift breakouts and integrated). 31 | Change the pins to those that match your board. 32 | """ 33 | import board 34 | import busio 35 | from digitalio import DigitalInOut 36 | from adafruit_esp32spi import adafruit_esp32spi 37 | 38 | if hasattr(board, "ESP_CS"): 39 | # If you are using a board with pre-defined ESP32 Pins: 40 | esp32_cs = DigitalInOut(board.ESP_CS) 41 | esp32_ready = DigitalInOut(board.ESP_BUSY) 42 | esp32_reset = DigitalInOut(board.ESP_RESET) 43 | else: 44 | # If you have an externally connected ESP32: 45 | esp32_cs = DigitalInOut(board.D13) # CHANGE TO MATCH YOUR BOARD 46 | esp32_ready = DigitalInOut(board.D11) # CHANGE TO MATCH YOUR BOARD 47 | esp32_reset = DigitalInOut(board.D12) # CHANGE TO MATCH YOUR BOARD 48 | 49 | spi = busio.SPI(board.SCK, board.MOSI, board.MISO) 50 | esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) 51 | 52 | print("CONNECT WIFI") 53 | while not esp.is_connected: 54 | try: 55 | esp.connect_AP(secrets["ssid"], secrets["password"]) 56 | except RuntimeError as e: 57 | print("could not connect to AP, retrying: ", e) 58 | continue 59 | 60 | import adafruit_esp32spi.adafruit_esp32spi_socket as socket 61 | 62 | socket.set_interface(esp) 63 | return (socket, None, esp) 64 | 65 | return (None, None, None) 66 | -------------------------------------------------------------------------------- /examples/cpython_server/README.md: -------------------------------------------------------------------------------- 1 | # Cpython websocket client/server demo 2 | 3 | To use, first run the server demo on your computer: 4 | 5 | - use pip to install `asyncio` and `aioconsole` 6 | - run `server.py` with python 3 7 | 8 | And place the following files at the root of the Circuitpython drive. 9 | 10 | - `client.py` 11 | - `connect_circuitpython.py` 12 | - `status_led.py` 13 | - `uwebsockets` directory 14 | - `secrets.py` (filled in) 15 | 16 | Once the board connects to the server, the server script should prompt you for a color, which will then be displayed on the status LED of the board. 17 | 18 | Accepted formats include: 19 | 20 | - hexadecimal html color `0xFFFFFF` 21 | - decimal version of that `16777215` 22 | - list of decimal RGB values `(255,255,255)` or `[255,255,255]` 23 | - any of: `aqua` `black` `blue` `green` `magenta` `orange` `pink` `purple` `red` `turquoise` `white` `yellow` 24 | 25 | From the board side, you can press buttons, if there are buttons configured, look in the `client.py` script. The buttons pressed will be printed out on the server console. 26 | 27 | 28 | SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 29 | SPDX-License-Identifier: MIT 30 | -------------------------------------------------------------------------------- /examples/cpython_server/client.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 2 | # SPDX-License-Identifier: MIT 3 | """ 4 | Client/Server demo for websockets 5 | 6 | The client receives colors from the server and changes the status LED 7 | according to it. The client listens to buttons on the board and sends 8 | messages to the server just so they know. 9 | 10 | Requirements from the examples directory: 11 | - connect_circuitpython.py 12 | - status_led.py 13 | """ 14 | ## set debug to False for future imports (removes logging) 15 | import micropython 16 | 17 | micropython.opt_level(1) 18 | 19 | import json 20 | import os 21 | import sys 22 | import time 23 | import errno 24 | 25 | """ 26 | Setup button inputs, reasonnable defaults for some boards. 27 | """ 28 | import board 29 | from digitalio import DigitalInOut, Pull 30 | 31 | buttons = [] 32 | bname = os.uname().machine.lower() 33 | if bname.find("magtag"): 34 | buttons = [ 35 | (board.D11, Pull.UP, False, "right"), 36 | (board.D12, Pull.UP, False, "bottom"), 37 | (board.D14, Pull.UP, False, "top"), 38 | (board.D15, Pull.UP, False, "left"), 39 | ] 40 | elif bname.find("feathers2") >= 0: 41 | buttons = [ 42 | (board.D0, Pull.UP, "boot"), 43 | ] 44 | 45 | for i in range(len(buttons)): 46 | btn = DigitalInOut(buttons[i][0]) 47 | btn.switch_to_input(buttons[i][1]) 48 | buttons[i] = ( 49 | btn, 50 | buttons[i][2], 51 | buttons[i][3], 52 | ) 53 | 54 | """ 55 | Setup internet and websockets connection 56 | """ 57 | from secrets import secrets 58 | from status_led import status_led 59 | from connect_circuitpython import connect_wifi 60 | from uwebsockets import Session 61 | 62 | socket, ssl_context, iface = connect_wifi() 63 | wsession = Session(socket, ssl=ssl_context, iface=iface) 64 | 65 | url = "ws://{}:{}/index".format(secrets["test_server"], secrets.get("test_port", 5000)) 66 | 67 | """ 68 | Loop-de-loop 69 | """ 70 | print(f"Connecting to {url}") 71 | with wsession.client(url) as ws: 72 | was_pressed = [] 73 | print(">", "START") 74 | ws.send(json.dumps({"start": "START"})) 75 | ws.settimeout(0.1) 76 | while True: 77 | # recv from the server 78 | try: 79 | result = ws.recv() 80 | except OSError as err: 81 | if err.args[0] == errno.ETIMEDOUT: 82 | result = None 83 | else: 84 | raise 85 | 86 | # react to the server 87 | if result != None: 88 | try: 89 | data = json.loads(result) 90 | except: 91 | data = {} 92 | if "color" in data: 93 | try: 94 | color = data["color"] 95 | print(f"Color: {color}") 96 | status_led.fill(color) 97 | status_led.show() 98 | except: 99 | print(f"ERREUR de couleur {data['color']}") 100 | if "response" in data: 101 | print("<", data["response"]) 102 | 103 | # listen to the buttons 104 | list_buttons = [] 105 | message_buttons = {} 106 | for button in buttons: 107 | if button[0].value == button[1]: 108 | list_buttons.append(button[2]) 109 | if button[2] not in was_pressed: 110 | message_buttons[button[2]] = "pressed" 111 | elif button[2] in was_pressed: 112 | message_buttons[button[2]] = "released" 113 | if len(message_buttons) > 0: 114 | button_message = json.dumps({"buttons": message_buttons}) 115 | print(">", button_message) 116 | ws.send(button_message) 117 | was_pressed = list_buttons 118 | -------------------------------------------------------------------------------- /examples/cpython_server/echo.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 2 | # SPDX-License-Identifier: MIT 3 | 4 | import asyncio 5 | import logging 6 | import os 7 | import socket 8 | import websockets 9 | 10 | 11 | logging.basicConfig( 12 | format="%(message)s", 13 | level=logging.DEBUG, 14 | ) 15 | 16 | 17 | PORT = 5000 18 | hostname = socket.gethostname() 19 | HOST = socket.gethostbyname(hostname) 20 | 21 | print(f"Access: {HOST}:{PORT}") 22 | 23 | 24 | async def echo(websocket, path): 25 | try: 26 | async for message in websocket: 27 | print("Received and echoing message: " + message, flush=True) 28 | await websocket.send(message) 29 | except: 30 | print("Bye") 31 | 32 | 33 | start_server = websockets.serve(echo, "0.0.0.0", PORT) 34 | 35 | print("WebSockets echo server starting", flush=True) 36 | asyncio.get_event_loop().run_until_complete(start_server) 37 | 38 | print("WebSockets echo server running", flush=True) 39 | asyncio.get_event_loop().run_forever() 40 | -------------------------------------------------------------------------------- /examples/cpython_server/server.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 2 | # SPDX-License-Identifier: MIT 3 | 4 | from aioconsole import ainput 5 | import asyncio 6 | import json 7 | import re 8 | import time 9 | import sys 10 | import websockets 11 | import socket 12 | 13 | PORT = 5000 14 | 15 | hostname = socket.gethostname() 16 | HOST = socket.gethostbyname(hostname) 17 | 18 | color_names = { 19 | "aqua": 0x00FFFF, 20 | "black": 0x000000, 21 | "blue": 0x0000FF, 22 | "green": 0x008000, 23 | "magenta": 0xFF00FF, 24 | "orange": 0xFFA500, 25 | "pink": 0xF02080, 26 | "purple": 0x800080, 27 | "red": 0xFF0000, 28 | "turquoise": 0x40E0D0, 29 | "white": 0xFFFFFF, 30 | "yellow": 0xFFFF00, 31 | } 32 | 33 | COLOR_PROMPT = "Color >>> " 34 | 35 | 36 | async def consumer(message): 37 | try: 38 | data = json.loads(message) 39 | except: 40 | data = {} 41 | try: 42 | if "buttons" in data: 43 | for button, action in data["buttons"].items(): 44 | if action == "released": 45 | print("") 46 | print(f"Button clicked: {button}") 47 | print(COLOR_PROMPT, end="") 48 | sys.stdout.flush() 49 | except: 50 | print("Malformed buttons", data) 51 | 52 | 53 | async def producer(): 54 | color = await ainput(COLOR_PROMPT) 55 | color = color.strip() 56 | if color == "": 57 | return None 58 | elif re.match("^\d+$", color): 59 | color = int(color) 60 | elif re.match("^\((\d+),(\d+),(\d+)\)$", color): 61 | m = re.match("^\((\d+),(\d+),(\d+)\)$", color) 62 | color = (int(m.group(1)), int(m.group(2)), int(m.group(3))) 63 | elif re.match("^\[(\d+),(\d+),(\d+)\]$", color): 64 | m = re.match("^\[(\d+),(\d+),(\d+)\]$", color) 65 | color = (int(m.group(1)), int(m.group(2)), int(m.group(3))) 66 | elif re.match("^0x([a-fA-F0-9]+)$", color): 67 | m = re.match("^0x([a-fA-F0-9]+)$", color) 68 | color = int(m.group(1), 16) 69 | elif color.lower() in color_names: 70 | color = color_names[color.lower()] 71 | return json.dumps({"color": color}) 72 | 73 | 74 | async def consumer_handler(websocket, path): 75 | print(f"START consumer_handler {path}") 76 | async for message in websocket: 77 | # print("<", message) 78 | await consumer(message) 79 | 80 | 81 | async def producer_handler(websocket, path): 82 | print(f"START producer_handler {path}") 83 | while True: 84 | message = await producer() 85 | if message: 86 | # print(">", message) 87 | await websocket.send(message) 88 | 89 | 90 | async def handler(websocket, path): 91 | print("Connection from {}".format(websocket.remote_address)) 92 | consumer_task = asyncio.ensure_future(consumer_handler(websocket, path)) 93 | producer_task = asyncio.ensure_future(producer_handler(websocket, path)) 94 | done, pending = await asyncio.wait( 95 | [consumer_task, producer_task], 96 | return_when=asyncio.FIRST_COMPLETED, 97 | ) 98 | for task in pending: 99 | task.cancel() 100 | 101 | 102 | print(f"Starting {HOST}:{PORT}") 103 | start_server = websockets.serve(handler, "0.0.0.0", PORT) 104 | asyncio.get_event_loop().run_until_complete(start_server) 105 | asyncio.get_event_loop().run_forever() 106 | -------------------------------------------------------------------------------- /examples/obs_remote_demo/README.md: -------------------------------------------------------------------------------- 1 | # OBS Websockets demo 2 | 3 | This is a demo for a client for the OBS websockets plugin. It supports using either the native wifi module or an airlift breakout or feather wing. The default values set in the obs_pins.py file are set for the a Unexpected Maker Feather S2. 4 | 5 | Requires `adafruit_hashlib` in addition to uwebsockets requirements. 6 | To use, place all the files at the root of the Circuitpython drive, along with the `uwebsockets` directory, the `connect_circuitpython.py` file, and the filled in `secrets.py`. 7 | 8 | To test it on your board you can change the `obs_pins.py` file: 9 | 10 | - Change the pins for the buttons. 11 | - Initialize the pixels (NeoPixel or DotStar, size of the strip). 12 | 13 | The colors are setup the following way: 14 | 15 | - Define the colors in `obs_colors.py`. 16 | - Color patterns are used to represent a state. 17 | - Multiple states can be active at the same time (like recording and streaming). 18 | - The pixel(s) displays each state in turn with 1 second for each. 19 | - A color pattern does not need to change every pixel: 20 | - If it contains `None`, the matching pixel is unchanged. 21 | - This allows for assigning a different pixel for each state and not have it blink. 22 | - When we exit a state, we reset the pattern 23 | 24 | The `obs_pins.py` and `obs_colors.py` files contain comments showing ways to set it up using an 8-pixels RGBW neopixel stick. 25 | 26 | 27 | SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 28 | SPDX-License-Identifier: MIT 29 | -------------------------------------------------------------------------------- /examples/obs_remote_demo/code.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 2 | # SPDX-License-Identifier: MIT 3 | 4 | from digitalio import DigitalInOut, Pull 5 | import gamepad 6 | import gc 7 | import time 8 | from secrets import secrets 9 | 10 | from connect_circuitpython import connect_wifi 11 | import obs_pins as pins 12 | from obsws import obsws 13 | 14 | # OBS connection info 15 | url = secrets["obs_url"] 16 | password = secrets["obs_password"] 17 | 18 | # Reset all 19 | def reset(): 20 | import microcontroller 21 | 22 | microcontroller.reset() 23 | 24 | 25 | ################################################################ 26 | # neopixels and colors 27 | ################################################################ 28 | 29 | from obs_colors import * 30 | 31 | 32 | class MyPix: 33 | def __init__(self, pixel): 34 | self._pixel = pixel 35 | 36 | def __getattr__(self, attr): 37 | if (self._pixel, attr): 38 | return getattr(self._pixel, attr) 39 | 40 | def set_pattern(self, values): 41 | for pos, val in enumerate(values): 42 | if val != None: 43 | self._pixel[pos] = val 44 | self._pixel.show() 45 | 46 | 47 | # RGBW: bpp = 4 48 | pixels_strip = MyPix(pins.hardware_pixels) 49 | pixels_strip.brightness = BRIGHTNESS 50 | pixels_strip.fill(STARTUP) 51 | pixels_strip.show() 52 | 53 | # passage en mode erreur 54 | def dieInError(): 55 | print("DEAD IN ERROR") 56 | pixels_strip.fill((255, 0, 0)) 57 | pixels_strip.show() 58 | 59 | 60 | ################################################################ 61 | # blink the statuses 62 | # sets the neopixels colors to each status one after the other 63 | # is a status has a pixel as None, don't change it 64 | # so if multiple pixels, they be made to stay a single color 65 | # by using each for one state 66 | ################################################################ 67 | 68 | swirl_interval = const(2) 69 | 70 | 71 | class StatusColor(dict): 72 | def __init__(self): 73 | self.patterns = {} 74 | self.pos = 0 75 | self.t0 = time.monotonic() 76 | 77 | def append(self, key, pattern): 78 | self.patterns[key] = pattern 79 | self.show_all() 80 | 81 | def remove(self, key): 82 | if key in self.patterns: 83 | del self.patterns[key] 84 | self.show_all() 85 | 86 | def show_all(self): 87 | if len(self.patterns) > 0: 88 | colors = [OFF] * pixels_strip.n 89 | for status, color_pattern in self.patterns.items(): 90 | for index, color in enumerate(color_pattern): 91 | if color is not None: 92 | colors[index] = color 93 | pixels_strip.set_pattern(colors) 94 | else: 95 | pixels_strip.set_pattern(ALL_OFF) 96 | self.t0 = time.monotonic() 97 | 98 | def update_swirl(self): 99 | if len(self.patterns) == 0: 100 | pixels_strip.set_pattern(ALL_OFF) 101 | else: 102 | self.pos = (self.pos + 1) % len(self.patterns) 103 | current = sorted(self.patterns.keys())[self.pos] 104 | pixels_strip.set_pattern(self.patterns[current]) 105 | 106 | def cycle_call(self): 107 | t1 = time.monotonic() 108 | if t1 - self.t0 > swirl_interval: 109 | self.t0 = t1 110 | self.update_swirl() 111 | 112 | 113 | status_colors = StatusColor() 114 | 115 | ################################################################ 116 | # buttons ! who doesn't like buttons ? 117 | ################################################################ 118 | 119 | 120 | class Button: 121 | def __init__(self, pin, pull): 122 | self.pin = DigitalInOut(pin) 123 | if pull == "UP": 124 | self.pin.switch_to_input(pull=Pull.UP) 125 | self.pull = True 126 | elif pull == "DOWN": 127 | self.pin.switch_to_input(pull=Pull.DOWN) 128 | self.pull = False 129 | else: 130 | raise (ValueError("Button: pull must be UP or DOWN")) 131 | self.wasOn = False 132 | 133 | @property 134 | def on(self): 135 | return self.pin.value != self.pull 136 | 137 | @property 138 | def pressed(self): 139 | if self.on and not self.wasOn: 140 | self.wasOn = True 141 | return True 142 | elif not self.on and self.wasOn: 143 | self.wasOn = False 144 | return False 145 | 146 | 147 | button_twitch = Button(pins.button_twitch, "UP") 148 | button_record = Button(pins.button_record, "UP") 149 | button_buffer = Button(pins.button_buffer, "UP") 150 | 151 | ################################################################ 152 | # event manager to register and react to messages from OBS 153 | ################################################################ 154 | 155 | # Events System 156 | reactions = [] 157 | updates = [] 158 | 159 | 160 | class React: 161 | def __init__(self, messageId, action): 162 | self.id = str(messageId) 163 | self.action = action 164 | 165 | 166 | class Update: 167 | def __init__(self, updateType, action): 168 | self.type = updateType 169 | self.action = action 170 | 171 | 172 | ################################################################ 173 | # manage the buffer record button/feature 174 | ################################################################ 175 | 176 | 177 | def buffer_on(message=None): 178 | pass 179 | # status_colors["buffer"] = BUFFER 180 | 181 | 182 | def buffer_off(message=None): 183 | pass 184 | # del status_colors["buffer"] 185 | 186 | 187 | def buffer_start(): 188 | global obs 189 | id = obs.send({"request-type": "StartReplayBuffer"}) 190 | reactions.insert(0, React(id, buffer_on)) 191 | 192 | 193 | ################################################################ 194 | # manage the record and stream actions 195 | ################################################################ 196 | statusRecord = False 197 | statusStream = False 198 | 199 | 200 | def status_got(message=None): 201 | global statusStream, statusRecord 202 | statusStream = message["streaming"] 203 | statusRecord = message["recording"] 204 | if statusStream: 205 | status_colors.append("stream", STREAM) 206 | elif "stream" in status_colors: 207 | status_colors.remove("stream") 208 | if statusRecord: 209 | status_colors.append("record", RECORD) 210 | elif "record" in status_colors: 211 | status_colors.remove("record") 212 | 213 | 214 | def get_status(): 215 | global obs, reactions 216 | id = obs.send({"request-type": "GetStreamingStatus"}) 217 | print("GetStreamingStatus", id) 218 | reactions.insert(0, React(id, status_got)) 219 | 220 | 221 | ################################################################ 222 | # helper functions for the loop 223 | ################################################################ 224 | 225 | # ACT ON MESSAGE 226 | def act_on_message(rec): 227 | global reactions 228 | for re in reversed(reactions): 229 | if re.id == rec["message-id"]: 230 | re.action(rec) 231 | reactions.remove(re) 232 | 233 | 234 | # ACT ON UPDATE 235 | def act_on_update(rec): 236 | global statusStream, statusRecord, status_colors 237 | for up in updates: 238 | if up.type == rec["update-type"]: 239 | up.action(rec) 240 | if rec["update-type"] == "StreamStarted": 241 | statusStream = True 242 | status_colors.append("stream", STREAM) 243 | elif rec["update-type"] == "StreamStopped": 244 | statusStream = False 245 | status_colors.remove("stream") 246 | elif rec["update-type"] == "RecordingStarted": 247 | statusRecord = True 248 | status_colors.append("record", RECORD) 249 | elif rec["update-type"] == "RecordingStopped": 250 | statusRecord = False 251 | status_colors.remove("record") 252 | elif rec["update-type"] == "Exiting": 253 | # TODO: do something about the disconnection 254 | print("DECO -- DO SOMETHING") 255 | 256 | 257 | # ACT ON BUTTONS 258 | def act_on_buttons(): 259 | if button_twitch.pressed: 260 | print("Button Stream") 261 | if statusStream: 262 | id = obs.send({"request-type": "StopStreaming"}) 263 | else: 264 | id = obs.send({"request-type": "StartStreaming"}) 265 | 266 | if button_record.pressed: 267 | print("Button Record") 268 | if statusRecord: 269 | id = obs.send({"request-type": "StopRecording"}) 270 | else: 271 | id = obs.send({"request-type": "StartRecording"}) 272 | 273 | if button_buffer.pressed: 274 | print("Button Buffer") 275 | id = obs.send({"request-type": "SaveReplayBuffer"}) 276 | 277 | 278 | ################################################################ 279 | # 280 | # the "main" loop pat 281 | # 282 | ################################################################ 283 | 284 | # connect to OBS (OR DIE) 285 | obs = None 286 | 287 | 288 | def connect(): 289 | global obs 290 | try: 291 | obs = obsws(url, 4444, password) 292 | obs.connect() 293 | except Exception as Ex: 294 | dieInError() 295 | print("Exception") 296 | print(Ex) 297 | raise Ex 298 | 299 | 300 | # register buffer updates 301 | updates.append(Update("ReplayStopped", buffer_off)) 302 | updates.append(Update("ReplayStarted", buffer_on)) 303 | 304 | # the OBS loop 305 | def obs_reading_loop(): 306 | global obs 307 | try: 308 | while True: 309 | gc.collect() 310 | rec = obs.recv() 311 | if rec: 312 | print("@recv", rec) 313 | if "message-id" in rec: 314 | act_on_message(rec) 315 | if "update-type" in rec: 316 | act_on_update(rec) 317 | gc.collect() 318 | # print("MEM",gc.mem_free()) 319 | act_on_buttons() 320 | time.sleep(0.01) 321 | status_colors.cycle_call() 322 | # 323 | except Exception as Ex: 324 | dieInError() 325 | print("Exception") 326 | print(Ex) 327 | raise Ex 328 | # reset() 329 | 330 | 331 | # the global while loop for connection 332 | while True: 333 | try: 334 | connect() 335 | if obs != None: 336 | # start the buffer, get the status 337 | buffer_start() 338 | get_status() 339 | gc.collect() 340 | # do the loop 341 | obs_reading_loop() 342 | except Exception as Ex: 343 | obs = None 344 | dieInError() 345 | print("Exception") 346 | print(Ex) 347 | if Ex.args[0] == 104 or Ex.args[0] == 103: # ECONNRESET / ECONNABORTED 348 | print("CONNECTION FAILED - SLEEP AND RETRY") 349 | time.sleep(10) 350 | else: 351 | raise Ex 352 | 353 | print("FIN") 354 | dieInError() 355 | -------------------------------------------------------------------------------- /examples/obs_remote_demo/obs_colors.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 2 | # SPDX-License-Identifier: MIT 3 | 4 | # base colors 5 | STARTUP = (50, 50, 50) 6 | NEUTRAL = (0, 0, 0) 7 | OFF = (0, 0, 0) 8 | # color patterns 9 | STREAM = [(128, 0, 255)] 10 | RECORD = [(255, 0, 0)] 11 | ALL_OFF = [OFF] 12 | 13 | BRIGHTNESS = 0.1 14 | 15 | ### Example using a 8-pixels RGBW neopixel stick 16 | # WHITE = const(0) # 128 17 | # STARTUP = (10, 10, 10, 0) 18 | # NEUTRAL = (0, 0, 0, 1) 19 | # OFF = (0, 0, 0, 0) 20 | # STREAM = [None] * 6 + [(128, 0, 255, WHITE)] 21 | # RECORD = [None] + [(255, 0, 0, WHITE)] 22 | # ALL_OFF = [OFF] * 8 23 | -------------------------------------------------------------------------------- /examples/obs_remote_demo/obs_pins.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 2 | # SPDX-License-Identifier: MIT 3 | 4 | import board 5 | 6 | if hasattr(board, "NEOPIXEL"): 7 | # for a board that has a neopixel (eg: Feather NRF52840 Express) 8 | import neopixel 9 | 10 | hardware_pixels = neopixel.NeoPixel(board.NEOPIXEL, 1) 11 | elif hasattr(board, "APA102_SCK"): 12 | # for a board that has a APA102 (eg: UnexpectedMaker Feather S2) 13 | import adafruit_dotstar 14 | 15 | hardware_pixels = adafruit_dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1) 16 | else: 17 | raise OSError("No hardware pixel identified, please define some") 18 | 19 | ### Example using a 8-pixels RGBW neopixel stick 20 | # from neopixel import NeoPixel 21 | # hardware_pixels = NeoPixel(board.IO36, 8, bpp=4) 22 | 23 | if hasattr(board, "IO9"): 24 | # UnexpectedMaker Feather S2 25 | button_twitch = board.IO7 26 | button_record = board.IO1 27 | button_buffer = board.IO33 28 | elif hasattr(board, "D9"): 29 | # Feather NRF52840 Express 30 | button_twitch = board.D9 31 | button_record = board.D10 32 | button_buffer = board.D6 33 | -------------------------------------------------------------------------------- /examples/obs_remote_demo/obsws.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: Copyright (c) 2017 Guillaume "Elektordi" Genty 2 | # SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 3 | # SPDX-License-Identifier: MIT 4 | 5 | import adafruit_hashlib as hashlib 6 | import binascii 7 | import json 8 | from uwebsockets import Session 9 | from connect_circuitpython import connect_wifi 10 | 11 | 12 | class ConnectionFailure(BaseException): 13 | pass 14 | 15 | 16 | def base64(input): 17 | tmp = binascii.b2a_base64(input) 18 | return tmp[:-1] 19 | 20 | 21 | class obsws: 22 | def __init__(self, host=None, port=4444, password=""): 23 | self.id = 0 24 | # self.thread_recv = None 25 | # self.eventmanager = EventManager() 26 | # self.answers = {} 27 | self.host = host 28 | self.port = port 29 | self.password = password 30 | self.ws = None 31 | 32 | def connect(self): 33 | URL = "ws://{}:{}".format(self.host, self.port) 34 | socket, ssl_context, iface = connect_wifi() 35 | session = Session(socket, ssl=ssl_context, iface=iface) 36 | self.ws = session.client(URL) 37 | self._auth(self.password) 38 | 39 | def _auth(self, password): 40 | self.id += 1 41 | auth_payload = {"request-type": "GetAuthRequired", "message-id": str(self.id)} 42 | self.ws.send(json.dumps(auth_payload)) 43 | result = json.loads(self.ws.recv()) 44 | print("obsws result:", result) 45 | 46 | if result["authRequired"]: 47 | secret = base64( 48 | hashlib.sha256((password + result["salt"]).encode("utf-8")).digest() 49 | ) 50 | auth = base64( 51 | hashlib.sha256(secret + result["challenge"].encode("utf-8")).digest() 52 | ).decode("utf-8") 53 | 54 | self.id += 1 55 | auth_payload = { 56 | "request-type": "Authenticate", 57 | "message-id": str(self.id), 58 | "auth": auth, 59 | } 60 | self.ws.send(json.dumps(auth_payload)) 61 | result = json.loads(self.ws.recv()) 62 | if result["status"] != "ok": 63 | raise ConnectionFailure(result["error"]) 64 | 65 | def recv(self): 66 | self.ws.settimeout(0.1) 67 | try: 68 | rec = self.ws.recv() 69 | if rec.strip() != "": 70 | result = json.loads(rec) 71 | else: 72 | result = {} 73 | return result 74 | except OSError as err: 75 | # timeout 76 | if err.args[0] == 110 or err.args[0] == 116: 77 | return None 78 | else: 79 | raise err 80 | 81 | def send(self, payload): 82 | self.id += 1 83 | payload["message-id"] = str(self.id) 84 | self.ws.settimeout(None) 85 | self.ws.send(json.dumps(payload)) 86 | # NOTE: il envoie "replay starting" "replay started" first 87 | # donc il ne faut pas attendre de recv() un status ok 88 | # result = json.loads(self.ws.recv()) 89 | # return result 90 | return self.id 91 | -------------------------------------------------------------------------------- /examples/secrets.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 2 | # SPDX-License-Identifier: MIT 3 | 4 | # REMOVE THIS LINE and update your credentials to access your wifi 5 | raise (OSError("Please update your secrets.py file and remove this line")) 6 | 7 | secrets = { 8 | "ssid": "wifi networks", 9 | "password": "wifi password", 10 | # for tests 11 | "test_server": "192.168.1.1", 12 | "test_port": "5000", 13 | # for the OBS demo 14 | "obs_url": "192.168.1.1", 15 | "obs_password": "", 16 | } 17 | -------------------------------------------------------------------------------- /examples/status_led.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 2 | # SPDX-License-Identifier: MIT 3 | 4 | import board 5 | import os 6 | 7 | if hasattr(board, "NEOPIXEL"): 8 | """ 9 | For a board that has a neopixel (eg: Feather NRF52840 Express) 10 | Also use the four pixels on the MagTag 11 | """ 12 | NPIXELS = 1 13 | if os.uname().machine.lower().find("magtag"): 14 | NPIXELS = 4 15 | import neopixel 16 | 17 | status_led = neopixel.NeoPixel(board.NEOPIXEL, NPIXELS) 18 | elif hasattr(board, "APA102_SCK"): 19 | """ 20 | For a board that has a APA102 (eg: UnexpectedMaker Feather S2) 21 | """ 22 | NPIXELS = 1 23 | import adafruit_dotstar 24 | 25 | status_led = adafruit_dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, NPIXELS) 26 | else: 27 | raise OSError("No hardware pixel identified, please define some") 28 | 29 | if hasattr(board, "LDO2"): 30 | """ 31 | Enable LDO2 on the Feather S2 so we can use the status LED 32 | """ 33 | from digitalio import DigitalInOut, Direction 34 | 35 | ldo2 = DigitalInOut(board.LDO2) 36 | ldo2.switch_to_output() 37 | ldo2.value = True 38 | 39 | if hasattr(board, "NEOPIXEL_POWER"): 40 | """ 41 | On the MagTag, bring down NEOPIXEL_POWER 42 | """ 43 | from digitalio import DigitalInOut, Direction 44 | 45 | neopower = DigitalInOut(board.NEOPIXEL_POWER) 46 | neopower.switch_to_output() 47 | neopower.value = False 48 | -------------------------------------------------------------------------------- /examples/test_all_wsorg.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 2 | # SPDX-License-Identifier: MIT 3 | 4 | from connect_circuitpython import connect_wifi 5 | 6 | socket, ssl_context, iface = connect_wifi() 7 | 8 | from uwebsockets import Session 9 | 10 | wsession = Session(socket, ssl=ssl_context, iface=iface) 11 | 12 | message = "Repeat this" 13 | urls = [ 14 | "wss://echo.websocket.org", 15 | "ws://echo.websocket.org", 16 | ] 17 | 18 | for url in urls: 19 | print(f"TESTING ECHO {url}") 20 | with wsession.client(url) as ws: 21 | print(f"SENDING: <{message}>") 22 | ws.send(message) 23 | result = ws.recv() 24 | print(f"RECEIVED: <{result}>") 25 | if result == message: 26 | print("SUCCESS !!") 27 | else: 28 | print("OH NO IT WENT WRONG") 29 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2020 Diego Elio Pettenò 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | 5 | [tool.black] 6 | target-version = ['py35'] 7 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # SPDX-FileCopyrightText: Copyright (c) 2021 Neradoc 3 | # 4 | # SPDX-License-Identifier: MIT 5 | 6 | Adafruit-Blinka 7 | # adafruit-circuitpython-binascii 8 | adafruit-circuitpython-logging 9 | -------------------------------------------------------------------------------- /setup.py.disabled: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 3 | # 4 | # SPDX-License-Identifier: MIT 5 | 6 | """ 7 | This library is not deployed to PyPI. It is either a board-specific helper library, or 8 | does not make sense for use on or is incompatible with single board computers and Linux. 9 | """ 10 | -------------------------------------------------------------------------------- /websockets/__init__.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 2 | # 3 | # SPDX-License-Identifier: MIT 4 | """ 5 | `websockets` 6 | ================================================================================ 7 | 8 | A library to connect to a websockets server. 9 | Based on https://github.com/danni/uwebsockets 10 | 11 | * Author(s): Neradoc 12 | 13 | Implementation Notes 14 | -------------------- 15 | **Software and Dependencies:** 16 | * Adafruit CircuitPython firmware for the supported boards: 17 | https://circuitpython.org/downloads 18 | """ 19 | 20 | # imports 21 | 22 | __version__ = "0.0.0+auto.0" 23 | __repo__ = "https://github.com/Neradoc/CircuitPython_websockets.git" 24 | 25 | from .socket import UniversalSocket 26 | from .client import connect 27 | 28 | 29 | class Session: 30 | """ 31 | Session class, used to configure the websocket client. 32 | Similar construction as the adafruit_requests version. 33 | """ 34 | 35 | def __init__(self, socket_module, *, ssl=None, iface=None): 36 | self._usocket = UniversalSocket( 37 | socket_module, 38 | ssl=ssl, 39 | iface=iface, 40 | ) 41 | 42 | def client(self, url, extra_headers=None): 43 | """ 44 | Connect as a client to the given URL, and return the WebSocket object. 45 | Extra headers sent on connection can be added with the extra_headers dict. 46 | """ 47 | return connect(url, self._usocket, extra_headers) 48 | -------------------------------------------------------------------------------- /websockets/client.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: Copyright (c) 2019 Danielle Madeley 2 | # SPDX-FileCopyrightText: Copyright (c) 2021 Neradoc 3 | # 4 | # SPDX-License-Identifier: MIT 5 | """ 6 | `websockets.client` 7 | ================================================================================ 8 | 9 | * Author(s): Danielle Madeley, Neradoc 10 | """ 11 | 12 | import binascii 13 | import random 14 | import adafruit_logging as logging 15 | 16 | from .protocol import Websocket, urlparse 17 | 18 | LOGGER = logging.getLogger(__name__) 19 | 20 | 21 | class WebsocketClient(Websocket): 22 | """Web socket client wrapper class""" 23 | 24 | is_client = True 25 | 26 | 27 | def connect(uri, socket_module, extra_headers=None): 28 | """ 29 | Connect a websocket. 30 | The uri is a string with ws or wss url scheme. 31 | The socket module is a module that matches the C python socket module API. 32 | Extra headers sent on connection can be added with the extra_headers dict. 33 | """ 34 | 35 | uri = urlparse(uri) 36 | assert uri 37 | 38 | if __debug__: 39 | LOGGER.debug("open connection %s:%s", uri.hostname, uri.port) 40 | 41 | addr_info = socket_module.getaddrinfo( 42 | uri.hostname, uri.port, 0, socket_module.SOCK_STREAM 43 | )[0] 44 | sock = socket_module.socket(addr_info[0], addr_info[1]) 45 | connect_host = addr_info[-1][0] 46 | 47 | if uri.protocol == "wss": 48 | connect_host = uri.hostname 49 | connect_mode = socket_module.TLS_MODE 50 | https = "s" 51 | else: 52 | connect_mode = socket_module.TCP_MODE 53 | https = "" 54 | 55 | if __debug__: 56 | LOGGER.debug(str((connect_host, uri.port))) 57 | 58 | sock.connect((connect_host, uri.port), connect_mode) 59 | 60 | def send_header(header, *args): 61 | output = header.format(*args) 62 | if __debug__: 63 | LOGGER.debug(output) 64 | return sock.send(output.encode() + b"\r\n") 65 | 66 | # Sec-WebSocket-Key is 16 bytes of random base64 encoded 67 | key = binascii.b2a_base64(bytes(random.getrandbits(8) for _ in range(16)))[:-1] 68 | send_header("GET {} HTTP/1.1", uri.path or "/") 69 | send_header("Host: {}:{}", uri.hostname, uri.port) 70 | send_header("Connection: Upgrade") 71 | send_header("Upgrade: websocket") 72 | send_header("Sec-WebSocket-Key: {}", key.decode()) 73 | send_header("Sec-WebSocket-Version: 13") 74 | send_header("Origin: http{}://{}:{}", https, uri.hostname, uri.port) 75 | # additional headers 76 | if extra_headers: 77 | for extra_header_key in extra_headers: 78 | send_header("{}: {}", extra_header_key, extra_headers[extra_header_key]) 79 | send_header("") 80 | 81 | header = sock.readline() 82 | if not header.startswith(b"HTTP/1.1 101 "): 83 | raise ConnectionError(header) 84 | 85 | # We don't (currently) need these headers should we check the returned key? 86 | while header: 87 | if __debug__: 88 | LOGGER.debug(str(header)) 89 | header = sock.readline() 90 | 91 | return WebsocketClient(sock) 92 | -------------------------------------------------------------------------------- /websockets/protocol.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: Copyright (c) 2019 Danielle Madeley 2 | # SPDX-FileCopyrightText: Copyright (c) 2021 Neradoc 3 | # 4 | # SPDX-License-Identifier: MIT 5 | """ 6 | `websockets.protocol` 7 | ================================================================================ 8 | 9 | * Author(s): Danielle Madeley, Neradoc 10 | """ 11 | # pylint: disable=invalid-name 12 | 13 | import random 14 | import re 15 | import struct 16 | from collections import namedtuple 17 | from micropython import const 18 | import adafruit_logging as logging 19 | 20 | LOGGER = logging.getLogger(__name__) 21 | 22 | # Opcodes 23 | _OP_CONT = const(0x0) 24 | _OP_TEXT = const(0x1) 25 | _OP_BYTES = const(0x2) 26 | _OP_CLOSE = const(0x8) 27 | _OP_PING = const(0x9) 28 | _OP_PONG = const(0xA) 29 | 30 | # Close codes 31 | CLOSE_OK = const(1000) 32 | CLOSE_GOING_AWAY = const(1001) 33 | CLOSE_PROTOCOL_ERROR = const(1002) 34 | CLOSE_DATA_NOT_SUPPORTED = const(1003) 35 | CLOSE_BAD_DATA = const(1007) 36 | CLOSE_POLICY_VIOLATION = const(1008) 37 | CLOSE_TOO_BIG = const(1009) 38 | CLOSE_MISSING_EXTN = const(1010) 39 | CLOSE_BAD_CONDITION = const(1011) 40 | 41 | URL_RE = re.compile(r"(wss|ws)://([A-Za-z0-9-\.]+)(?:\:([0-9]+))?(/.+)?") 42 | URI = namedtuple("URI", ("protocol", "hostname", "port", "path")) 43 | 44 | 45 | class NoDataException(Exception): 46 | """No data received unexpectedly""" 47 | 48 | 49 | class ConnectionClosed(Exception): 50 | """Connection closed""" 51 | 52 | 53 | def urlparse(uri): 54 | """Parse ws:// URLs""" 55 | match = URL_RE.match(uri) 56 | if match: 57 | protocol = match.group(1) 58 | host = match.group(2) 59 | port = match.group(3) 60 | path = match.group(4) 61 | 62 | if protocol == "wss": 63 | if port is None: 64 | port = 443 65 | elif protocol == "ws": 66 | if port is None: 67 | port = 80 68 | else: 69 | raise ValueError("Scheme {} is invalid".format(protocol)) 70 | 71 | return URI(protocol, host, int(port), path) 72 | 73 | raise ValueError("URL invalid. Format: ws[s]://server:port/[path]") 74 | 75 | 76 | class Websocket: 77 | """ 78 | Basis of the Websocket protocol. 79 | """ 80 | 81 | is_client = False 82 | 83 | def __init__(self, sock): 84 | self.sock = sock 85 | self.open = True 86 | 87 | def __enter__(self): 88 | return self 89 | 90 | def __exit__(self, exc_type, exc, tb): 91 | self.close() 92 | 93 | def settimeout(self, timeout): 94 | """Set the timeout of the underlying socket""" 95 | self.sock.settimeout(timeout) 96 | 97 | def read_frame(self): # max_size=None 98 | """ 99 | Read a frame from the socket. 100 | See https://tools.ietf.org/html/rfc6455#section-5.2 for the details. 101 | """ 102 | 103 | # Frame header 104 | two_bytes = self.sock.read(2) 105 | 106 | if not two_bytes: 107 | raise NoDataException 108 | 109 | byte1, byte2 = struct.unpack("!BB", two_bytes) 110 | 111 | # Byte 1: FIN(1) _(1) _(1) _(1) OPCODE(4) 112 | fin = bool(byte1 & 0x80) 113 | opcode = byte1 & 0x0F 114 | 115 | # Byte 2: MASK(1) LENGTH(7) 116 | mask = bool(byte2 & (1 << 7)) 117 | length = byte2 & 0x7F 118 | 119 | if length == 126: # Magic number, length header is 2 bytes 120 | (length,) = struct.unpack("!H", self.sock.read(2)) 121 | elif length == 127: # Magic number, length header is 8 bytes 122 | (length,) = struct.unpack("!Q", self.sock.read(8)) 123 | 124 | if mask: # Mask is 4 bytes 125 | mask_bits = self.sock.read(4) 126 | 127 | try: 128 | data = self.sock.read(length) 129 | except MemoryError: 130 | # We can't receive this many bytes, close the socket 131 | if __debug__: 132 | LOGGER.debug("Frame of length %s too big. Closing", length) 133 | self.close(code=CLOSE_TOO_BIG) 134 | return True, _OP_CLOSE, None 135 | 136 | if mask: 137 | data = bytes(b ^ mask_bits[i % 4] for i, b in enumerate(data)) 138 | 139 | return fin, opcode, data 140 | 141 | def write_frame(self, opcode, data=b""): 142 | """ 143 | Write a frame to the socket. 144 | See https://tools.ietf.org/html/rfc6455#section-5.2 for the details. 145 | """ 146 | fin = True 147 | mask = self.is_client # messages sent by client are masked 148 | 149 | length = len(data) 150 | 151 | # Frame header 152 | # Byte 1: FIN(1) _(1) _(1) _(1) OPCODE(4) 153 | byte1 = 0x80 if fin else 0 154 | byte1 |= opcode 155 | 156 | # Byte 2: MASK(1) LENGTH(7) 157 | byte2 = 0x80 if mask else 0 158 | 159 | if length < 126: # 126 is magic value to use 2-byte length header 160 | byte2 |= length 161 | self.sock.send(struct.pack("!BB", byte1, byte2)) 162 | 163 | elif length < (1 << 16): # Length fits in 2-bytes 164 | byte2 |= 126 # Magic code 165 | self.sock.send(struct.pack("!BBH", byte1, byte2, length)) 166 | 167 | elif length < (1 << 64): 168 | byte2 |= 127 # Magic code 169 | self.sock.send(struct.pack("!BBQ", byte1, byte2, length)) 170 | 171 | else: 172 | raise ValueError() 173 | 174 | if mask: # Mask is 4 bytes 175 | mask_bits = struct.pack("!I", random.getrandbits(32)) 176 | self.sock.send(mask_bits) 177 | 178 | data = bytes(b ^ mask_bits[i % 4] for i, b in enumerate(data)) 179 | 180 | self.sock.send(data) 181 | 182 | def recv(self): 183 | """ 184 | Receive data from the websocket. 185 | 186 | This is slightly different from 'websockets' in that it doesn't 187 | fire off a routine to process frames and put the data in a queue. 188 | If you don't call recv() sufficiently often you won't process control 189 | frames. 190 | """ 191 | assert self.open 192 | 193 | while self.open: 194 | try: 195 | fin, opcode, data = self.read_frame() 196 | except NoDataException: 197 | return "" 198 | except ValueError: 199 | LOGGER.debug("Failed to read frame. Socket dead.") 200 | self._close() 201 | raise ConnectionClosed() # pylint: disable=raise-missing-from 202 | 203 | if not fin: 204 | raise NotImplementedError() 205 | 206 | if opcode == _OP_TEXT: 207 | return data.decode("utf-8") 208 | if opcode == _OP_BYTES: 209 | return data 210 | if opcode == _OP_CLOSE: 211 | self._close() 212 | raise ConnectionClosed(opcode) 213 | if opcode == _OP_PONG: 214 | # Ignore this frame, keep waiting for a data frame 215 | continue 216 | if opcode == _OP_PING: 217 | # We need to send a pong frame 218 | if __debug__: 219 | LOGGER.debug("Sending PONG") 220 | self.write_frame(_OP_PONG, data) 221 | # And then wait to receive 222 | continue 223 | if opcode == _OP_CONT: 224 | # This is a continuation of a previous frame 225 | raise NotImplementedError(opcode) 226 | # nothing 227 | raise ValueError(opcode) 228 | 229 | def send(self, buf): 230 | """Send data to the websocket.""" 231 | 232 | assert self.open 233 | 234 | if isinstance(buf, str): 235 | opcode = _OP_TEXT 236 | buf = buf.encode("utf-8") 237 | elif isinstance(buf, bytes): 238 | opcode = _OP_BYTES 239 | else: 240 | raise TypeError() 241 | 242 | self.write_frame(opcode, buf) 243 | 244 | def close(self, code=CLOSE_OK, reason=""): 245 | """Close the websocket.""" 246 | if not self.open: 247 | return 248 | 249 | buf = struct.pack("!H", code) + reason.encode("utf-8") 250 | 251 | self.write_frame(_OP_CLOSE, buf) 252 | self._close() 253 | 254 | def _close(self): 255 | if __debug__: 256 | LOGGER.debug("Connection closed") 257 | self.open = False 258 | self.sock.close() 259 | -------------------------------------------------------------------------------- /websockets/socket.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: Copyright (c) 2021 Neradoc 2 | # 3 | # SPDX-License-Identifier: MIT 4 | """ 5 | `websockets` 6 | ================================================================================ 7 | 8 | Universal socket for abstracting ESP32SPI/native wifi 9 | 10 | * Author(s): Neradoc 11 | """ 12 | 13 | import errno 14 | from micropython import const 15 | 16 | TCP_MODE = 1 17 | TLS_MODE = 2 18 | UDP_MODE = 4 19 | _BUFFER_SIZE = const(32) 20 | 21 | 22 | class UniversalSocket: 23 | """ 24 | Socket class for compatibility with native wifi and ESP32SPI wifi. 25 | """ 26 | 27 | TCP_MODE = TCP_MODE 28 | TLS_MODE = TLS_MODE 29 | UDP_MODE = UDP_MODE 30 | 31 | def __init__(self, socket, *, ssl=None, iface=None): 32 | self.socket_module = socket 33 | self._socket = None 34 | self.buffer = None 35 | self.ssl_context = ssl 36 | self.iface = iface 37 | self.buffer = bytearray(_BUFFER_SIZE) 38 | 39 | def readline(self): 40 | """ 41 | Implement readline() for native wifi using recv_into 42 | """ 43 | if hasattr(self._socket, "readline"): 44 | return self._socket.readline() 45 | 46 | data_string = b"" 47 | while True: 48 | num = self._socket.recv_into(self.buffer, 1) 49 | data_string += self.buffer[:num] 50 | if num == 0: 51 | return data_string 52 | if data_string[-2:] == b"\r\n": 53 | return data_string[:-2] 54 | 55 | def read(self, length): 56 | """ 57 | Implement read() for native wifi using recv_into 58 | """ 59 | if hasattr(self._socket, "read"): 60 | return self._socket.read(length) 61 | 62 | total = 0 63 | data_string = b"" 64 | while total < length: 65 | reste = length - total 66 | num = self._socket.recv_into(self.buffer, min(_BUFFER_SIZE, reste)) 67 | # 68 | if num == 0: 69 | # timeout 70 | raise OSError(errno.ETIMEDOUT) 71 | # 72 | data_string += self.buffer[:num] 73 | total = total + num 74 | return data_string 75 | 76 | # settimeout, send, close 77 | def __getattr__(self, attr): 78 | if self._socket and hasattr(self._socket, attr): 79 | # we are a socket 80 | return getattr(self._socket, attr) 81 | if hasattr(self.socket_module, attr): 82 | # we are also the socket module 83 | return getattr(self.socket_module, attr) 84 | if hasattr(self.iface, attr): 85 | # we could be the interface ? 86 | # TODO: remove that ? 87 | return getattr(self.iface, attr) 88 | raise AttributeError(f"'UniversalSocket' object has no attribute '{attr}'") 89 | 90 | def connect(self, host, mode=TCP_MODE): 91 | """ 92 | Connect to the host = (hostname,port) with the mode (TCP/TLS supported) 93 | Wrapping with the ssl_context happens here, not done by the outside code 94 | """ 95 | hostname, port = host 96 | if mode == self.TLS_MODE: 97 | if self.ssl_context: 98 | self._socket = self.ssl_context.wrap_socket( 99 | self._socket, server_hostname=hostname 100 | ) 101 | if port is None: 102 | port = 443 103 | else: 104 | if port is None: 105 | port = 80 106 | # 107 | if self.iface is not None: 108 | if mode == self.TLS_MODE: 109 | connect_mode = self.iface.TLS_MODE 110 | if mode == self.TCP_MODE: 111 | connect_mode = self.iface.TCP_MODE 112 | return self._socket.connect((hostname, port), connect_mode) 113 | # else: 114 | return self._socket.connect((hostname, port)) 115 | 116 | # TODO: remove (stick with getattr) 117 | def getaddrinfo(self, *args): 118 | """Get address info from the underlying socket module""" 119 | return self.socket_module.getaddrinfo(*args) 120 | 121 | def socket(self, *args): 122 | """ 123 | We are the socket, as well as the socket module 124 | """ 125 | self._socket = self.socket_module.socket(*args) 126 | return self 127 | --------------------------------------------------------------------------------