├── docs ├── _static │ ├── favicon.ico │ ├── favicon.ico.license │ └── custom.css ├── api.rst.license ├── index.rst.license ├── examples.rst.license ├── requirements.txt ├── api.rst ├── examples.rst ├── index.rst └── conf.py ├── README.rst.license ├── examples ├── pyportal_startup.wav ├── pyportal_startup.wav.license ├── pyportal_qrcode_generation.py ├── pyportal_simpletest.py └── pyportal_internet_json_fetching.py ├── optional_requirements.txt ├── .gitattributes ├── .github ├── workflows │ ├── build.yml │ ├── release_pypi.yml │ ├── release_gh.yml │ └── failure-help-text.yml └── PULL_REQUEST_TEMPLATE │ └── adafruit_circuitpython_pr.md ├── requirements.txt ├── .readthedocs.yaml ├── .pre-commit-config.yaml ├── LICENSES ├── MIT.txt ├── Unlicense.txt └── CC-BY-4.0.txt ├── LICENSE ├── pyproject.toml ├── .gitignore ├── README.rst ├── adafruit_pyportal ├── graphics.py ├── peripherals.py ├── network.py └── __init__.py ├── ruff.toml └── CODE_OF_CONDUCT.md /docs/_static/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_CircuitPython_PyPortal/HEAD/docs/_static/favicon.ico -------------------------------------------------------------------------------- /README.rst.license: -------------------------------------------------------------------------------- 1 | SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | 3 | SPDX-License-Identifier: MIT 4 | -------------------------------------------------------------------------------- /examples/pyportal_startup.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/adafruit/Adafruit_CircuitPython_PyPortal/HEAD/examples/pyportal_startup.wav -------------------------------------------------------------------------------- /docs/api.rst.license: -------------------------------------------------------------------------------- 1 | SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | 3 | SPDX-License-Identifier: MIT 4 | -------------------------------------------------------------------------------- /docs/index.rst.license: -------------------------------------------------------------------------------- 1 | SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | 3 | SPDX-License-Identifier: MIT 4 | -------------------------------------------------------------------------------- /docs/examples.rst.license: -------------------------------------------------------------------------------- 1 | SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | 3 | SPDX-License-Identifier: MIT 4 | -------------------------------------------------------------------------------- /optional_requirements.txt: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | -------------------------------------------------------------------------------- /docs/_static/favicon.ico.license: -------------------------------------------------------------------------------- 1 | SPDX-FileCopyrightText: 2018 Phillip Torrone for Adafruit Industries 2 | 3 | SPDX-License-Identifier: CC-BY-4.0 4 | -------------------------------------------------------------------------------- /examples/pyportal_startup.wav.license: -------------------------------------------------------------------------------- 1 | SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | 3 | SPDX-License-Identifier: MIT 4 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | 5 | * text eol=lf 6 | *.wav -text 7 | *.ico -text 8 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 Kattni Rembor for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | 5 | sphinx 6 | sphinxcontrib-jquery 7 | sphinx-rtd-theme 8 | -------------------------------------------------------------------------------- /docs/_static/custom.css: -------------------------------------------------------------------------------- 1 | /* SPDX-FileCopyrightText: 2025 Sam Blenny 2 | * SPDX-License-Identifier: MIT 3 | */ 4 | 5 | /* Monkey patch the rtd theme to prevent horizontal stacking of short items 6 | * see https://github.com/readthedocs/sphinx_rtd_theme/issues/1301 7 | */ 8 | .py.property{display: block !important;} 9 | -------------------------------------------------------------------------------- /.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: Run Build CI workflow 14 | uses: adafruit/workflows-circuitpython-libs/build@main 15 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2022 Alec Delaney, for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | 5 | Adafruit-Blinka-displayio 6 | Adafruit-Blinka 7 | adafruit-circuitpython-bitmap-font 8 | adafruit-circuitpython-busdevice 9 | adafruit-circuitpython-touchscreen 10 | adafruit-circuitpython-esp32spi 11 | adafruit-circuitpython-requests 12 | adafruit-circuitpython-neopixel 13 | adafruit-circuitpython-portalbase 14 | -------------------------------------------------------------------------------- /docs/api.rst: -------------------------------------------------------------------------------- 1 | 2 | .. If you created a package, create one automodule per module in the package. 3 | 4 | .. If your library file(s) are nested in a directory (e.g. /adafruit_foo/foo.py) 5 | .. use this format as the module name: "adafruit_foo.foo" 6 | 7 | .. automodule:: adafruit_pyportal 8 | :members: 9 | 10 | .. automodule:: adafruit_pyportal.graphics 11 | :members: 12 | 13 | .. automodule:: adafruit_pyportal.network 14 | :members: 15 | 16 | .. automodule:: adafruit_pyportal.peripherals 17 | :members: 18 | -------------------------------------------------------------------------------- /.readthedocs.yaml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | 5 | # Read the Docs configuration file 6 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details 7 | 8 | # Required 9 | version: 2 10 | 11 | sphinx: 12 | configuration: docs/conf.py 13 | 14 | build: 15 | os: ubuntu-lts-latest 16 | tools: 17 | python: "3" 18 | 19 | python: 20 | install: 21 | - requirements: docs/requirements.txt 22 | - requirements: requirements.txt 23 | -------------------------------------------------------------------------------- /.github/workflows/release_pypi.yml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | name: PyPI 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: Run PyPI Release CI workflow 16 | uses: adafruit/workflows-circuitpython-libs/release-pypi@main 17 | with: 18 | pypi-username: ${{ secrets.pypi_username }} 19 | pypi-password: ${{ secrets.pypi_password }} 20 | -------------------------------------------------------------------------------- /.github/workflows/release_gh.yml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | name: GitHub 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: Run GitHub Release CI workflow 16 | uses: adafruit/workflows-circuitpython-libs/release-gh@main 17 | with: 18 | github-token: ${{ secrets.GITHUB_TOKEN }} 19 | upload-url: ${{ github.event.release.upload_url }} 20 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2020 Diego Elio Pettenò 2 | # SPDX-FileCopyrightText: 2024 Justin Myers 3 | # 4 | # SPDX-License-Identifier: Unlicense 5 | 6 | repos: 7 | - repo: https://github.com/pre-commit/pre-commit-hooks 8 | rev: v4.5.0 9 | hooks: 10 | - id: check-yaml 11 | - id: end-of-file-fixer 12 | - id: trailing-whitespace 13 | - repo: https://github.com/astral-sh/ruff-pre-commit 14 | rev: v0.3.4 15 | hooks: 16 | - id: ruff-format 17 | - id: ruff 18 | args: ["--fix"] 19 | - repo: https://github.com/fsfe/reuse-tool 20 | rev: v3.0.1 21 | hooks: 22 | - id: reuse 23 | -------------------------------------------------------------------------------- /docs/examples.rst: -------------------------------------------------------------------------------- 1 | Simple test 2 | ------------ 3 | 4 | Ensure your device works with this simple test. 5 | 6 | .. literalinclude:: ../examples/pyportal_simpletest.py 7 | :caption: examples/pyportal_simpletest.py 8 | :linenos: 9 | 10 | Internet test 11 | ------------- 12 | 13 | Example to illustrate the device capability to get json data 14 | 15 | .. literalinclude:: ../examples/pyportal_internet_json_fetching.py 16 | :caption: examples/pyportal_internet_json_fetching.py 17 | :linenos: 18 | 19 | QR Test 20 | ------- 21 | 22 | This example shows a web address QR in the display 23 | 24 | .. literalinclude:: ../examples/pyportal_qrcode_generation.py 25 | :caption: examples/pyportal_qrcode_generation.py 26 | :linenos: 27 | -------------------------------------------------------------------------------- /examples/pyportal_qrcode_generation.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 Jose David M. 2 | # SPDX-License-Identifier: MIT 3 | 4 | """ 5 | This example shows a web address QR in the display 6 | """ 7 | 8 | import board 9 | 10 | from adafruit_pyportal.graphics import Graphics 11 | 12 | # Set display to show 13 | display = board.DISPLAY 14 | 15 | # Background Information 16 | base = Graphics(default_bg=0x990099, debug=True) 17 | 18 | # WebPage to show in the QR 19 | webpage = "http://www.adafruit.com" 20 | 21 | # QR size Information 22 | qr_size = 9 # Pixels 23 | scale = 3 24 | 25 | # Create a barcode 26 | base.qrcode( 27 | webpage, 28 | qr_size=scale, 29 | x=display.width // 2 - qr_size * scale, 30 | y=display.height // 2 - qr_size * scale, 31 | ) 32 | 33 | while True: 34 | pass 35 | -------------------------------------------------------------------------------- /examples/pyportal_simpletest.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | # NOTE: Make sure you've created your settings.toml file before running this example 6 | # https://learn.adafruit.com/adafruit-pyportal/create-your-settings-toml-file 7 | import board 8 | from displayio import CIRCUITPYTHON_TERMINAL 9 | 10 | from adafruit_pyportal import PyPortal 11 | 12 | # Set a data source URL 13 | TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html" 14 | 15 | # Create the PyPortal object 16 | pyportal = PyPortal(url=TEXT_URL, status_neopixel=board.NEOPIXEL) 17 | 18 | # Set display to show REPL 19 | board.DISPLAY.root_group = CIRCUITPYTHON_TERMINAL 20 | 21 | # Go get that data 22 | print("Fetching text from", TEXT_URL) 23 | data = pyportal.fetch() 24 | 25 | # Print out what we got 26 | print("-" * 40) 27 | print(data) 28 | print("-" * 40) 29 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2020 Melissa LeBlanc-Williams for Adafruit Industries 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/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 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | .. include:: ../README.rst 2 | 3 | Table of Contents 4 | ================= 5 | 6 | .. toctree:: 7 | :maxdepth: 4 8 | :hidden: 9 | 10 | self 11 | 12 | .. toctree:: 13 | :caption: Examples 14 | 15 | examples 16 | 17 | .. toctree:: 18 | :caption: API Reference 19 | :maxdepth: 3 20 | 21 | api 22 | 23 | .. toctree:: 24 | :caption: Tutorials 25 | 26 | Adafruit PyPortal Learning Guide 27 | 28 | .. toctree:: 29 | :caption: Related Products 30 | 31 | Adafruit PyPortal 32 | 33 | .. toctree:: 34 | :caption: Other Links 35 | 36 | Download from GitHub 37 | Download Library Bundle 38 | CircuitPython Reference Documentation 39 | CircuitPython Support Forum 40 | Discord Chat 41 | Adafruit Learning System 42 | Adafruit Blog 43 | Adafruit Store 44 | 45 | Indices and tables 46 | ================== 47 | 48 | * :ref:`genindex` 49 | * :ref:`modindex` 50 | * :ref:`search` 51 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2022 Alec Delaney for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | [build-system] 6 | requires = [ 7 | "setuptools", 8 | "wheel", 9 | "setuptools-scm", 10 | ] 11 | 12 | [project] 13 | name = "adafruit-circuitpython-pyportal" 14 | description = "CircuitPython driver for Adafruit PyPortal" 15 | version = "0.0.0+auto.0" 16 | readme = "README.rst" 17 | authors = [ 18 | {name = "Adafruit Industries", email = "circuitpython@adafruit.com"} 19 | ] 20 | urls = {Homepage = "https://github.com/adafruit/Adafruit_CircuitPython_REPLACE"} 21 | keywords = [ 22 | "adafruit", 23 | "pyportal", 24 | "display", 25 | "iot", 26 | "wifi", 27 | "hardware", 28 | "micropythoncircuitpython", 29 | ] 30 | license = {text = "MIT"} 31 | classifiers = [ 32 | "Intended Audience :: Developers", 33 | "Topic :: Software Development :: Libraries", 34 | "Topic :: Software Development :: Embedded Systems", 35 | "Topic :: System :: Hardware", 36 | "License :: OSI Approved :: MIT License", 37 | "Programming Language :: Python :: 3", 38 | ] 39 | dynamic = ["dependencies", "optional-dependencies"] 40 | 41 | [tool.setuptools] 42 | packages = ["adafruit_pyportal"] 43 | 44 | [tool.setuptools.dynamic] 45 | dependencies = {file = ["requirements.txt"]} 46 | optional-dependencies = {optional = {file = ["optional_requirements.txt"]}} 47 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Introduction 2 | ============ 3 | 4 | .. image:: https://readthedocs.org/projects/adafruit-circuitpython-pyportal/badge/?version=latest 5 | :target: https://docs.circuitpython.org/projects/pyportal/en/latest/ 6 | :alt: Documentation Status 7 | 8 | .. image:: https://raw.githubusercontent.com/adafruit/Adafruit_CircuitPython_Bundle/main/badges/adafruit_discord.svg 9 | :target: https://adafru.it/discord 10 | :alt: Discord 11 | 12 | .. image:: https://github.com/adafruit/Adafruit_CircuitPython_PyPortal/workflows/Build%20CI/badge.svg 13 | :target: https://github.com/adafruit/Adafruit_CircuitPython_PyPortal 14 | :alt: Build Status 15 | 16 | .. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json 17 | :target: https://github.com/astral-sh/ruff 18 | :alt: Code Style: Ruff 19 | 20 | CircuitPython driver for Adafruit PyPortal. 21 | 22 | 23 | Dependencies 24 | ============= 25 | This driver depends on: 26 | 27 | * `Adafruit CircuitPython `_ 28 | * `Bus Device `_ 29 | 30 | Please ensure all dependencies are available on the CircuitPython filesystem. 31 | This is easily achieved by downloading 32 | `the Adafruit library and driver bundle `_. 33 | 34 | Usage Example 35 | ============= 36 | 37 | See examples/pyportal_simpletest.py 38 | 39 | Documentation 40 | ============= 41 | 42 | API documentation for this library can be found on `Read the Docs `_. 43 | 44 | For information on building library documentation, please check out `this guide `_. 45 | 46 | Contributing 47 | ============ 48 | 49 | Contributions are welcome! Please read our `Code of Conduct 50 | `_ 51 | before contributing to help this project stay welcoming. 52 | -------------------------------------------------------------------------------- /adafruit_pyportal/graphics.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2020 Melissa LeBlanc-Williams, written for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | """ 5 | `adafruit_pyportal.graphics` 6 | ================================================================================ 7 | 8 | CircuitPython driver for Adafruit PyPortal. 9 | 10 | * Author(s): Limor Fried, Kevin J. Walters, Melissa LeBlanc-Williams 11 | 12 | Implementation Notes 13 | -------------------- 14 | 15 | **Hardware:** 16 | 17 | * `Adafruit PyPortal `_ 18 | 19 | **Software and Dependencies:** 20 | 21 | * Adafruit CircuitPython firmware for the supported boards: 22 | https://github.com/adafruit/circuitpython/releases 23 | 24 | """ 25 | 26 | import board 27 | from adafruit_portalbase.graphics import GraphicsBase 28 | 29 | __version__ = "0.0.0+auto.0" 30 | __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_PyPortal.git" 31 | 32 | 33 | class Graphics(GraphicsBase): 34 | """Graphics Helper Class for the PyPortal Library 35 | 36 | :param default_bg: The path to your default background image file or a hex color. 37 | Defaults to 0x000000. 38 | :param debug: Turn on debug print outs. Defaults to False. 39 | 40 | """ 41 | 42 | def __init__(self, *, default_bg=None, debug=False): 43 | super().__init__(board.DISPLAY, default_bg=default_bg, debug=debug) 44 | # Tracks whether we've hidden the background when we showed the QR code. 45 | self._qr_only = False 46 | 47 | def qrcode(self, qr_data, *, qr_size=1, x=0, y=0, hide_background=False): # noqa: PLR0913 Too many arguments in function definition 48 | """Display a QR code 49 | 50 | :param qr_data: The data for the QR code. 51 | :param int qr_size: The scale of the QR code. 52 | :param x: The x position of upper left corner of the QR code on the display. 53 | :param y: The y position of upper left corner of the QR code on the display. 54 | 55 | """ 56 | super().qrcode( 57 | qr_data, 58 | qr_size=qr_size, 59 | x=x, 60 | y=y, 61 | ) 62 | if hide_background: 63 | self.display.root_group = self._qr_group 64 | self._qr_only = hide_background 65 | 66 | def hide_QR(self): 67 | """Clear any QR codes that are currently on the screen""" 68 | 69 | if self._qr_only: 70 | self.display.root_group = self.root_group 71 | else: 72 | try: 73 | self._qr_group.pop() 74 | except (IndexError, AttributeError): # later test if empty 75 | pass 76 | -------------------------------------------------------------------------------- /examples/pyportal_internet_json_fetching.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries 2 | # SPDX-License-Identifier: MIT 3 | 4 | """ 5 | Example to illustrate the device capability to get json data 6 | """ 7 | 8 | # NOTE: Make sure you've created your settings.toml file before running this example 9 | # https://learn.adafruit.com/adafruit-pyportal/create-your-settings-toml-file 10 | from os import getenv 11 | 12 | import adafruit_connection_manager 13 | import adafruit_requests 14 | import board 15 | from adafruit_esp32spi import adafruit_esp32spi 16 | from digitalio import DigitalInOut 17 | 18 | # Get wifi details and more from a settings.toml file 19 | # tokens used by this Demo: CIRCUITPY_WIFI_SSID, CIRCUITPY_WIFI_PASSWORD 20 | ssid = getenv("CIRCUITPY_WIFI_SSID") 21 | password = getenv("CIRCUITPY_WIFI_PASSWORD") 22 | 23 | print("ESP32 SPI webclient test") 24 | 25 | TEXT_URL = "http://wifitest.adafruit.com/testwifi/index.html" 26 | JSON_URL = "http://wifitest.adafruit.com/testwifi/sample.json" 27 | 28 | 29 | # ESP32 Pins: 30 | esp32_cs = DigitalInOut(board.ESP_CS) 31 | esp32_ready = DigitalInOut(board.ESP_BUSY) 32 | esp32_reset = DigitalInOut(board.ESP_RESET) 33 | 34 | # SPI Configuration 35 | spi = board.SPI() 36 | esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset) 37 | pool = adafruit_connection_manager.get_radio_socketpool(esp) 38 | ssl_context = adafruit_connection_manager.get_radio_ssl_context(esp) 39 | requests = adafruit_requests.Session(pool, ssl_context) 40 | 41 | if esp.status == adafruit_esp32spi.WL_IDLE_STATUS: 42 | print("ESP32 found and in idle mode") 43 | print("Firmware vers.", esp.firmware_version) 44 | print("MAC addr:", ":".join("%02X" % byte for byte in esp.MAC_address)) 45 | 46 | for ap in esp.scan_networks(): 47 | print("\t%-23s RSSI: %d" % (ap.ssid, ap.rssi)) 48 | 49 | print("Connecting to AP...") 50 | while not esp.is_connected: 51 | try: 52 | esp.connect_AP(ssid, password) 53 | except RuntimeError as e: 54 | print("could not connect to AP, retrying: ", e) 55 | continue 56 | print("Connected to", esp.ap_info.ssid, "\tRSSI:", esp.ap_info.rssi) 57 | print("My IP address is", esp.ipv4_address) 58 | print("IP lookup adafruit.com: %s" % esp.pretty_ip(esp.get_host_by_name("adafruit.com"))) 59 | print("Ping google.com: %d ms" % esp.ping("google.com")) 60 | 61 | # esp._debug = True 62 | print("Fetching text from", TEXT_URL) 63 | r = requests.get(TEXT_URL) 64 | print("-" * 40) 65 | print(r.text) 66 | print("-" * 40) 67 | r.close() 68 | 69 | print() 70 | print("Fetching json from", JSON_URL) 71 | r = requests.get(JSON_URL) 72 | print("-" * 40) 73 | print(r.json()) 74 | print("-" * 40) 75 | r.close() 76 | print("Done!") 77 | -------------------------------------------------------------------------------- /ruff.toml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2024 Tim Cocks for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | target-version = "py38" 6 | line-length = 100 7 | 8 | [lint] 9 | select = ["I", "PL", "UP"] 10 | 11 | extend-select = [ 12 | "D419", # empty-docstring 13 | "E501", # line-too-long 14 | "W291", # trailing-whitespace 15 | "PLC0414", # useless-import-alias 16 | "PLC2401", # non-ascii-name 17 | "PLC2801", # unnecessary-dunder-call 18 | "PLC3002", # unnecessary-direct-lambda-call 19 | "PLE0101", # return-in-init 20 | "F706", # return-outside-function 21 | "F704", # yield-outside-function 22 | "PLE0116", # continue-in-finally 23 | "PLE0117", # nonlocal-without-binding 24 | "PLE0241", # duplicate-bases 25 | "PLE0302", # unexpected-special-method-signature 26 | "PLE0604", # invalid-all-object 27 | "PLE0605", # invalid-all-format 28 | "PLE0643", # potential-index-error 29 | "PLE0704", # misplaced-bare-raise 30 | "PLE1141", # dict-iter-missing-items 31 | "PLE1142", # await-outside-async 32 | "PLE1205", # logging-too-many-args 33 | "PLE1206", # logging-too-few-args 34 | "PLE1307", # bad-string-format-type 35 | "PLE1310", # bad-str-strip-call 36 | "PLE1507", # invalid-envvar-value 37 | "PLE2502", # bidirectional-unicode 38 | "PLE2510", # invalid-character-backspace 39 | "PLE2512", # invalid-character-sub 40 | "PLE2513", # invalid-character-esc 41 | "PLE2514", # invalid-character-nul 42 | "PLE2515", # invalid-character-zero-width-space 43 | "PLR0124", # comparison-with-itself 44 | "PLR0202", # no-classmethod-decorator 45 | "PLR0203", # no-staticmethod-decorator 46 | "UP004", # useless-object-inheritance 47 | "PLR0206", # property-with-parameters 48 | "PLR0904", # too-many-public-methods 49 | "PLR0911", # too-many-return-statements 50 | "PLR0912", # too-many-branches 51 | "PLR0913", # too-many-arguments 52 | "PLR0914", # too-many-locals 53 | "PLR0915", # too-many-statements 54 | "PLR0916", # too-many-boolean-expressions 55 | "PLR1702", # too-many-nested-blocks 56 | "PLR1704", # redefined-argument-from-local 57 | "PLR1711", # useless-return 58 | "C416", # unnecessary-comprehension 59 | "PLR1733", # unnecessary-dict-index-lookup 60 | "PLR1736", # unnecessary-list-index-lookup 61 | 62 | # ruff reports this rule is unstable 63 | #"PLR6301", # no-self-use 64 | 65 | "PLW0108", # unnecessary-lambda 66 | "PLW0120", # useless-else-on-loop 67 | "PLW0127", # self-assigning-variable 68 | "PLW0129", # assert-on-string-literal 69 | "B033", # duplicate-value 70 | "PLW0131", # named-expr-without-context 71 | "PLW0245", # super-without-brackets 72 | "PLW0406", # import-self 73 | "PLW0602", # global-variable-not-assigned 74 | "PLW0603", # global-statement 75 | "PLW0604", # global-at-module-level 76 | 77 | # fails on the try: import typing used by libraries 78 | #"F401", # unused-import 79 | 80 | "F841", # unused-variable 81 | "E722", # bare-except 82 | "PLW0711", # binary-op-exception 83 | "PLW1501", # bad-open-mode 84 | "PLW1508", # invalid-envvar-default 85 | "PLW1509", # subprocess-popen-preexec-fn 86 | "PLW2101", # useless-with-lock 87 | "PLW3301", # nested-min-max 88 | ] 89 | 90 | ignore = [ 91 | "PLR2004", # magic-value-comparison 92 | "UP030", # format literals 93 | "PLW1514", # unspecified-encoding 94 | 95 | ] 96 | 97 | [format] 98 | line-ending = "lf" 99 | -------------------------------------------------------------------------------- /adafruit_pyportal/peripherals.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # SPDX-FileCopyrightText: Copyright (c) 2020 Melissa LeBlanc-Williams for Adafruit Industries 3 | # 4 | # SPDX-License-Identifier: MIT 5 | """ 6 | `adafruit_pyportal.peripherals` 7 | ================================================================================ 8 | 9 | CircuitPython driver for Adafruit PyPortal. 10 | 11 | * Author(s): Limor Fried, Kevin J. Walters, Melissa LeBlanc-Williams 12 | 13 | Implementation Notes 14 | -------------------- 15 | 16 | **Hardware:** 17 | 18 | * `Adafruit PyPortal `_ 19 | 20 | **Software and Dependencies:** 21 | 22 | * Adafruit CircuitPython firmware for the supported boards: 23 | https://github.com/adafruit/circuitpython/releases 24 | 25 | """ 26 | 27 | import gc 28 | 29 | import audiocore 30 | import audioio 31 | import board 32 | import pwmio 33 | import storage 34 | from digitalio import DigitalInOut 35 | 36 | try: 37 | import sdcardio 38 | 39 | NATIVE_SD = True 40 | except ImportError: 41 | import adafruit_sdcard as sdcardio 42 | 43 | NATIVE_SD = False 44 | 45 | __version__ = "0.0.0+auto.0" 46 | __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_PyPortal.git" 47 | 48 | 49 | class Peripherals: 50 | """Peripherals Helper Class for the PyPortal Library""" 51 | 52 | def __init__(self, spi, display, display_group, debug=False): # noqa: PLR0912,PLR0913 Too many branches,Too many arguments in function definition 53 | # Speaker Enable 54 | self._speaker_enable = DigitalInOut(board.SPEAKER_ENABLE) 55 | self._speaker_enable.switch_to_output(False) 56 | 57 | self._display = display 58 | 59 | if hasattr(board, "AUDIO_OUT"): 60 | self.audio = audioio.AudioOut(board.AUDIO_OUT) 61 | elif hasattr(board, "SPEAKER"): 62 | self.audio = audioio.AudioOut(board.SPEAKER) 63 | else: 64 | raise AttributeError("Board does not have a builtin speaker!") 65 | self.wavfile = None 66 | 67 | if debug: 68 | print("Init SD Card") 69 | sd_cs = board.SD_CS 70 | if not NATIVE_SD: 71 | sd_cs = DigitalInOut(sd_cs) 72 | self._sdcard = None 73 | 74 | try: 75 | self._sdcard = sdcardio.SDCard(spi, sd_cs) 76 | vfs = storage.VfsFat(self._sdcard) 77 | storage.mount(vfs, "/sd") 78 | except OSError as error: 79 | print("No SD card found:", error) 80 | 81 | try: 82 | if hasattr(board, "TFT_BACKLIGHT"): 83 | self._backlight = pwmio.PWMOut(board.TFT_BACKLIGHT) 84 | elif hasattr(board, "TFT_LITE"): 85 | self._backlight = pwmio.PWMOut(board.TFT_LITE) 86 | except ValueError: 87 | self._backlight = None 88 | self.set_backlight(1.0) # turn on backlight 89 | 90 | if hasattr(board, "TOUCH_XL"): 91 | import adafruit_touchscreen 92 | 93 | if debug: 94 | print("Init touchscreen") 95 | 96 | self.touchscreen = adafruit_touchscreen.Touchscreen( 97 | board.TOUCH_XL, 98 | board.TOUCH_XR, 99 | board.TOUCH_YD, 100 | board.TOUCH_YU, 101 | calibration=((5200, 59000), (5800, 57000)), 102 | size=(board.DISPLAY.width, board.DISPLAY.height), 103 | ) 104 | 105 | self.set_backlight(1.0) # turn on backlight 106 | elif hasattr(board, "BUTTON_CLOCK"): 107 | from adafruit_cursorcontrol.cursorcontrol import Cursor 108 | from adafruit_cursorcontrol.cursorcontrol_cursormanager import CursorManager 109 | 110 | if debug: 111 | print("Init cursor") 112 | self.mouse_cursor = Cursor(board.DISPLAY, display_group=display_group, cursor_speed=8) 113 | self.mouse_cursor.hide() 114 | self.cursor = CursorManager(self.mouse_cursor) 115 | else: 116 | raise AttributeError("PyPortal module requires either a touchscreen or gamepad.") 117 | 118 | gc.collect() 119 | 120 | def set_backlight(self, val): 121 | """Adjust the TFT backlight. 122 | 123 | :param val: The backlight brightness. Use a value between ``0`` and ``1``, where ``0`` is 124 | off, and ``1`` is 100% brightness. 125 | 126 | """ 127 | val = max(0, min(1.0, val)) 128 | if self._backlight: 129 | self._backlight.duty_cycle = int(val * 65535) 130 | else: 131 | try: 132 | self._display.auto_brightness = False 133 | except AttributeError: 134 | pass 135 | self._display.brightness = val 136 | 137 | def play_file(self, file_name, wait_to_finish=True): 138 | """Play a wav file. 139 | 140 | :param str file_name: The name of the wav file to play on the speaker. 141 | :param bool wait_to_finish: flag to determine if this is a blocking call 142 | 143 | """ 144 | 145 | # can't use `with` because we need wavefile to remain open after return 146 | self.wavfile = open(file_name, "rb") 147 | wavedata = audiocore.WaveFile(self.wavfile) 148 | self._speaker_enable.value = True 149 | self.audio.play(wavedata) 150 | if not wait_to_finish: 151 | return 152 | while self.audio.playing: 153 | pass 154 | self.wavfile.close() 155 | self._speaker_enable.value = False 156 | 157 | def stop_play(self): 158 | """Stops playing a wav file.""" 159 | self.audio.stop() 160 | if self.wavfile is not None: 161 | self.wavfile.close() 162 | self._speaker_enable.value = False 163 | 164 | def sd_check(self): 165 | """Returns True if there is an SD card preset and False 166 | if there is no SD card. The _sdcard value is set in _init 167 | """ 168 | if self._sdcard: 169 | return True 170 | return False 171 | 172 | @property 173 | def speaker_disable(self): 174 | """ 175 | Enable or disable the speaker for power savings 176 | """ 177 | return not self._speaker_enable.value 178 | 179 | @speaker_disable.setter 180 | def speaker_disable(self, value): 181 | self._speaker_enable.value = not value 182 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | 7 | # Adafruit 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 | * Trolling, insulting/derogatory comments, and personal or political attacks 43 | * Promoting or spreading disinformation, lies, or conspiracy theories against 44 | a person, group, organisation, project, or community 45 | * Public or private harassment 46 | * Publishing others' private information, such as a physical or electronic 47 | address, without explicit permission 48 | * Other conduct which could reasonably be considered inappropriate 49 | 50 | The goal of the standards and moderation guidelines outlined here is to build 51 | and maintain a respectful community. We ask that you don’t just aim to be 52 | "technically unimpeachable", but rather try to be your best self. 53 | 54 | We value many things beyond technical expertise, including collaboration and 55 | supporting others within our community. Providing a positive experience for 56 | other community members can have a much more significant impact than simply 57 | providing the correct answer. 58 | 59 | ## Our Responsibilities 60 | 61 | Project leaders are responsible for clarifying the standards of acceptable 62 | behavior and are expected to take appropriate and fair corrective action in 63 | response to any instances of unacceptable behavior. 64 | 65 | Project leaders have the right and responsibility to remove, edit, or 66 | reject messages, comments, commits, code, issues, and other contributions 67 | that are not aligned to this Code of Conduct, or to ban temporarily or 68 | permanently any community member for other behaviors that they deem 69 | inappropriate, threatening, offensive, or harmful. 70 | 71 | ## Moderation 72 | 73 | Instances of behaviors that violate the Adafruit Community Code of Conduct 74 | may be reported by any member of the community. Community members are 75 | encouraged to report these situations, including situations they witness 76 | involving other community members. 77 | 78 | You may report in the following ways: 79 | 80 | In any situation, you may send an email to . 81 | 82 | On the Adafruit Discord, you may send an open message from any channel 83 | to all Community Moderators by tagging @community moderators. You may 84 | also send an open message from any channel, or a direct message to 85 | @kattni#1507, @tannewt#4653, @danh#1614, @cater#2442, 86 | @sommersoft#0222, @Mr. Certainly#0472 or @Andon#8175. 87 | 88 | Email and direct message reports will be kept confidential. 89 | 90 | In situations on Discord where the issue is particularly egregious, possibly 91 | illegal, requires immediate action, or violates the Discord terms of service, 92 | you should also report the message directly to Discord. 93 | 94 | These are the steps for upholding our community’s standards of conduct. 95 | 96 | 1. Any member of the community may report any situation that violates the 97 | Adafruit Community Code of Conduct. All reports will be reviewed and 98 | investigated. 99 | 2. If the behavior is an egregious violation, the community member who 100 | committed the violation may be banned immediately, without warning. 101 | 3. Otherwise, moderators will first respond to such behavior with a warning. 102 | 4. Moderators follow a soft "three strikes" policy - the community member may 103 | be given another chance, if they are receptive to the warning and change their 104 | behavior. 105 | 5. If the community member is unreceptive or unreasonable when warned by a 106 | moderator, or the warning goes unheeded, they may be banned for a first or 107 | second offense. Repeated offenses will result in the community member being 108 | banned. 109 | 110 | ## Scope 111 | 112 | This Code of Conduct and the enforcement policies listed above apply to all 113 | Adafruit Community venues. This includes but is not limited to any community 114 | spaces (both public and private), the entire Adafruit Discord server, and 115 | Adafruit GitHub repositories. Examples of Adafruit Community spaces include 116 | but are not limited to meet-ups, audio chats on the Adafruit Discord, or 117 | interaction at a conference. 118 | 119 | This Code of Conduct applies both within project spaces and in public spaces 120 | when an individual is representing the project or its community. As a community 121 | member, you are representing our community, and are expected to behave 122 | accordingly. 123 | 124 | ## Attribution 125 | 126 | This Code of Conduct is adapted from the [Contributor Covenant], 127 | version 1.4, available at 128 | , 129 | and the [Rust Code of Conduct](https://www.rust-lang.org/en-US/conduct.html). 130 | 131 | For other projects adopting the Adafruit Community Code of 132 | Conduct, please contact the maintainers of those projects for enforcement. 133 | If you wish to use this code of conduct for your own project, consider 134 | explicitly mentioning your moderation policy or making a copy with your 135 | own moderation policy so as to avoid confusion. 136 | 137 | [Contributor Covenant]: https://www.contributor-covenant.org 138 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | import datetime 6 | import os 7 | import sys 8 | 9 | sys.path.insert(0, os.path.abspath("..")) 10 | 11 | # -- General configuration ------------------------------------------------ 12 | 13 | # Add any Sphinx extension module names here, as strings. They can be 14 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 15 | # ones. 16 | extensions = [ 17 | "sphinx.ext.autodoc", 18 | "sphinxcontrib.jquery", 19 | "sphinx.ext.intersphinx", 20 | "sphinx.ext.napoleon", 21 | "sphinx.ext.todo", 22 | ] 23 | 24 | # TODO: Please Read! 25 | # Uncomment the below if you use native CircuitPython modules such as 26 | # digitalio, micropython and busio. List the modules you use. Without it, the 27 | # autodoc module docs will fail to generate with a warning. 28 | autodoc_mock_imports = [ 29 | "busio", 30 | "board", 31 | "digitalio", 32 | "rtc", 33 | "supervisor", 34 | "pulseio", 35 | "pwmio", 36 | "audioio", 37 | "audiocore", 38 | "microcontroller", 39 | "neopixel", 40 | "adafruit_sdcard", 41 | "storage", 42 | "sdcardio", 43 | "terminalio", 44 | "adafruit_io", 45 | "adafruit_cursorcontrol", 46 | "adafruit_esp32spi", 47 | "adafruit_requests", 48 | "adafruit_portalbase", 49 | ] 50 | 51 | 52 | intersphinx_mapping = { 53 | "python": ("https://docs.python.org/3", None), 54 | "BusDevice": ( 55 | "https://docs.circuitpython.org/projects/busdevice/en/latest/", 56 | None, 57 | ), 58 | "CircuitPython": ("https://docs.circuitpython.org/en/latest/", None), 59 | } 60 | 61 | # Add any paths that contain templates here, relative to this directory. 62 | templates_path = ["_templates"] 63 | 64 | source_suffix = ".rst" 65 | 66 | # The master toctree document. 67 | master_doc = "index" 68 | 69 | # General information about the project. 70 | project = "Adafruit PyPortal Library" 71 | creation_year = "2019" 72 | current_year = str(datetime.datetime.now().year) 73 | year_duration = ( 74 | current_year if current_year == creation_year else creation_year + " - " + current_year 75 | ) 76 | copyright = year_duration + " Limor Fried" 77 | author = "Limor Fried" 78 | 79 | # The version info for the project you're documenting, acts as replacement for 80 | # |version| and |release|, also used in various other places throughout the 81 | # built documents. 82 | # 83 | # The short X.Y version. 84 | version = "1.0" 85 | # The full version, including alpha/beta/rc tags. 86 | release = "1.0" 87 | 88 | # The language for content autogenerated by Sphinx. Refer to documentation 89 | # for a list of supported languages. 90 | # 91 | # This is also used if you do content translation via gettext catalogs. 92 | # Usually you set "language" from the command line for these cases. 93 | language = "en" 94 | 95 | # List of patterns, relative to source directory, that match files and 96 | # directories to ignore when looking for source files. 97 | # This patterns also effect to html_static_path and html_extra_path 98 | exclude_patterns = ["_build", "Thumbs.db", ".DS_Store", ".env", "CODE_OF_CONDUCT.md"] 99 | 100 | # The reST default role (used for this markup: `text`) to use for all 101 | # documents. 102 | # 103 | default_role = "any" 104 | 105 | # If true, '()' will be appended to :func: etc. cross-reference text. 106 | # 107 | add_function_parentheses = True 108 | 109 | # The name of the Pygments (syntax highlighting) style to use. 110 | pygments_style = "sphinx" 111 | 112 | # If true, `todo` and `todoList` produce output, else they produce nothing. 113 | todo_include_todos = False 114 | 115 | # If this is True, todo emits a warning for each TODO entries. The default is False. 116 | todo_emit_warnings = True 117 | 118 | napoleon_numpy_docstring = False 119 | 120 | # -- Options for HTML output ---------------------------------------------- 121 | 122 | # The theme to use for HTML and HTML Help pages. See the documentation for 123 | # a list of builtin themes. 124 | # 125 | import sphinx_rtd_theme 126 | 127 | html_theme = "sphinx_rtd_theme" 128 | 129 | # Add any paths that contain custom static files (such as style sheets) here, 130 | # relative to this directory. They are copied after the builtin static files, 131 | # so a file named "default.css" will overwrite the builtin "default.css". 132 | html_static_path = ["_static"] 133 | 134 | # Include extra css to work around rtd theme glitches 135 | html_css_files = ["custom.css"] 136 | 137 | # The name of an image file (relative to this directory) to use as a favicon of 138 | # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 139 | # pixels large. 140 | # 141 | html_favicon = "_static/favicon.ico" 142 | 143 | # Output file base name for HTML help builder. 144 | htmlhelp_basename = "AdafruitPyportalLibrarydoc" 145 | 146 | # -- Options for LaTeX output --------------------------------------------- 147 | 148 | latex_elements = { 149 | # The paper size ('letterpaper' or 'a4paper'). 150 | # 151 | # 'papersize': 'letterpaper', 152 | # The font size ('10pt', '11pt' or '12pt'). 153 | # 154 | # 'pointsize': '10pt', 155 | # Additional stuff for the LaTeX preamble. 156 | # 157 | # 'preamble': '', 158 | # Latex figure (float) alignment 159 | # 160 | # 'figure_align': 'htbp', 161 | } 162 | 163 | # Grouping the document tree into LaTeX files. List of tuples 164 | # (source start file, target name, title, 165 | # author, documentclass [howto, manual, or own class]). 166 | latex_documents = [ 167 | ( 168 | master_doc, 169 | "AdafruitPyPortalLibrary.tex", 170 | "AdafruitPyPortal Library Documentation", 171 | author, 172 | "manual", 173 | ), 174 | ] 175 | 176 | # -- Options for manual page output --------------------------------------- 177 | 178 | # One entry per manual page. List of tuples 179 | # (source start file, name, description, authors, manual section). 180 | man_pages = [ 181 | ( 182 | master_doc, 183 | "AdafruitPyPortallibrary", 184 | "Adafruit PyPortal Library Documentation", 185 | [author], 186 | 1, 187 | ) 188 | ] 189 | 190 | # -- Options for Texinfo output ------------------------------------------- 191 | 192 | # Grouping the document tree into Texinfo files. List of tuples 193 | # (source start file, target name, title, author, 194 | # dir menu entry, description, category) 195 | texinfo_documents = [ 196 | ( 197 | master_doc, 198 | "AdafruitPyPortalLibrary", 199 | "Adafruit PyPortal Library Documentation", 200 | author, 201 | "AdafruitPyPortalLibrary", 202 | "One line description of project.", 203 | "Miscellaneous", 204 | ), 205 | ] 206 | -------------------------------------------------------------------------------- /adafruit_pyportal/network.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2020 Melissa LeBlanc-Williams, written for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | """ 5 | `adafruit_pyportal.network` 6 | ================================================================================ 7 | 8 | CircuitPython driver for Adafruit PyPortal. 9 | 10 | * Author(s): Limor Fried, Kevin J. Walters, Melissa LeBlanc-Williams 11 | 12 | Implementation Notes 13 | -------------------- 14 | 15 | **Hardware:** 16 | 17 | * `Adafruit PyPortal `_ 18 | 19 | **Software and Dependencies:** 20 | 21 | * Adafruit CircuitPython firmware for the supported boards: 22 | https://github.com/adafruit/circuitpython/releases 23 | 24 | """ 25 | 26 | import gc 27 | 28 | import neopixel 29 | from adafruit_portalbase.network import ( 30 | CONTENT_JSON, 31 | CONTENT_TEXT, 32 | NetworkBase, 33 | ) 34 | from adafruit_portalbase.wifi_coprocessor import WiFi 35 | 36 | __version__ = "0.0.0+auto.0" 37 | __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_PyPortal.git" 38 | 39 | # you'll need to pass in an io username, width, height, format (bit depth), io key, and then url! 40 | IMAGE_CONVERTER_SERVICE = ( 41 | "https://io.adafruit.com/api/v2/%s/integrations/image-formatter?" 42 | "x-aio-key=%s&width=%d&height=%d&output=BMP%d&url=%s" 43 | ) 44 | 45 | 46 | class Network(NetworkBase): 47 | """Class representing the Adafruit PyPortal. 48 | 49 | :param status_neopixel: The pin for the status NeoPixel. Use ``board.NEOPIXEL`` for the on-board 50 | NeoPixel. Defaults to ``None``, not the status LED 51 | :param esp: A passed ESP32 object, Can be used in cases where the ESP32 chip needs to be used 52 | before calling the pyportal class. Defaults to ``None``. 53 | :param busio.SPI external_spi: A previously declared spi object. Defaults to ``None``. 54 | :param bool extract_values: If true, single-length fetched values are automatically extracted 55 | from lists and tuples. Defaults to ``True``. 56 | :param debug: Turn on debug print outs. Defaults to False. 57 | :param convert_image: Determine whether or not to use the AdafruitIO image converter service. 58 | Set as False if your image is already resized. Defaults to True. 59 | :param image_url_path: The HTTP traversal path for a background image to display. 60 | Defaults to ``None``. 61 | :param image_json_path: The JSON traversal path for a background image to display. Defaults to 62 | ``None``. 63 | :param image_resize: What size to resize the image we got from the json_path, make this a tuple 64 | of the width and height you want. Defaults to ``None``. 65 | :param image_position: The position of the image on the display as an (x, y) tuple. Defaults to 66 | ``None``. 67 | :param image_dim_json_path: The JSON traversal path for the original dimensions of image tuple. 68 | Used with fetch(). Defaults to ``None``. 69 | 70 | """ 71 | 72 | def __init__( # noqa: PLR0913 Too many arguments in function definition 73 | self, 74 | *, 75 | status_neopixel=None, 76 | esp=None, 77 | external_spi=None, 78 | extract_values=True, 79 | debug=False, 80 | convert_image=True, 81 | image_url_path=None, 82 | image_json_path=None, 83 | image_resize=None, 84 | image_position=None, 85 | image_dim_json_path=None, 86 | ): 87 | if status_neopixel: 88 | status_led = neopixel.NeoPixel(status_neopixel, 1, brightness=0.2) 89 | else: 90 | status_led = None 91 | wifi = WiFi(status_led=status_led, esp=esp, external_spi=external_spi) 92 | 93 | super().__init__( 94 | wifi, 95 | extract_values=extract_values, 96 | debug=debug, 97 | ) 98 | 99 | self._convert_image = convert_image 100 | self._image_json_path = image_json_path 101 | self._image_url_path = image_url_path 102 | self._image_resize = image_resize 103 | self._image_position = image_position 104 | self._image_dim_json_path = image_dim_json_path 105 | gc.collect() 106 | 107 | @property 108 | def ip_address(self): 109 | """Return the IP Address nicely formatted""" 110 | return self._wifi.esp.pretty_ip(self._wifi.esp.ip_address) 111 | 112 | def image_converter_url(self, image_url, width, height, color_depth=16): 113 | """Generate a converted image url from the url passed in, 114 | with the given width and height. ADAFRUIT_AIO_USERNAME and 115 | ADAFRUIT_AIO_KEY must be set in settings.toml.""" 116 | try: 117 | aio_username = self._get_setting("ADAFRUIT_AIO_USERNAME") 118 | aio_key = self._get_setting("ADAFRUIT_AIO_KEY") 119 | except KeyError as error: 120 | raise KeyError( 121 | "\n\nOur image converter service require a login/password to rate-limit. " 122 | "Please register for a free adafruit.io account and place the user/key in " 123 | "your settings.toml file under 'ADAFRUIT_AIO_USERNAME' and 'ADAFRUIT_AIO_KEY'" 124 | ) from error 125 | 126 | return IMAGE_CONVERTER_SERVICE % ( 127 | aio_username, 128 | aio_key, 129 | width, 130 | height, 131 | color_depth, 132 | image_url, 133 | ) 134 | 135 | def process_image(self, json_data, sd_card=False): # noqa: PLR0912 Too many branches 136 | """ 137 | Process image content 138 | 139 | :param json_data: The JSON data that we can pluck values from 140 | :param bool sd_card: Whether or not we have an SD card inserted 141 | 142 | """ 143 | filename = None 144 | position = None 145 | image_url = None 146 | 147 | if self._image_url_path: 148 | image_url = self._image_url_path 149 | 150 | if self._image_json_path: 151 | image_url = self.json_traverse(json_data, self._image_json_path) 152 | 153 | iwidth = 0 154 | iheight = 0 155 | if self._image_dim_json_path: 156 | iwidth = int(self.json_traverse(json_data, self._image_dim_json_path[0])) 157 | iheight = int(self.json_traverse(json_data, self._image_dim_json_path[1])) 158 | print("image dim:", iwidth, iheight) 159 | 160 | if image_url: 161 | print("original URL:", image_url) 162 | if self._convert_image: 163 | if iwidth < iheight: 164 | image_url = self.image_converter_url( 165 | image_url, 166 | int(self._image_resize[1] * self._image_resize[1] / self._image_resize[0]), 167 | self._image_resize[1], 168 | ) 169 | else: 170 | image_url = self.image_converter_url( 171 | image_url, self._image_resize[0], self._image_resize[1] 172 | ) 173 | 174 | print("convert URL:", image_url) 175 | # convert image to bitmap and cache 176 | # print("**not actually wgetting**") 177 | filename = "/cache.bmp" 178 | chunk_size = 4096 # default chunk size is 12K (for QSPI) 179 | if sd_card: 180 | filename = "/sd" + filename 181 | chunk_size = 512 # current bug in big SD writes -> stick to 1 block 182 | try: 183 | self.wget(image_url, filename, chunk_size=chunk_size) 184 | except OSError as error: 185 | raise OSError( 186 | """\n\nNo writable filesystem found for saving datastream. 187 | Insert an SD card or set internal filesystem to be unsafe by 188 | setting 'disable_concurrent_write_protection' in the mount options in boot.py""" 189 | ) from error 190 | except RuntimeError as error: 191 | raise RuntimeError("wget didn't write a complete file") from error 192 | if iwidth < iheight: 193 | pwidth = int(self._image_resize[1] * self._image_resize[1] / self._image_resize[0]) 194 | position = ( 195 | self._image_position[0] + int((self._image_resize[0] - pwidth) / 2), 196 | self._image_position[1], 197 | ) 198 | else: 199 | position = self._image_position 200 | 201 | image_url = None 202 | gc.collect() 203 | 204 | return filename, position 205 | -------------------------------------------------------------------------------- /adafruit_pyportal/__init__.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2020 Melissa LeBlanc-Williams, written for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | """ 5 | `adafruit_pyportal` 6 | ================================================================================ 7 | 8 | CircuitPython driver for Adafruit PyPortal. 9 | 10 | * Author(s): Limor Fried, Kevin J. Walters, Melissa LeBlanc-Williams 11 | 12 | Implementation Notes 13 | -------------------- 14 | 15 | **Hardware:** 16 | 17 | * `Adafruit PyPortal `_ 18 | 19 | **Software and Dependencies:** 20 | 21 | * Adafruit CircuitPython firmware for the supported boards: 22 | https://github.com/adafruit/circuitpython/releases 23 | 24 | """ 25 | 26 | import gc 27 | import os 28 | import time 29 | 30 | import board 31 | import supervisor 32 | import terminalio 33 | from adafruit_portalbase import PortalBase 34 | 35 | from adafruit_pyportal.graphics import Graphics 36 | from adafruit_pyportal.network import CONTENT_JSON, CONTENT_TEXT, Network 37 | from adafruit_pyportal.peripherals import Peripherals 38 | 39 | __version__ = "0.0.0+auto.0" 40 | __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_PyPortal.git" 41 | 42 | 43 | class PyPortal(PortalBase): 44 | """Class representing the Adafruit PyPortal. 45 | 46 | :param url: The URL of your data source. Defaults to ``None``. 47 | :param headers: The headers for authentication, typically used by Azure API's. 48 | :param json_path: The list of json traversal to get data out of. Can be list of lists for 49 | multiple data points. Defaults to ``None`` to not use json. 50 | :param regexp_path: The list of regexp strings to get data out (use a single regexp group). Can 51 | be list of regexps for multiple data points. Defaults to ``None`` to not 52 | use regexp. 53 | :param convert_image: Determine whether or not to use the AdafruitIO image converter service. 54 | Set as False if your image is already resized. Defaults to True. 55 | :param default_bg: The path to your default background image file or a hex color. 56 | Defaults to 0x000000. 57 | :param status_neopixel: The pin for the status NeoPixel. Use ``board.NEOPIXEL`` for the on-board 58 | NeoPixel. Defaults to ``None``, not the status LED 59 | :param str text_font: The path to your font file for your data text display. 60 | :param text_position: The position of your extracted text on the display in an (x, y) tuple. 61 | Can be a list of tuples for when there's a list of json_paths, for example 62 | :param text_color: The color of the text, in 0xRRGGBB format. Can be a list of colors for when 63 | there's multiple texts. Defaults to ``None``. 64 | :param text_wrap: Whether or not to wrap text (for long text data chunks). Defaults to 65 | ``False``, no wrapping. 66 | :param text_maxlen: The max length of the text for text wrapping. Defaults to 0. 67 | :param text_transform: A function that will be called on the text before display 68 | :param int text_scale: The factor to scale the default size of the text by 69 | :param json_transform: A function or a list of functions to call with the parsed JSON. 70 | Changes and additions are permitted for the ``dict`` object. 71 | :param image_json_path: The JSON traversal path for a background image to display. Defaults to 72 | ``None``. 73 | :param image_resize: What size to resize the image we got from the json_path, make this a tuple 74 | of the width and height you want. Defaults to ``None``. 75 | :param image_position: The position of the image on the display as an (x, y) tuple. Defaults to 76 | ``None``. 77 | :param image_dim_json_path: The JSON traversal path for the original dimensions of image tuple. 78 | Used with fetch(). Defaults to ``None``. 79 | :param success_callback: A function we'll call if you like, when we fetch data successfully. 80 | Defaults to ``None``. 81 | :param str caption_text: The text of your caption, a fixed text not changed by the data we get. 82 | Defaults to ``None``. 83 | :param str caption_font: The path to the font file for your caption. Defaults to ``None``. 84 | :param caption_position: The position of your caption on the display as an (x, y) tuple. 85 | Defaults to ``None``. 86 | :param caption_color: The color of your caption. Must be a hex value, e.g. ``0x808000``. 87 | :param image_url_path: The HTTP traversal path for a background image to display. 88 | Defaults to ``None``. 89 | :param esp: A passed ESP32 object, Can be used in cases where the ESP32 chip needs to be used 90 | before calling the pyportal class. Defaults to ``None``. 91 | :param busio.SPI external_spi: A previously declared spi object. Defaults to ``None``. 92 | :param debug: Turn on debug print outs. Defaults to False. 93 | 94 | """ 95 | 96 | def __init__( # noqa: PLR0912,PLR0913,PLR0915 Too many branches,Too many arguments in function definition,Too many statements 97 | self, 98 | *, 99 | url=None, 100 | headers=None, 101 | json_path=None, 102 | regexp_path=None, 103 | convert_image=True, 104 | default_bg=0x000000, 105 | status_neopixel=None, 106 | text_font=terminalio.FONT, 107 | text_position=None, 108 | text_color=0x808080, 109 | text_wrap=False, 110 | text_maxlen=0, 111 | text_transform=None, 112 | text_scale=1, 113 | json_transform=None, 114 | image_json_path=None, 115 | image_resize=None, 116 | image_position=None, 117 | image_dim_json_path=None, 118 | caption_text=None, 119 | caption_font=None, 120 | caption_position=None, 121 | caption_color=0x808080, 122 | image_url_path=None, 123 | success_callback=None, 124 | esp=None, 125 | external_spi=None, 126 | debug=False, 127 | ): 128 | graphics = Graphics( 129 | default_bg=default_bg, 130 | debug=debug, 131 | ) 132 | 133 | self._default_bg = default_bg 134 | 135 | if external_spi: # If SPI Object Passed 136 | spi = external_spi 137 | else: # Else: Make ESP32 connection 138 | spi = board.SPI() 139 | 140 | if image_json_path or image_url_path: 141 | if debug: 142 | print("Init image path") 143 | if not image_position: 144 | image_position = (0, 0) # default to top corner 145 | if not image_resize: 146 | image_resize = ( 147 | self.display.width, 148 | self.display.height, 149 | ) # default to full screen 150 | 151 | network = Network( 152 | status_neopixel=status_neopixel, 153 | esp=esp, 154 | external_spi=spi, 155 | extract_values=False, 156 | convert_image=convert_image, 157 | image_url_path=image_url_path, 158 | image_json_path=image_json_path, 159 | image_resize=image_resize, 160 | image_position=image_position, 161 | image_dim_json_path=image_dim_json_path, 162 | debug=debug, 163 | ) 164 | 165 | self.url = url 166 | 167 | super().__init__( 168 | network, 169 | graphics, 170 | url=url, 171 | headers=headers, 172 | json_path=json_path, 173 | regexp_path=regexp_path, 174 | json_transform=json_transform, 175 | success_callback=success_callback, 176 | debug=debug, 177 | ) 178 | 179 | # Convenience Shortcuts for compatibility 180 | self.peripherals = Peripherals( 181 | spi, display=self.display, display_group=self.root_group, debug=debug 182 | ) 183 | self.set_backlight = self.peripherals.set_backlight 184 | self.sd_check = self.peripherals.sd_check 185 | self.play_file = self.peripherals.play_file 186 | self.stop_play = self.peripherals.stop_play 187 | 188 | self.image_converter_url = self.network.image_converter_url 189 | self.wget = self.network.wget 190 | self.show_QR = self.graphics.qrcode 191 | self.hide_QR = self.graphics.hide_QR 192 | 193 | if hasattr(self.peripherals, "touchscreen"): 194 | self.touchscreen = self.peripherals.touchscreen 195 | if hasattr(self.peripherals, "mouse_cursor"): 196 | self.mouse_cursor = self.peripherals.mouse_cursor 197 | if hasattr(self.peripherals, "cursor"): 198 | self.cursor = self.peripherals.cursor 199 | 200 | # show thank you and bootup file if available 201 | for bootscreen in ("/thankyou.bmp", "/pyportal_startup.bmp"): 202 | try: 203 | os.stat(bootscreen) 204 | for i in range(100, -1, -1): # dim down 205 | self.set_backlight(i / 100) 206 | time.sleep(0.005) 207 | self.set_background(bootscreen) 208 | try: 209 | self.display.refresh(target_frames_per_second=60) 210 | except AttributeError: 211 | self.display.wait_for_frame() 212 | for i in range(100): # dim up 213 | self.set_backlight(i / 100) 214 | time.sleep(0.005) 215 | time.sleep(2) 216 | except OSError: 217 | pass # they removed it, skip! 218 | 219 | try: 220 | self.peripherals.play_file("pyportal_startup.wav") 221 | except OSError: 222 | pass # they deleted the file, no biggie! 223 | 224 | if default_bg is not None: 225 | self.graphics.set_background(default_bg) 226 | 227 | if self._debug: 228 | print("Init caption") 229 | if caption_font: 230 | self._caption_font = self._load_font(caption_font) 231 | self.set_caption(caption_text, caption_position, caption_color) 232 | 233 | if text_font: 234 | if text_position is not None and isinstance(text_position[0], (list, tuple)): 235 | num = len(text_position) 236 | if not text_wrap: 237 | text_wrap = [0] * num 238 | if not text_maxlen: 239 | text_maxlen = [0] * num 240 | if not text_transform: 241 | text_transform = [None] * num 242 | if not isinstance(text_scale, (list, tuple)): 243 | text_scale = [text_scale] * num 244 | else: 245 | num = 1 246 | text_position = (text_position,) 247 | text_color = (text_color,) 248 | text_wrap = (text_wrap,) 249 | text_maxlen = (text_maxlen,) 250 | text_transform = (text_transform,) 251 | text_scale = (text_scale,) 252 | for i in range(num): 253 | self.add_text( 254 | text_position=text_position[i], 255 | text_font=text_font, 256 | text_color=text_color[i], 257 | text_wrap=text_wrap[i], 258 | text_maxlen=text_maxlen[i], 259 | text_transform=text_transform[i], 260 | text_scale=text_scale[i], 261 | ) 262 | else: 263 | self._text_font = None 264 | self._text = None 265 | 266 | gc.collect() 267 | 268 | def set_caption(self, caption_text, caption_position, caption_color): 269 | """A caption. Requires setting ``caption_font`` in init! 270 | 271 | :param caption_text: The text of the caption. 272 | :param caption_position: The position of the caption text. 273 | :param caption_color: The color of your caption text. Must be a hex value, e.g. 274 | ``0x808000``. 275 | """ 276 | if self._debug: 277 | print("Setting caption to", caption_text) 278 | 279 | if (not caption_text) or (not self._caption_font) or (not caption_position): 280 | return # nothing to do! 281 | 282 | index = self.add_text( 283 | text_position=caption_position, 284 | text_font=self._caption_font, 285 | text_color=caption_color, 286 | is_data=False, 287 | ) 288 | self.set_text(caption_text, index) 289 | 290 | def fetch(self, refresh_url=None, timeout=10, force_content_type=None): # noqa: PLR0912 Too many branches 291 | """Fetch data from the url we initialized with, perfom any parsing, 292 | and display text or graphics. This function does pretty much everything 293 | Optionally update the URL 294 | """ 295 | 296 | if refresh_url: 297 | self.url = refresh_url 298 | 299 | response = self.network.fetch(self.url, headers=self._headers, timeout=timeout) 300 | 301 | json_out = None 302 | if not force_content_type: 303 | content_type = self.network.check_response(response) 304 | else: 305 | content_type = force_content_type 306 | json_path = self._json_path 307 | 308 | if content_type == CONTENT_JSON: 309 | if json_path is not None: 310 | # Drill down to the json path and set json_out as that node 311 | if isinstance(json_path, (list, tuple)) and ( 312 | not json_path or not isinstance(json_path[0], (list, tuple)) 313 | ): 314 | json_path = (json_path,) 315 | try: 316 | gc.collect() 317 | json_out = response.json() 318 | if self._debug: 319 | print(json_out) 320 | gc.collect() 321 | except ValueError: # failed to parse? 322 | print("Couldn't parse json: ", response.text) 323 | raise 324 | except MemoryError: 325 | supervisor.reload() 326 | 327 | try: 328 | filename, position = self.network.process_image(json_out, self.peripherals.sd_check()) 329 | if filename and position is not None: 330 | self.graphics.set_background(filename, position) 331 | except ValueError as error: 332 | print("Error displaying cached image. " + error.args[0]) 333 | if self._default_bg is not None: 334 | self.graphics.set_background(self._default_bg) 335 | except KeyError as error: 336 | print("Error finding image data. '" + error.args[0] + "' not found.") 337 | self.set_background(self._default_bg) 338 | 339 | if content_type == CONTENT_JSON: 340 | values = self.network.process_json(json_out, json_path) 341 | elif content_type == CONTENT_TEXT: 342 | values = self.network.process_text(response.text, self._regexp_path) 343 | 344 | # if we have a callback registered, call it now 345 | if self._success_callback: 346 | self._success_callback(values) 347 | 348 | self._fill_text_labels(values) 349 | # Clean up 350 | json_out = None 351 | response = None 352 | gc.collect() 353 | 354 | if len(values) == 1: 355 | values = values[0] 356 | 357 | return values 358 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------