├── pyproject.toml ├── README.rst.license ├── examples ├── server │ ├── README.md.license │ ├── static │ │ ├── index.html │ │ └── led_color_picker_example.js │ ├── README.md │ └── esp32s2_wsgiserver.py ├── wsgiserver_simpletest.py └── wsgiserver_displaytest.py ├── requirements.txt ├── .gitignore ├── setup.py.disabled ├── test └── send_empty_line.py ├── .github └── workflows │ ├── failure-help-text.yml │ ├── build.yml │ └── release.yml ├── LICENSE ├── LICENSES ├── MIT.txt ├── Unlicense.txt └── CC-BY-4.0.txt ├── .pre-commit-config.yaml ├── README.rst ├── CODE_OF_CONDUCT.md ├── wsgiserver.py └── .pylintrc /pyproject.toml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2020 Diego Elio Pettenò 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | 5 | [tool.black] 6 | target-version = ['py35'] 7 | -------------------------------------------------------------------------------- /README.rst.license: -------------------------------------------------------------------------------- 1 | SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 3 | SPDX-License-Identifier: MIT 4 | -------------------------------------------------------------------------------- /examples/server/README.md.license: -------------------------------------------------------------------------------- 1 | SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 3 | SPDX-License-Identifier: MIT 4 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 3 | # 4 | # SPDX-License-Identifier: MIT 5 | 6 | Adafruit-Blinka 7 | black 8 | pylint 9 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | 5 | *.mpy 6 | .idea 7 | __pycache__ 8 | _build 9 | *.pyc 10 | .env 11 | .python-version 12 | build*/ 13 | bundles 14 | *.DS_Store 15 | .eggs 16 | dist 17 | **/*.egg-info 18 | .vscode 19 | -------------------------------------------------------------------------------- /setup.py.disabled: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 3 | # 4 | # SPDX-License-Identifier: MIT 5 | 6 | """ 7 | This library is not deployed to PyPI. It is either a board-specific helper library, or 8 | does not make sense for use on or is incompatible with single board computers and Linux. 9 | """ 10 | -------------------------------------------------------------------------------- /examples/server/static/index.html: -------------------------------------------------------------------------------- 1 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 |

LED color picker demo!

14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /test/send_empty_line.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 2 | # SPDX-License-Identifier: MIT 3 | # 4 | # pylint: skip-file 5 | """ 6 | Test sending an empty line to a server (issue #5) 7 | """ 8 | import click 9 | import socket 10 | 11 | 12 | @click.command() 13 | @click.argument( 14 | "address", 15 | required=True, 16 | ) 17 | def main(address): 18 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 19 | s.connect((address, 80)) 20 | s.send(b"\r\n") 21 | 22 | 23 | main() 24 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /examples/server/README.md: -------------------------------------------------------------------------------- 1 | This is a port of [Server example](https://github.com/adafruit/Adafruit_CircuitPython_ESP32SPI/tree/main/examples/server) from Adafruit ESP32SPI library to ESP32-S2 WROVER. 2 | 3 | Should works on any ESP32-S2 **WROVER** module with builtin Neopixel like 4 | * Adafruit Metro ESP32-S2 5 | * Espressif Saola 1 6 | * MuseLab nanoESP32-S2 7 | * Unexpected Maker FeatherS2 8 | 9 | WROOM modules seems not have suficient RAM to run this example. 10 | 11 | To run: 12 | 13 | * copy `esp32s2_wsgiserver.py` file and `static` folder in CIRCUITPY drive 14 | * create the usual `secrets.py` 15 | * copy required libraries in `CIRCUITPY/lib` folder 16 | * wsgiserver (from this repo) 17 | * adafruit_wsgi (from [CircuitPython Libraries](https://circuitpython.org/libraries)) 18 | * neopixel (from [CircuitPython Libraries](https://circuitpython.org/libraries)) 19 | * rename `esp32s2_wsgiserver.py` to `code.py` 20 | or 21 | * type `import esp32s2_wsgiserver.py` in serial console 22 | * open a web browser at the a adress diplayed in serial console 23 | 24 | Support also /led_off and /led_on pathes. 25 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2022 Neradoc 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LICENSES/MIT.txt: -------------------------------------------------------------------------------- 1 | MIT License Copyright (c) 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is furnished 8 | to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice (including the next 11 | paragraph) shall be included in all copies or substantial portions of the 12 | Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 16 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 17 | OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 18 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF 19 | OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /LICENSES/Unlicense.txt: -------------------------------------------------------------------------------- 1 | This is free and unencumbered software released into the public domain. 2 | 3 | Anyone is free to copy, modify, publish, use, compile, sell, or distribute 4 | this software, either in source code form or as a compiled binary, for any 5 | purpose, commercial or non-commercial, and by any means. 6 | 7 | In jurisdictions that recognize copyright laws, the author or authors of this 8 | software dedicate any and all copyright interest in the software to the public 9 | domain. We make this dedication for the benefit of the public at large and 10 | to the detriment of our heirs and successors. We intend this dedication to 11 | be an overt act of relinquishment in perpetuity of all present and future 12 | rights to this software under copyright law. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 16 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 17 | BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 18 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH 19 | THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, 20 | please refer to 21 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2020 Diego Elio Pettenò 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | 5 | repos: 6 | - repo: https://github.com/python/black 7 | rev: 22.3.0 8 | hooks: 9 | - id: black 10 | - repo: https://github.com/fsfe/reuse-tool 11 | rev: v0.12.1 12 | hooks: 13 | - id: reuse 14 | - repo: https://github.com/pre-commit/pre-commit-hooks 15 | rev: v2.3.0 16 | hooks: 17 | - id: check-yaml 18 | - id: end-of-file-fixer 19 | - id: trailing-whitespace 20 | - repo: https://github.com/pycqa/pylint 21 | rev: pylint-2.7.1 22 | hooks: 23 | - id: pylint 24 | name: pylint (library code) 25 | types: [python] 26 | exclude: "^(docs/|examples/|tests/|setup.py$)" 27 | - repo: local 28 | hooks: 29 | - id: pylint_examples 30 | name: pylint (examples code) 31 | description: Run pylint rules on "examples/*.py" files 32 | entry: /usr/bin/env bash -c 33 | args: ['([[ ! -d "examples" ]] || for example in $(find . -path "./examples/*.py"); do pylint --disable=missing-docstring,invalid-name,consider-using-f-string $example; done)'] 34 | language: system 35 | - id: pylint_tests 36 | name: pylint (tests code) 37 | description: Run pylint rules on "tests/*.py" files 38 | entry: /usr/bin/env bash -c 39 | args: ['([[ ! -d "tests" ]] || for test in $(find . -path "./tests/*.py"); do pylint --disable=missing-docstring $test; done)'] 40 | language: system 41 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Introduction 2 | ============ 3 | 4 | This is a port of `adafruit_esp32spi/adafruit_esp32spi_wsgiserver.py` to ESP32-S2. 5 | 6 | * copy `wsgiserver.py` and all the files in `examples/wsgi_simpletest` to the board. 7 | * create the usual secrets.py (`see here `) 8 | * install the requirements of the demo with circup or manually 9 | * `adafruit_wsgi` for the web server application helper 10 | * `adafruit_dotstar` or `neopixel` for the LED demo 11 | * rename `wsgiserver_simpletest.py` to `code.py` 12 | 13 | Test by going to http://IP_ADDRESS/led_on/255/255/0 and http://IP_ADDRESS/led_off 14 | 15 | 16 | Dependencies 17 | ============= 18 | This driver depends on: 19 | 20 | * `Adafruit CircuitPython `_ 21 | 22 | Please ensure all dependencies are available on the CircuitPython filesystem. 23 | This is easily achieved by downloading 24 | `the Adafruit library and driver bundle `_ 25 | or individual libraries can be installed using 26 | `circup `_. 27 | 28 | Installing to a Connected CircuitPython Device with Circup 29 | ========================================================== 30 | 31 | Make sure that you have ``circup`` installed in your Python environment. 32 | Install it with the following command if necessary: 33 | 34 | .. code-block:: shell 35 | 36 | pip3 install circup 37 | 38 | With ``circup`` installed and your CircuitPython device connected use the 39 | following command to install: 40 | 41 | .. code-block:: shell 42 | 43 | circup install wsgiserver 44 | 45 | Or the following command to update an existing version: 46 | 47 | .. code-block:: shell 48 | 49 | circup update 50 | 51 | 52 | Contributing 53 | ============ 54 | 55 | Contributions are welcome! Please read our `Code of Conduct 56 | `_ 57 | before contributing to help this project stay welcoming. 58 | -------------------------------------------------------------------------------- /examples/wsgiserver_simpletest.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries 2 | # SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 3 | # SPDX-License-Identifier: MIT 4 | 5 | import board 6 | import busio 7 | from digitalio import DigitalInOut 8 | import socketpool 9 | import time 10 | import wifi 11 | 12 | import wsgiserver as server 13 | from adafruit_wsgi.wsgi_app import WSGIApp 14 | 15 | # Get wifi details and more from a secrets.py file 16 | try: 17 | from secrets import secrets 18 | except ImportError: 19 | print("WiFi secrets are kept in secrets.py, please add them there!") 20 | raise 21 | 22 | # This example depends on a WSGI Server to run. 23 | # We are using the wsgi server made for the ESP32 24 | 25 | print("ESP32 S2 simple web app test!") 26 | 27 | print("Connect wifi") 28 | wifi.radio.connect(secrets["ssid"], secrets["password"]) 29 | HOST = repr(wifi.radio.ipv4_address) 30 | PORT = 80 # Port to listen on 31 | print(HOST, PORT) 32 | 33 | 34 | """Use below for Most Boards""" 35 | import neopixel 36 | 37 | status_light = neopixel.NeoPixel(board.NEOPIXEL, 1) 38 | 39 | 40 | # Here we create our application, registering the 41 | # following functions to be called on specific HTTP GET requests routes 42 | 43 | web_app = WSGIApp() 44 | 45 | 46 | @web_app.route("/led_on///") 47 | def led_on(request, r, g, b): # pylint: disable=unused-argument 48 | print("led on!") 49 | status_light.fill((int(r), int(g), int(b))) 50 | return ("200 OK", [], "led on!") 51 | 52 | 53 | @web_app.route("/led_off") 54 | def led_off(request): # pylint: disable=unused-argument 55 | print("led off!") 56 | status_light.fill(0) 57 | return ("200 OK", [], "led off!") 58 | 59 | 60 | # Here we setup our server, passing in our web_app as the application 61 | wsgiServer = server.WSGIServer(80, application=web_app) 62 | 63 | print(f"open this IP in your browser: http://{HOST}:{PORT}/") 64 | 65 | # Start the server 66 | wsgiServer.start() 67 | while True: 68 | # Our main loop where we have the server poll for incoming requests 69 | wsgiServer.update_poll() 70 | # Could do any other background tasks here, like reading sensors 71 | time.sleep(0.01) 72 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | name: Build CI 6 | 7 | on: [pull_request, push] 8 | 9 | jobs: 10 | test: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Dump GitHub context 14 | env: 15 | GITHUB_CONTEXT: ${{ toJson(github) }} 16 | run: echo "$GITHUB_CONTEXT" 17 | - name: Translate Repo Name For Build Tools filename_prefix 18 | id: repo-name 19 | run: | 20 | echo ::set-output name=repo-name::$( 21 | echo ${{ github.repository }} | 22 | awk -F '\/' '{ print tolower($2) }' | 23 | tr '_' '-' 24 | ) 25 | - name: Set up Python 3.x 26 | uses: actions/setup-python@v2 27 | with: 28 | python-version: "3.x" 29 | - name: Versions 30 | run: | 31 | python3 --version 32 | - name: Checkout Current Repo 33 | uses: actions/checkout@v1 34 | with: 35 | submodules: true 36 | - name: Checkout tools repo 37 | uses: actions/checkout@v2 38 | with: 39 | repository: adafruit/actions-ci-circuitpython-libs 40 | path: actions-ci 41 | - name: Install dependencies 42 | # (e.g. - apt-get: gettext, etc; pip: circuitpython-build-tools, requirements.txt; etc.) 43 | run: | 44 | source actions-ci/install.sh 45 | - name: Pip install pylint, Sphinx, pre-commit 46 | run: | 47 | pip install --force-reinstall pylint Sphinx sphinx-rtd-theme pre-commit 48 | - name: Library version 49 | run: git describe --dirty --always --tags 50 | - name: Setup problem matchers 51 | uses: adafruit/circuitpython-action-library-ci-problem-matchers@v1 52 | - name: Pre-commit hooks 53 | run: | 54 | pre-commit run --all-files 55 | - name: Build assets 56 | run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location . 57 | - name: Archive bundles 58 | uses: actions/upload-artifact@v2 59 | with: 60 | name: bundles 61 | path: ${{ github.workspace }}/bundles/ 62 | - name: Check For docs folder 63 | id: need-docs 64 | run: | 65 | echo ::set-output name=docs::$( find . -wholename './docs' ) 66 | - name: Build docs 67 | if: contains(steps.need-docs.outputs.docs, 'docs') 68 | working-directory: docs 69 | run: sphinx-build -E -W -b html . _build/html 70 | - name: Check For setup.py 71 | id: need-pypi 72 | run: | 73 | echo ::set-output name=setup-py::$( find . -wholename './setup.py' ) 74 | - name: Build Python package 75 | if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') 76 | run: | 77 | pip install --upgrade setuptools wheel twine readme_renderer testresources 78 | python setup.py sdist 79 | python setup.py bdist_wheel --universal 80 | twine check dist/* 81 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | name: Release Actions 6 | 7 | on: 8 | release: 9 | types: [published] 10 | 11 | jobs: 12 | upload-release-assets: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - name: Dump GitHub context 16 | env: 17 | GITHUB_CONTEXT: ${{ toJson(github) }} 18 | run: echo "$GITHUB_CONTEXT" 19 | - name: Translate Repo Name For Build Tools filename_prefix 20 | id: repo-name 21 | run: | 22 | echo ::set-output name=repo-name::$( 23 | echo ${{ github.repository }} | 24 | awk -F '\/' '{ print tolower($2) }' | 25 | tr '_' '-' 26 | ) 27 | - name: Set up Python 3.x 28 | uses: actions/setup-python@v2 29 | with: 30 | python-version: "3.x" 31 | - name: Versions 32 | run: | 33 | python3 --version 34 | - name: Checkout Current Repo 35 | uses: actions/checkout@v1 36 | with: 37 | submodules: true 38 | - name: Checkout tools repo 39 | uses: actions/checkout@v2 40 | with: 41 | repository: adafruit/actions-ci-circuitpython-libs 42 | path: actions-ci 43 | - name: Install deps 44 | run: | 45 | source actions-ci/install.sh 46 | - name: Build assets 47 | run: circuitpython-build-bundles --filename_prefix ${{ steps.repo-name.outputs.repo-name }} --library_location . 48 | - name: Upload Release Assets 49 | # the 'official' actions version does not yet support dynamically 50 | # supplying asset names to upload. @csexton's version chosen based on 51 | # discussion in the issue below, as its the simplest to implement and 52 | # allows for selecting files with a pattern. 53 | # https://github.com/actions/upload-release-asset/issues/4 54 | #uses: actions/upload-release-asset@v1.0.1 55 | uses: csexton/release-asset-action@master 56 | with: 57 | pattern: "bundles/*" 58 | github-token: ${{ secrets.GITHUB_TOKEN }} 59 | 60 | upload-pypi: 61 | runs-on: ubuntu-latest 62 | steps: 63 | - uses: actions/checkout@v1 64 | - name: Check For setup.py 65 | id: need-pypi 66 | run: | 67 | echo ::set-output name=setup-py::$( find . -wholename './setup.py' ) 68 | - name: Set up Python 69 | if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') 70 | uses: actions/setup-python@v2 71 | with: 72 | python-version: '3.x' 73 | - name: Install dependencies 74 | if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') 75 | run: | 76 | python -m pip install --upgrade pip 77 | pip install setuptools wheel twine 78 | - name: Build and publish 79 | if: contains(steps.need-pypi.outputs.setup-py, 'setup.py') 80 | env: 81 | TWINE_USERNAME: ${{ secrets.pypi_username }} 82 | TWINE_PASSWORD: ${{ secrets.pypi_password }} 83 | run: | 84 | for file in $(find -not -path "./.*" -not -path "./docs*" -name "*.py"); do 85 | sed -i -e "s/0.0.0-auto.0/${{github.event.release.tag_name}}/" $file; 86 | done; 87 | python setup.py sdist 88 | twine upload dist/* 89 | -------------------------------------------------------------------------------- /examples/wsgiserver_displaytest.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries 2 | # SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 3 | # SPDX-License-Identifier: MIT 4 | 5 | import board 6 | import time 7 | import wifi 8 | from adafruit_wsgi.wsgi_app import WSGIApp 9 | import wsgiserver as server 10 | 11 | ############################################################################ 12 | ############################################################################ 13 | 14 | import displayio 15 | import terminalio 16 | from adafruit_display_text.bitmap_label import Label 17 | 18 | oled = board.DISPLAY 19 | splash = displayio.Group() 20 | 21 | main_label = Label( 22 | text="Connecting...", 23 | font=terminalio.FONT, 24 | color=0xFFFFFF, 25 | scale=2, 26 | anchored_position=(oled.width // 2, oled.height // 2), 27 | anchor_point=(0.5, 0.5), 28 | ) 29 | splash.append(main_label) 30 | oled.show(splash) 31 | 32 | ############################################################################ 33 | ############################################################################ 34 | 35 | # Get wifi details and more from a secrets.py file 36 | try: 37 | from secrets import secrets 38 | except ImportError: 39 | print("WiFi secrets are kept in secrets.py, please add them there!") 40 | raise 41 | 42 | # This example depends on a WSGI Server to run. 43 | # We are using the wsgi server made for the ESP32 44 | 45 | print("ESP32 S2 simple web app test!") 46 | 47 | print("Connect wifi") 48 | wifi.radio.connect(secrets["ssid"], secrets["password"]) 49 | HOST = repr(wifi.radio.ipv4_address) 50 | PORT = 80 # Port to listen on 51 | print(HOST, PORT) 52 | 53 | ############################################################################ 54 | ############################################################################ 55 | 56 | # Here we create our application, registering the 57 | # following functions to be called on specific HTTP GET requests routes 58 | 59 | web_app = WSGIApp() 60 | 61 | 62 | @web_app.route("/") 63 | def homepage(request): # pylint: disable=unused-argument 64 | text = """ 65 |

Text color

66 |

White

67 |

RED

68 |

GREEN

69 |

BLUE

70 | """ 71 | return ("200 OK", [], text) 72 | 73 | 74 | @web_app.route("/led_on///") 75 | def led_on(request, r, g, b): # pylint: disable=unused-argument 76 | print("led on!") 77 | main_label.color = (int(r), int(g), int(b)) 78 | text = f""" 79 |

Color is {(int(r), int(g), int(b))}. 80 |   81 |

82 |

Go back

83 | """ 84 | return ("200 OK", [], text) 85 | 86 | 87 | @web_app.route("/led_off") 88 | def led_off(request): # pylint: disable=unused-argument 89 | print("led off!") 90 | main_label.color = (255, 255, 255) 91 | text = """ 92 |

Color is white.

93 |

Go back

94 | """ 95 | return ("200 OK", [], text) 96 | 97 | 98 | ############################################################################ 99 | ############################################################################ 100 | 101 | # Here we setup our server, passing in our web_app as the application 102 | wsgiServer = server.WSGIServer(80, application=web_app) 103 | 104 | print(f"open this IP in your browser: http://{HOST}:{PORT}/") 105 | main_label.text = f"{HOST}" 106 | 107 | # Start the server 108 | wsgiServer.start() 109 | while True: 110 | # Our main loop where we have the server poll for incoming requests 111 | wsgiServer.update_poll() 112 | # Could do any other background tasks here, like reading sensors 113 | time.sleep(0.01) 114 | -------------------------------------------------------------------------------- /examples/server/static/led_color_picker_example.js: -------------------------------------------------------------------------------- 1 | // SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries 2 | // 3 | // SPDX-License-Identifier: MIT 4 | 5 | let canvas = document.getElementById('colorPicker'); 6 | let ctx = canvas.getContext("2d"); 7 | ctx.width = 300; 8 | ctx.height = 300; 9 | 10 | function drawColorPicker() { 11 | /** 12 | * Color picker inspired by: 13 | * https://medium.com/@bantic/hand-coding-a-color-wheel-with-canvas-78256c9d7d43 14 | */ 15 | let radius = 150; 16 | let image = ctx.createImageData(2*radius, 2*radius); 17 | let data = image.data; 18 | 19 | for (let x = -radius; x < radius; x++) { 20 | for (let y = -radius; y < radius; y++) { 21 | 22 | let [r, phi] = xy2polar(x, y); 23 | 24 | if (r > radius) { 25 | // skip all (x,y) coordinates that are outside of the circle 26 | continue; 27 | } 28 | 29 | let deg = rad2deg(phi); 30 | 31 | // Figure out the starting index of this pixel in the image data array. 32 | let rowLength = 2*radius; 33 | let adjustedX = x + radius; // convert x from [-50, 50] to [0, 100] (the coordinates of the image data array) 34 | let adjustedY = y + radius; // convert y from [-50, 50] to [0, 100] (the coordinates of the image data array) 35 | let pixelWidth = 4; // each pixel requires 4 slots in the data array 36 | let index = (adjustedX + (adjustedY * rowLength)) * pixelWidth; 37 | 38 | let hue = deg; 39 | let saturation = r / radius; 40 | let value = 1.0; 41 | 42 | let [red, green, blue] = hsv2rgb(hue, saturation, value); 43 | let alpha = 255; 44 | 45 | data[index] = red; 46 | data[index+1] = green; 47 | data[index+2] = blue; 48 | data[index+3] = alpha; 49 | } 50 | } 51 | 52 | ctx.putImageData(image, 0, 0); 53 | } 54 | 55 | function xy2polar(x, y) { 56 | let r = Math.sqrt(x*x + y*y); 57 | let phi = Math.atan2(y, x); 58 | return [r, phi]; 59 | } 60 | 61 | // rad in [-π, π] range 62 | // return degree in [0, 360] range 63 | function rad2deg(rad) { 64 | return ((rad + Math.PI) / (2 * Math.PI)) * 360; 65 | } 66 | 67 | // hue in range [0, 360] 68 | // saturation, value in range [0,1] 69 | // return [r,g,b] each in range [0,255] 70 | // See: https://en.wikipedia.org/wiki/HSL_and_HSV#From_HSV 71 | function hsv2rgb(hue, saturation, value) { 72 | let chroma = value * saturation; 73 | let hue1 = hue / 60; 74 | let x = chroma * (1- Math.abs((hue1 % 2) - 1)); 75 | let r1, g1, b1; 76 | if (hue1 >= 0 && hue1 <= 1) { 77 | ([r1, g1, b1] = [chroma, x, 0]); 78 | } else if (hue1 >= 1 && hue1 <= 2) { 79 | ([r1, g1, b1] = [x, chroma, 0]); 80 | } else if (hue1 >= 2 && hue1 <= 3) { 81 | ([r1, g1, b1] = [0, chroma, x]); 82 | } else if (hue1 >= 3 && hue1 <= 4) { 83 | ([r1, g1, b1] = [0, x, chroma]); 84 | } else if (hue1 >= 4 && hue1 <= 5) { 85 | ([r1, g1, b1] = [x, 0, chroma]); 86 | } else if (hue1 >= 5 && hue1 <= 6) { 87 | ([r1, g1, b1] = [chroma, 0, x]); 88 | } 89 | 90 | let m = value - chroma; 91 | let [r,g,b] = [r1+m, g1+m, b1+m]; 92 | 93 | // Change r,g,b values from [0,1] to [0,255] 94 | return [255*r,255*g,255*b]; 95 | } 96 | 97 | function onColorPick(event) { 98 | coords = getCursorPosition(canvas, event) 99 | imageData = ctx.getImageData(coords[0],coords[1],1,1) 100 | rgbObject = { 101 | r: imageData.data[0], 102 | g: imageData.data[1], 103 | b: imageData.data[2] 104 | } 105 | console.log(`r: ${rgbObject.r} g: ${rgbObject.g} b: ${rgbObject.b}`); 106 | data = JSON.stringify(rgbObject); 107 | window.fetch("/ajax/ledcolor", { 108 | method: "POST", 109 | body: data, 110 | headers: { 111 | 'Content-Type': 'application/json; charset=utf-8', 112 | }, 113 | }).then(response => { 114 | console.log("sucess!: " + response) 115 | }, error => { 116 | console.log("error!: " + error) 117 | }) 118 | } 119 | 120 | function getCursorPosition(canvas, event) { 121 | const rect = canvas.getBoundingClientRect() 122 | const x = event.clientX - rect.left 123 | const y = event.clientY - rect.top 124 | console.log("x: " + x + " y: " + y) 125 | return [x,y] 126 | } 127 | 128 | drawColorPicker(); 129 | canvas.addEventListener('mousedown', onColorPick); 130 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | 7 | # CircuitPython Community Code of Conduct 8 | 9 | ## Our Pledge 10 | 11 | In the interest of fostering an open and welcoming environment, we as 12 | contributors and leaders pledge to making participation in our project and 13 | our community a harassment-free experience for everyone, regardless of age, body 14 | size, disability, ethnicity, gender identity and expression, level or type of 15 | experience, education, socio-economic status, nationality, personal appearance, 16 | race, religion, or sexual identity and orientation. 17 | 18 | ## Our Standards 19 | 20 | We are committed to providing a friendly, safe and welcoming environment for 21 | all. 22 | 23 | Examples of behavior that contributes to creating a positive environment 24 | include: 25 | 26 | * Be kind and courteous to others 27 | * Using welcoming and inclusive language 28 | * Being respectful of differing viewpoints and experiences 29 | * Collaborating with other community members 30 | * Gracefully accepting constructive criticism 31 | * Focusing on what is best for the community 32 | * Showing empathy towards other community members 33 | 34 | Examples of unacceptable behavior by participants include: 35 | 36 | * The use of sexualized language or imagery and sexual attention or advances 37 | * The use of inappropriate images, including in a community member's avatar 38 | * The use of inappropriate language, including in a community member's nickname 39 | * Any spamming, flaming, baiting or other attention-stealing behavior 40 | * Excessive or unwelcome helping; answering outside the scope of the question 41 | asked 42 | * Discussion or promotion of activities or projects that intend or pose a risk of 43 | significant harm 44 | * Trolling, insulting/derogatory comments, and personal or political attacks 45 | * Promoting or spreading disinformation, lies, or conspiracy theories against 46 | a person, group, organisation, project, or community 47 | * Public or private harassment 48 | * Publishing others' private information, such as a physical or electronic 49 | address, without explicit permission 50 | * Other conduct which could reasonably be considered inappropriate 51 | 52 | The goal of the standards and moderation guidelines outlined here is to build 53 | and maintain a respectful community. We ask that you don’t just aim to be 54 | "technically unimpeachable", but rather try to be your best self. 55 | 56 | We value many things beyond technical expertise, including collaboration and 57 | supporting others within our community. Providing a positive experience for 58 | other community members can have a much more significant impact than simply 59 | providing the correct answer. 60 | 61 | ## Our Responsibilities 62 | 63 | Project leaders are responsible for clarifying the standards of acceptable 64 | behavior and are expected to take appropriate and fair corrective action in 65 | response to any instances of unacceptable behavior. 66 | 67 | Project leaders have the right and responsibility to remove, edit, or 68 | reject messages, comments, commits, code, issues, and other contributions 69 | that are not aligned to this Code of Conduct, or to ban temporarily or 70 | permanently any community member for other behaviors that they deem 71 | inappropriate, threatening, offensive, or harmful. 72 | 73 | ## Moderation 74 | 75 | Instances of behaviors that violate the CircuitPython Community Code of Conduct 76 | may be reported by any member of the community. Community members are 77 | encouraged to report these situations, including situations they witness 78 | involving other community members. 79 | 80 | You may report in the following ways: 81 | 82 | In any situation, you may email the project maintainer. 83 | 84 | Email reports will be kept confidential. 85 | 86 | In situations on GitHub where the issue is particularly offensive, possibly 87 | illegal, requires immediate action, or violates the GitHub terms of service, 88 | you should also report the message directly to GitHub via the comment, or via 89 | [GitHub Support](https://support.github.com/contact/report-abuse?category=report-abuse&report=other&report_type=unspecified). 90 | 91 | These are the steps for upholding our community’s standards of conduct. 92 | 93 | 1. Any member of the community may report any situation that violates the 94 | CircuitPython Community Code of Conduct. All reports will be reviewed and 95 | investigated. 96 | 2. If the behavior is a severe violation, the community member who 97 | committed the violation may be banned immediately, without warning. 98 | 3. Otherwise, moderators will first respond to such behavior with a warning. 99 | 4. Moderators follow a soft "three strikes" policy - the community member may 100 | be given another chance, if they are receptive to the warning and change their 101 | behavior. 102 | 5. If the community member is unreceptive or unreasonable when warned by a 103 | moderator, or the warning goes unheeded, they may be banned for a first or 104 | second offense. Repeated offenses will result in the community member being 105 | banned. 106 | 6. Disciplinary actions (warnings, bans, etc) for Code of Conduct violations apply 107 | to the platform where the violation occurred. However, depending on the severity 108 | of the violation, the disciplinary action may be applied across CircuitPython's 109 | other community platforms. For example, a severe violation in one Community forum 110 | may result in a ban on not only the CircuitPython GitHub organisation, 111 | but also on the CircuitPython Twitter, live stream text chats, etc. 112 | 113 | ## Scope 114 | 115 | This Code of Conduct and the enforcement policies listed above apply to all 116 | CircuitPython Community venues. This includes but is not limited to any community 117 | spaces (both public and private), and CircuitPython repositories. Examples of 118 | CircuitPython Community spaces include but are not limited to meet-ups, issue 119 | threads on GitHub, text chats during a live stream, or interaction at a conference. 120 | 121 | This Code of Conduct applies both within project spaces and in public spaces 122 | when an individual is representing the project or its community. As a community 123 | member, you are representing our community, and are expected to behave 124 | accordingly. 125 | 126 | ## Attribution 127 | 128 | This Code of Conduct is adapted from the 129 | [Adafruit Community Code of Conduct](https://github.com/adafruit/Adafruit_Community_Code_of_Conduct), 130 | which is adapted from the [Contributor Covenant](https://www.contributor-covenant.org/), 131 | version 1.4, available on [contributor-covenant.org](https://www.contributor-covenant.org/version/1/4/code-of-conduct.html), 132 | and the [Rust Code of Conduct](https://www.rust-lang.org/en-US/conduct.html). 133 | 134 | For other projects adopting the CircuitPython Community Code of 135 | Conduct, please contact the maintainers of those projects for enforcement. 136 | If you wish to use this code of conduct for your own project, consider 137 | explicitly mentioning your moderation policy or making a copy with your 138 | own moderation policy so as to avoid confusion. 139 | -------------------------------------------------------------------------------- /examples/server/esp32s2_wsgiserver.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2019 ladyada for Adafruit Industries 2 | # SPDX-FileContributor: Modified by Reppad 3 | # 4 | # SPDX-License-Identifier: MIT 5 | 6 | import os 7 | import board 8 | import neopixel 9 | import wifi 10 | import wsgiserver as server 11 | 12 | # This example depends on the 'static' folder in the examples folder 13 | # being copied to the root of the circuitpython filesystem. 14 | # This is where our static assets like html, js, and css live. 15 | 16 | # Get wifi details and more from a secrets.py file 17 | try: 18 | from secrets import secrets 19 | except ImportError: 20 | print("WiFi secrets are kept in secrets.py, please add them there!") 21 | raise 22 | 23 | try: 24 | import json as json_module 25 | except ImportError: 26 | import ujson as json_module 27 | 28 | print("ESP32-S2 simple web server test!") 29 | 30 | print("Connect wifi") 31 | wifi.radio.connect(secrets["ssid"], secrets["password"]) 32 | HOST = repr(wifi.radio.ipv4_address) 33 | PORT = 80 # Port to listen on 34 | print(HOST, PORT) 35 | 36 | # Use below for Most Boards 37 | status_light = neopixel.NeoPixel( 38 | board.NEOPIXEL, 1, brightness=0.2 39 | ) # Uncomment for Most Boards 40 | # Uncomment below for ItsyBitsy M4 41 | # import adafruit_dotstar as dotstar 42 | # status_light = dotstar.DotStar(board.APA102_SCK, board.APA102_MOSI, 1, brightness=1) 43 | 44 | 45 | class SimpleWSGIApplication: 46 | """ 47 | An example of a simple WSGI Application that supports 48 | basic route handling and static asset file serving for common file types 49 | """ 50 | 51 | INDEX = "/index.html" 52 | CHUNK_SIZE = 8912 # max number of bytes to read at once when reading files 53 | 54 | def __init__(self, static_dir=None, debug=False): 55 | self._debug = debug 56 | self._listeners = {} 57 | self._start_response = None 58 | self._static = static_dir 59 | if self._static: 60 | self._static_files = ["/" + file for file in os.listdir(self._static)] 61 | 62 | def __call__(self, environ, start_response): 63 | """ 64 | Called whenever the server gets a request. 65 | The environ dict has details about the request per wsgi specification. 66 | Call start_response with the response status string and headers as a list of tuples. 67 | Return a single item list with the item being your response data string. 68 | """ 69 | if self._debug: 70 | self._log_environ(environ) 71 | 72 | self._start_response = start_response 73 | status = "" 74 | headers = [] 75 | resp_data = [] 76 | 77 | key = self._get_listener_key( 78 | environ["REQUEST_METHOD"].lower(), environ["PATH_INFO"] 79 | ) 80 | if key in self._listeners: 81 | status, headers, resp_data = self._listeners[key](environ) 82 | if environ["REQUEST_METHOD"].lower() == "get" and self._static: 83 | path = environ["PATH_INFO"] 84 | if path in self._static_files: 85 | status, headers, resp_data = self.serve_file( 86 | path, directory=self._static 87 | ) 88 | elif path == "/" and self.INDEX in self._static_files: 89 | status, headers, resp_data = self.serve_file( 90 | self.INDEX, directory=self._static 91 | ) 92 | 93 | self._start_response(status, headers) 94 | return resp_data 95 | 96 | def on(self, method, path, request_handler): 97 | """ 98 | Register a Request Handler for a particular HTTP method and path. 99 | request_handler will be called whenever a matching HTTP request is received. 100 | 101 | request_handler should accept the following args: 102 | (Dict environ) 103 | request_handler should return a tuple in the shape of: 104 | (status, header_list, data_iterable) 105 | 106 | :param str method: the method of the HTTP request 107 | :param str path: the path of the HTTP request 108 | :param func request_handler: the function to call 109 | """ 110 | self._listeners[self._get_listener_key(method, path)] = request_handler 111 | 112 | def serve_file(self, file_path, directory=None): 113 | status = "200 OK" 114 | headers = [("Content-Type", self._get_content_type(file_path))] 115 | 116 | full_path = file_path if not directory else directory + file_path 117 | 118 | def resp_iter(): 119 | with open(full_path, "rb") as file: 120 | while True: 121 | chunk = file.read(self.CHUNK_SIZE) 122 | if chunk: 123 | yield chunk 124 | else: 125 | break 126 | 127 | return (status, headers, resp_iter()) 128 | 129 | def _log_environ(self, environ): # pylint: disable=no-self-use 130 | print("environ map:") 131 | for name, value in environ.items(): 132 | print(name, value) 133 | 134 | def _get_listener_key(self, method, path): # pylint: disable=no-self-use 135 | return "{0}|{1}".format(method.lower(), path) 136 | 137 | def _get_content_type(self, file): # pylint: disable=no-self-use 138 | ext = file.split(".")[-1] 139 | if ext in ("html", "htm"): 140 | return "text/html" 141 | if ext == "js": 142 | return "application/javascript" 143 | if ext == "css": 144 | return "text/css" 145 | if ext in ("jpg", "jpeg"): 146 | return "image/jpeg" 147 | if ext == "png": 148 | return "image/png" 149 | return "text/plain" 150 | 151 | 152 | # Our HTTP Request handlers 153 | def led_on(environ): # pylint: disable=unused-argument 154 | print("led on!") 155 | status_light.fill((0, 0, 100)) 156 | return web_app.serve_file("static/index.html") 157 | 158 | 159 | def led_off(environ): # pylint: disable=unused-argument 160 | print("led off!") 161 | status_light.fill(0) 162 | return web_app.serve_file("static/index.html") 163 | 164 | 165 | def led_color(environ): # pylint: disable=unused-argument 166 | json = json_module.loads(environ["wsgi.input"].getvalue()) 167 | print(json) 168 | rgb_tuple = (json.get("r"), json.get("g"), json.get("b")) 169 | status_light.fill(rgb_tuple) 170 | return ("200 OK", [], []) 171 | 172 | 173 | # Here we create our application, setting the static directory location 174 | # and registering the above request_handlers for specific HTTP requests 175 | # we want to listen and respond to. 176 | static = "/static" 177 | try: 178 | static_files = os.listdir(static) 179 | if "index.html" not in static_files: 180 | raise RuntimeError( 181 | """ 182 | This example depends on an index.html, but it isn't present. 183 | Please add it to the {0} directory""".format( 184 | static 185 | ) 186 | ) 187 | except (OSError) as e: 188 | raise RuntimeError( 189 | """ 190 | This example depends on a static asset directory. 191 | Please create one named {0} in the root of the device filesystem.""".format( 192 | static 193 | ) 194 | ) from e 195 | 196 | web_app = SimpleWSGIApplication(static_dir=static) 197 | web_app.on("GET", "/led_on", led_on) 198 | web_app.on("GET", "/led_off", led_off) 199 | web_app.on("POST", "/ajax/ledcolor", led_color) 200 | 201 | # Here we setup our server, passing in our web_app as the application 202 | wsgiServer = server.WSGIServer(80, application=web_app) 203 | 204 | print(f"open this IP in your browser: http://{HOST}:{PORT}/") 205 | 206 | # Start the server 207 | wsgiServer.start() 208 | while True: 209 | # Our main loop where we have the server poll for incoming requests 210 | wsgiServer.update_poll() 211 | # Could do any other background tasks here, like reading sensors 212 | -------------------------------------------------------------------------------- /wsgiserver.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: Copyright (c) 2019 Matt Costi for Adafruit Industries 2 | # SPDX-FileCopyrightText: Copyright (c) 2022 Neradoc 3 | # 4 | # SPDX-License-Identifier: MIT 5 | 6 | """ 7 | `wsgiserver` 8 | ================================================================================ 9 | 10 | A simple WSGI (Web Server Gateway Interface) server that interfaces with the ESP32 over SPI. 11 | Opens a specified port on the ESP32 to listen for incoming HTTP Requests and 12 | Accepts an Application object that must be callable, which gets called 13 | whenever a new HTTP Request has been received. 14 | 15 | The Application MUST accept 2 ordered parameters: 16 | 1. environ object (incoming request data) 17 | 2. start_response function. Must be called before the Application 18 | callable returns, in order to set the response status and headers. 19 | 20 | The Application MUST return a single string in a list, 21 | which is the response data 22 | 23 | Requires update_poll being called in the applications main event loop. 24 | 25 | For more details about Python WSGI see: 26 | https://www.python.org/dev/peps/pep-0333/ 27 | 28 | * Author(s): Matt Costi, Neradoc 29 | """ 30 | # pylint: disable=no-name-in-module 31 | 32 | import io 33 | import gc 34 | from micropython import const 35 | import socketpool 36 | import wifi 37 | 38 | 39 | __version__ = "0.0.0-auto.0" 40 | __repo__ = "https://github.com/Neradoc/CircuitPython_wsgiserver.git" 41 | 42 | 43 | class BadRequestError(Exception): 44 | """Raised when the client sends an unexpected empty line""" 45 | 46 | 47 | _BUFFER_SIZE = 32 48 | buffer = bytearray(_BUFFER_SIZE) 49 | 50 | 51 | def _readline(socketin): 52 | """ 53 | Implement readline() for native wifi using recv_into. 54 | 55 | :param Socket socketin: the socket. 56 | """ 57 | data_string = b"" 58 | while True: 59 | try: 60 | num = socketin.recv_into(buffer, 1) 61 | data_string += str(buffer, "utf8")[:num] 62 | if num == 0: 63 | return data_string 64 | if data_string[-2:] == b"\r\n": 65 | return data_string[:-2] 66 | except OSError as ex: 67 | # if ex.errno == 9: # [Errno 9] EBADF 68 | # return None 69 | if ex.errno == 11: # [Errno 11] EAGAIN 70 | continue 71 | raise 72 | 73 | 74 | def _read(socketin, length=-1): 75 | """ 76 | Implement read() for native wifi using recv_into. 77 | 78 | :param Socket socketin: the socket. 79 | :param int length: how many bytes to read. 80 | """ 81 | total = 0 82 | data_string = b"" 83 | try: 84 | if length > 0: # pylint:disable=no-else-return 85 | while total < length: 86 | reste = length - total 87 | num = socketin.recv_into(buffer, min(_BUFFER_SIZE, reste)) 88 | # 89 | if num == 0: 90 | # timeout 91 | # raise OSError(110) 92 | return data_string 93 | # 94 | data_string += buffer[:num] 95 | total = total + num 96 | return data_string 97 | else: 98 | while True: 99 | num = socketin.recv_into(buffer, 1) 100 | data_string += str(buffer, "utf8")[:num] 101 | if num == 0: 102 | return data_string 103 | except OSError as ex: 104 | if ex.errno == 11: # [Errno 11] EAGAIN 105 | return data_string 106 | raise 107 | 108 | 109 | def parse_headers(sock): 110 | """ 111 | Parses the header portion of an HTTP request/response from the socket. 112 | Expects first line of HTTP request/response to have been read already 113 | return: header dictionary 114 | rtype: Dict 115 | """ 116 | headers = {} 117 | while True: 118 | line = _readline(sock) 119 | if not line or line == b"\r\n": 120 | break 121 | 122 | # print("**line: ", line) 123 | title, content = line.split(b": ", 1) 124 | if title and content: 125 | title = str(title.lower(), "utf-8") 126 | content = str(content, "utf-8") 127 | headers[title] = content 128 | return headers 129 | 130 | 131 | pool = socketpool.SocketPool(wifi.radio) 132 | 133 | NO_SOCK_AVAIL = const(255) 134 | 135 | # pylint: disable=invalid-name 136 | class WSGIServer: 137 | """ 138 | A simple server that implements the WSGI interface 139 | """ 140 | 141 | def __init__(self, port=80, debug=False, application=None): 142 | self.application = application 143 | self.port = port 144 | self._server_sock = None 145 | self._client_sock = None 146 | self._debug = debug 147 | 148 | self._response_status = None 149 | self._response_headers = [] 150 | 151 | def start(self): 152 | """ 153 | starts the server and begins listening for incoming connections. 154 | Call update_poll in the main loop for the application callable to be 155 | invoked on receiving an incoming request. 156 | """ 157 | self._server_sock = pool.socket(pool.AF_INET, pool.SOCK_STREAM) 158 | self._server_sock.bind((repr(wifi.radio.ipv4_address), self.port)) 159 | self._server_sock.listen(1) 160 | 161 | # if self._debug: 162 | # ip = _the_interface.pretty_ip(_the_interface.ip_address) 163 | # print("Server available at {0}:{1}".format(ip, self.port)) 164 | # print( 165 | # "Sever status: ", 166 | # _the_interface.get_server_state(self._server_sock.socknum), 167 | # ) 168 | 169 | def pretty_ip(self): 170 | """ 171 | Return a "pretty" representation of the current local IP. 172 | """ 173 | return f"http://{wifi.radio.ipv4_address}:{self.port}" 174 | 175 | def update_poll(self): 176 | """ 177 | Call this method inside your main event loop to get the server 178 | check for new incoming client requests. When a request comes in, 179 | the application callable will be invoked. 180 | """ 181 | self.client_available() 182 | if self._client_sock: 183 | try: 184 | environ = self._get_environ(self._client_sock) 185 | result = self.application(environ, self._start_response) 186 | self.finish_response(result) 187 | except BadRequestError: 188 | self._start_response("400 Bad Request", []) 189 | self.finish_response([]) 190 | 191 | def finish_response(self, result): 192 | """ 193 | Called after the application callbile returns result data to respond with. 194 | Creates the HTTP Response payload from the response_headers and results data, 195 | and sends it back to client. 196 | 197 | :param string result: the data string to send back in the response to the client. 198 | """ 199 | try: 200 | response = "HTTP/1.1 {0}\r\n".format(self._response_status) 201 | for header in self._response_headers: 202 | response += "{0}: {1}\r\n".format(*header) 203 | response += "\r\n" 204 | self._client_sock.send(response.encode("utf-8")) 205 | for data in result: 206 | if isinstance(data, str): 207 | data = data.encode("utf-8") 208 | elif not isinstance(data, bytes): 209 | data = str(data).encode("utf-8") 210 | bytes_sent = 0 211 | while bytes_sent < len(data): 212 | try: 213 | bytes_sent += self._client_sock.send(data[bytes_sent:]) 214 | except OSError as ex: 215 | if ex.errno != 11: # [Errno 11] EAGAIN 216 | raise 217 | gc.collect() 218 | except OSError as ex: 219 | if ex.errno != 104: # [Errno 104] ECONNRESET 220 | raise 221 | finally: 222 | # print("closing") 223 | self._client_sock.close() 224 | self._client_sock = None 225 | 226 | def client_available(self): 227 | """ 228 | returns a client socket connection if available. 229 | Otherwise, returns None 230 | :return: the client 231 | :rtype: Socket 232 | """ 233 | if not self._server_sock: 234 | print("Server has not been started, cannot check for clients!") 235 | elif not self._client_sock: 236 | self._server_sock.setblocking(False) 237 | try: 238 | self._client_sock, _ = self._server_sock.accept() 239 | except OSError as ex: 240 | if ex.errno != 11: # [Errno 11] EAGAIN 241 | raise 242 | 243 | def _start_response(self, status, response_headers): 244 | """ 245 | The application callable will be given this method as the second param 246 | This is to be called before the application callable returns, to signify 247 | the response can be started with the given status and headers. 248 | 249 | :param string status: a status string including the code and reason. ex: "200 OK" 250 | :param list response_headers: a list of tuples to represent the headers. 251 | ex ("header-name", "header value") 252 | """ 253 | self._response_status = status 254 | self._response_headers = [("Server", "esp32WSGIServer")] + response_headers 255 | 256 | def _get_environ(self, client): 257 | """ 258 | The application callable will be given the resulting environ dictionary. 259 | It contains metadata about the incoming request and the request body ("wsgi.input") 260 | 261 | :param Socket client: socket to read the request from 262 | """ 263 | env = {} 264 | line = _readline(client).decode("utf-8") 265 | try: 266 | (method, path, ver) = line.rstrip("\r\n").split(None, 2) 267 | except ValueError: 268 | raise BadRequestError("Unknown request from client.") 269 | 270 | env["wsgi.version"] = (1, 0) 271 | env["wsgi.url_scheme"] = "http" 272 | env["wsgi.multithread"] = False 273 | env["wsgi.multiprocess"] = False 274 | env["wsgi.run_once"] = False 275 | 276 | env["REQUEST_METHOD"] = method 277 | env["SCRIPT_NAME"] = "" 278 | env["SERVER_NAME"] = str(wifi.radio.ipv4_address) 279 | env["SERVER_PROTOCOL"] = ver 280 | env["SERVER_PORT"] = self.port 281 | if path.find("?") >= 0: 282 | env["PATH_INFO"] = path.split("?")[0] 283 | env["QUERY_STRING"] = path.split("?")[1] 284 | else: 285 | env["PATH_INFO"] = path 286 | 287 | headers = parse_headers(client) 288 | if "content-type" in headers: 289 | env["CONTENT_TYPE"] = headers.get("content-type") 290 | if "content-length" in headers: 291 | env["CONTENT_LENGTH"] = headers.get("content-length") 292 | body = _read(client, int(env["CONTENT_LENGTH"])) 293 | env["wsgi.input"] = io.StringIO(body) 294 | else: 295 | body = _read(client) 296 | env["wsgi.input"] = io.StringIO(body) 297 | for name, value in headers.items(): 298 | key = "HTTP_" + name.replace("-", "_").upper() 299 | if key in env: 300 | value = "{0},{1}".format(env[key], value) 301 | env[key] = value 302 | 303 | return env 304 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /.pylintrc: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | 5 | [MASTER] 6 | 7 | # A comma-separated list of package or module names from where C extensions may 8 | # be loaded. Extensions are loading into the active Python interpreter and may 9 | # run arbitrary code 10 | extension-pkg-whitelist= 11 | 12 | # Add files or directories to the ignore-list. They should be base names, not 13 | # paths. 14 | ignore=CVS 15 | 16 | # Add files or directories matching the regex patterns to the ignore-list. The 17 | # regex matches against base names, not paths. 18 | ignore-patterns= 19 | 20 | # Python code to execute, usually for sys.path manipulation such as 21 | # pygtk.require(). 22 | #init-hook= 23 | 24 | # Use multiple processes to speed up Pylint. 25 | jobs=1 26 | 27 | # List of plugins (as comma separated values of python modules names) to load, 28 | # usually to register additional checkers. 29 | load-plugins= 30 | 31 | # Pickle collected data for later comparisons. 32 | persistent=yes 33 | 34 | # Specify a configuration file. 35 | #rcfile= 36 | 37 | # Allow loading of arbitrary C extensions. Extensions are imported into the 38 | # active Python interpreter and may run arbitrary code. 39 | unsafe-load-any-extension=no 40 | 41 | disable=wrong-import-order,consider-using-f-string,raise-missing-from 42 | 43 | 44 | [MESSAGES CONTROL] 45 | 46 | # Only show warnings with the listed confidence levels. Leave empty to show 47 | # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED 48 | confidence= 49 | 50 | # Disable the message, report, category or checker with the given id(s). You 51 | # can either give multiple identifiers separated by comma (,) or put this 52 | # option multiple times (only on the command line, not in the configuration 53 | # file where it should appear only once).You can also use "--disable=all" to 54 | # disable everything first and then reenable specific checks. For example, if 55 | # you want to run only the similarities checker, you can use "--disable=all 56 | # --enable=similarities". If you want to run only the classes checker, but have 57 | # no Warning level messages displayed, use"--disable=all --enable=classes 58 | # --disable=W" 59 | # disable=import-error,print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call 60 | disable=print-statement,parameter-unpacking,unpacking-in-except,old-raise-syntax,backtick,long-suffix,old-ne-operator,old-octal-literal,import-star-module-level,raw-checker-failed,bad-inline-option,locally-disabled,locally-enabled,file-ignored,suppressed-message,useless-suppression,deprecated-pragma,apply-builtin,basestring-builtin,buffer-builtin,cmp-builtin,coerce-builtin,execfile-builtin,file-builtin,long-builtin,raw_input-builtin,reduce-builtin,standarderror-builtin,unicode-builtin,xrange-builtin,coerce-method,delslice-method,getslice-method,setslice-method,no-absolute-import,old-division,dict-iter-method,dict-view-method,next-method-called,metaclass-assignment,indexing-exception,raising-string,reload-builtin,oct-method,hex-method,nonzero-method,cmp-method,input-builtin,round-builtin,intern-builtin,unichr-builtin,map-builtin-not-iterating,zip-builtin-not-iterating,range-builtin-not-iterating,filter-builtin-not-iterating,using-cmp-argument,eq-without-hash,div-method,idiv-method,rdiv-method,exception-message-attribute,invalid-str-codec,sys-max-int,bad-python3-import,deprecated-string-function,deprecated-str-translate-call,import-error,bad-continuation,pointless-string-statement 61 | 62 | # Enable the message, report, category or checker with the given id(s). You can 63 | # either give multiple identifier separated by comma (,) or put this option 64 | # multiple time (only on the command line, not in the configuration file where 65 | # it should appear only once). See also the "--disable" option for examples. 66 | enable= 67 | 68 | 69 | [REPORTS] 70 | 71 | # Python expression which should return a note less than 10 (10 is the highest 72 | # note). You have access to the variables errors warning, statement which 73 | # respectively contain the number of errors / warnings messages and the total 74 | # number of statements analyzed. This is used by the global evaluation report 75 | # (RP0004). 76 | evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) 77 | 78 | # Template used to display messages. This is a python new-style format string 79 | # used to format the message information. See doc for all details 80 | #msg-template= 81 | 82 | # Set the output format. Available formats are text, parseable, colorized, json 83 | # and msvs (visual studio).You can also give a reporter class, eg 84 | # mypackage.mymodule.MyReporterClass. 85 | output-format=text 86 | 87 | # Tells whether to display a full report or only the messages 88 | reports=no 89 | 90 | # Activate the evaluation score. 91 | score=yes 92 | 93 | 94 | [REFACTORING] 95 | 96 | # Maximum number of nested blocks for function / method body 97 | max-nested-blocks=5 98 | 99 | 100 | [LOGGING] 101 | 102 | # Logging modules to check that the string format arguments are in logging 103 | # function parameter format 104 | logging-modules=logging 105 | 106 | 107 | [SPELLING] 108 | 109 | # Spelling dictionary name. Available dictionaries: none. To make it working 110 | # install python-enchant package. 111 | spelling-dict= 112 | 113 | # List of comma separated words that should not be checked. 114 | spelling-ignore-words= 115 | 116 | # A path to a file that contains private dictionary; one word per line. 117 | spelling-private-dict-file= 118 | 119 | # Tells whether to store unknown words to indicated private dictionary in 120 | # --spelling-private-dict-file option instead of raising a message. 121 | spelling-store-unknown-words=no 122 | 123 | 124 | [MISCELLANEOUS] 125 | 126 | # List of note tags to take in consideration, separated by a comma. 127 | # notes=FIXME,XXX,TODO 128 | notes=FIXME,XXX 129 | 130 | 131 | [TYPECHECK] 132 | 133 | # List of decorators that produce context managers, such as 134 | # contextlib.contextmanager. Add to this list to register other decorators that 135 | # produce valid context managers. 136 | contextmanager-decorators=contextlib.contextmanager 137 | 138 | # List of members which are set dynamically and missed by pylint inference 139 | # system, and so shouldn't trigger E1101 when accessed. Python regular 140 | # expressions are accepted. 141 | generated-members= 142 | 143 | # Tells whether missing members accessed in mixin class should be ignored. A 144 | # mixin class is detected if its name ends with "mixin" (case insensitive). 145 | ignore-mixin-members=yes 146 | 147 | # This flag controls whether pylint should warn about no-member and similar 148 | # checks whenever an opaque object is returned when inferring. The inference 149 | # can return multiple potential results while evaluating a Python object, but 150 | # some branches might not be evaluated, which results in partial inference. In 151 | # that case, it might be useful to still emit no-member and other checks for 152 | # the rest of the inferred objects. 153 | ignore-on-opaque-inference=yes 154 | 155 | # List of class names for which member attributes should not be checked (useful 156 | # for classes with dynamically set attributes). This supports the use of 157 | # qualified names. 158 | ignored-classes=optparse.Values,thread._local,_thread._local 159 | 160 | # List of module names for which member attributes should not be checked 161 | # (useful for modules/projects where namespaces are manipulated during runtime 162 | # and thus existing member attributes cannot be deduced by static analysis. It 163 | # supports qualified module names, as well as Unix pattern matching. 164 | ignored-modules=board 165 | 166 | # Show a hint with possible names when a member name was not found. The aspect 167 | # of finding the hint is based on edit distance. 168 | missing-member-hint=yes 169 | 170 | # The minimum edit distance a name should have in order to be considered a 171 | # similar match for a missing member name. 172 | missing-member-hint-distance=1 173 | 174 | # The total number of similar names that should be taken in consideration when 175 | # showing a hint for a missing member. 176 | missing-member-max-choices=1 177 | 178 | 179 | [VARIABLES] 180 | 181 | # List of additional names supposed to be defined in builtins. Remember that 182 | # you should avoid to define new builtins when possible. 183 | additional-builtins= 184 | 185 | # Tells whether unused global variables should be treated as a violation. 186 | allow-global-unused-variables=yes 187 | 188 | # List of strings which can identify a callback function by name. A callback 189 | # name must start or end with one of those strings. 190 | callbacks=cb_,_cb 191 | 192 | # A regular expression matching the name of dummy variables (i.e. expectedly 193 | # not used). 194 | dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_ 195 | 196 | # Argument names that match this expression will be ignored. Default to name 197 | # with leading underscore 198 | ignored-argument-names=_.*|^ignored_|^unused_ 199 | 200 | # Tells whether we should check for unused import in __init__ files. 201 | init-import=no 202 | 203 | # List of qualified module names which can have objects that can redefine 204 | # builtins. 205 | redefining-builtins-modules=six.moves,future.builtins 206 | 207 | 208 | [FORMAT] 209 | 210 | # Expected format of line ending, e.g. empty (any line ending), LF or CRLF. 211 | # expected-line-ending-format= 212 | expected-line-ending-format=LF 213 | 214 | # Regexp for a line that is allowed to be longer than the limit. 215 | ignore-long-lines=^\s*(# )??$ 216 | 217 | # Number of spaces of indent required inside a hanging or continued line. 218 | indent-after-paren=4 219 | 220 | # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 221 | # tab). 222 | indent-string=' ' 223 | 224 | # Maximum number of characters on a single line. 225 | max-line-length=100 226 | 227 | # Maximum number of lines in a module 228 | max-module-lines=1000 229 | 230 | # List of optional constructs for which whitespace checking is disabled. `dict- 231 | # separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. 232 | # `trailing-comma` allows a space between comma and closing bracket: (a, ). 233 | # `empty-line` allows space-only lines. 234 | no-space-check=trailing-comma,dict-separator 235 | 236 | # Allow the body of a class to be on the same line as the declaration if body 237 | # contains single statement. 238 | single-line-class-stmt=no 239 | 240 | # Allow the body of an if to be on the same line as the test if there is no 241 | # else. 242 | single-line-if-stmt=no 243 | 244 | 245 | [SIMILARITIES] 246 | 247 | # Ignore comments when computing similarities. 248 | ignore-comments=yes 249 | 250 | # Ignore docstrings when computing similarities. 251 | ignore-docstrings=yes 252 | 253 | # Ignore imports when computing similarities. 254 | ignore-imports=yes 255 | 256 | # Minimum lines number of a similarity. 257 | min-similarity-lines=12 258 | 259 | 260 | [BASIC] 261 | 262 | # Naming hint for argument names 263 | argument-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ 264 | 265 | # Regular expression matching correct argument names 266 | argument-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ 267 | 268 | # Naming hint for attribute names 269 | attr-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ 270 | 271 | # Regular expression matching correct attribute names 272 | attr-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ 273 | 274 | # Bad variable names which should always be refused, separated by a comma 275 | bad-names=foo,bar,baz,toto,tutu,tata 276 | 277 | # Naming hint for class attribute names 278 | class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ 279 | 280 | # Regular expression matching correct class attribute names 281 | class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ 282 | 283 | # Naming hint for class names 284 | # class-name-hint=[A-Z_][a-zA-Z0-9]+$ 285 | class-name-hint=[A-Z_][a-zA-Z0-9_]+$ 286 | 287 | # Regular expression matching correct class names 288 | # class-rgx=[A-Z_][a-zA-Z0-9]+$ 289 | class-rgx=[A-Z_][a-zA-Z0-9_]+$ 290 | 291 | # Naming hint for constant names 292 | const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$ 293 | 294 | # Regular expression matching correct constant names 295 | const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ 296 | 297 | # Minimum line length for functions/classes that require docstrings, shorter 298 | # ones are exempt. 299 | docstring-min-length=-1 300 | 301 | # Naming hint for function names 302 | function-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ 303 | 304 | # Regular expression matching correct function names 305 | function-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ 306 | 307 | # Good variable names which should always be accepted, separated by a comma 308 | # good-names=i,j,k,ex,Run,_ 309 | good-names=r,g,b,w,i,j,k,n,x,y,z,ex,ok,Run,_ 310 | 311 | # Include a hint for the correct naming format with invalid-name 312 | include-naming-hint=no 313 | 314 | # Naming hint for inline iteration names 315 | inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$ 316 | 317 | # Regular expression matching correct inline iteration names 318 | inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ 319 | 320 | # Naming hint for method names 321 | method-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ 322 | 323 | # Regular expression matching correct method names 324 | method-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ 325 | 326 | # Naming hint for module names 327 | module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ 328 | 329 | # Regular expression matching correct module names 330 | module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ 331 | 332 | # Colon-delimited sets of names that determine each other's naming style when 333 | # the name regexes allow several styles. 334 | name-group= 335 | 336 | # Regular expression which should only match function or class names that do 337 | # not require a docstring. 338 | no-docstring-rgx=^_ 339 | 340 | # List of decorators that produce properties, such as abc.abstractproperty. Add 341 | # to this list to register other decorators that produce valid properties. 342 | property-classes=abc.abstractproperty 343 | 344 | # Naming hint for variable names 345 | variable-name-hint=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ 346 | 347 | # Regular expression matching correct variable names 348 | variable-rgx=(([a-z][a-z0-9_]{2,30})|(_[a-z0-9_]*))$ 349 | 350 | 351 | [IMPORTS] 352 | 353 | # Allow wildcard imports from modules that define __all__. 354 | allow-wildcard-with-all=no 355 | 356 | # Analyse import fallback blocks. This can be used to support both Python 2 and 357 | # 3 compatible code, which means that the block might have code that exists 358 | # only in one or another interpreter, leading to false positives when analysed. 359 | analyse-fallback-blocks=no 360 | 361 | # Deprecated modules which should not be used, separated by a comma 362 | deprecated-modules=optparse,tkinter.tix 363 | 364 | # Create a graph of external dependencies in the given file (report RP0402 must 365 | # not be disabled) 366 | ext-import-graph= 367 | 368 | # Create a graph of every (i.e. internal and external) dependencies in the 369 | # given file (report RP0402 must not be disabled) 370 | import-graph= 371 | 372 | # Create a graph of internal dependencies in the given file (report RP0402 must 373 | # not be disabled) 374 | int-import-graph= 375 | 376 | # Force import order to recognize a module as part of the standard 377 | # compatibility libraries. 378 | known-standard-library= 379 | 380 | # Force import order to recognize a module as part of a third party library. 381 | known-third-party=enchant 382 | 383 | 384 | [CLASSES] 385 | 386 | # List of method names used to declare (i.e. assign) instance attributes. 387 | defining-attr-methods=__init__,__new__,setUp 388 | 389 | # List of member names, which should be excluded from the protected access 390 | # warning. 391 | exclude-protected=_asdict,_fields,_replace,_source,_make 392 | 393 | # List of valid names for the first argument in a class method. 394 | valid-classmethod-first-arg=cls 395 | 396 | # List of valid names for the first argument in a metaclass class method. 397 | valid-metaclass-classmethod-first-arg=mcs 398 | 399 | 400 | [DESIGN] 401 | 402 | # Maximum number of arguments for function / method 403 | max-args=5 404 | 405 | # Maximum number of attributes for a class (see R0902). 406 | # max-attributes=7 407 | max-attributes=11 408 | 409 | # Maximum number of boolean expressions in a if statement 410 | max-bool-expr=5 411 | 412 | # Maximum number of branch for function / method body 413 | max-branches=12 414 | 415 | # Maximum number of locals for function / method body 416 | max-locals=15 417 | 418 | # Maximum number of parents for a class (see R0901). 419 | max-parents=7 420 | 421 | # Maximum number of public methods for a class (see R0904). 422 | max-public-methods=20 423 | 424 | # Maximum number of return / yield for function / method body 425 | max-returns=6 426 | 427 | # Maximum number of statements in function / method body 428 | max-statements=50 429 | 430 | # Minimum number of public methods for a class (see R0903). 431 | min-public-methods=1 432 | 433 | 434 | [EXCEPTIONS] 435 | 436 | # Exceptions that will emit a warning when being caught. Defaults to 437 | # "Exception" 438 | overgeneral-exceptions=Exception 439 | --------------------------------------------------------------------------------