├── .gitattributes ├── .github ├── PULL_REQUEST_TEMPLATE │ └── adafruit_circuitpython_pr.md └── workflows │ ├── build.yml │ ├── failure-help-text.yml │ ├── release_gh.yml │ └── release_pypi.yml ├── .gitignore ├── .pre-commit-config.yaml ├── .readthedocs.yaml ├── CODE_OF_CONDUCT.md ├── LICENSE ├── LICENSES ├── CC-BY-4.0.txt ├── MIT.txt └── Unlicense.txt ├── README.rst ├── README.rst.license ├── adafruit_ble_file_transfer.py ├── docs ├── _static │ ├── favicon.ico │ └── favicon.ico.license ├── api.rst ├── api.rst.license ├── conf.py ├── examples.rst ├── examples.rst.license ├── index.rst ├── index.rst.license └── requirements.txt ├── examples ├── ble_file_transfer_listdirs.py ├── ble_file_transfer_simpletest.py └── ble_file_transfer_stub_server.py ├── optional_requirements.txt ├── pyproject.toml ├── requirements.txt └── ruff.toml /.gitattributes: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | 5 | .py text eol=lf 6 | .rst text eol=lf 7 | .txt text eol=lf 8 | .yaml text eol=lf 9 | .toml text eol=lf 10 | .license text eol=lf 11 | .md text eol=lf 12 | -------------------------------------------------------------------------------- /.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://circuitpython.readthedocs.io/en/latest/docs/design_guide.html 8 | 9 | If your changes are to documentation, please verify that the documentation builds locally by following the steps found here: https://adafru.it/build-docs 10 | 11 | Before submitting the pull request, make sure you've run Pylint and Black locally on your code. You can do this manually or using pre-commit. Instructions are available here: https://adafru.it/check-your-code 12 | 13 | Please remove all of this text before submitting. Include an explanation or list of changes included in your PR, as well as, if applicable, a link to any related issues. 14 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | name: Build CI 6 | 7 | on: [pull_request, push] 8 | 9 | jobs: 10 | test: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Run Build CI workflow 14 | uses: adafruit/workflows-circuitpython-libs/build@main 15 | -------------------------------------------------------------------------------- /.github/workflows/failure-help-text.yml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2021 Scott Shawcroft for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | name: Failure help text 6 | 7 | on: 8 | workflow_run: 9 | workflows: ["Build CI"] 10 | types: 11 | - completed 12 | 13 | jobs: 14 | post-help: 15 | runs-on: ubuntu-latest 16 | if: ${{ github.event.workflow_run.conclusion == 'failure' && github.event.workflow_run.event == 'pull_request' }} 17 | steps: 18 | - name: Post comment to help 19 | uses: adafruit/circuitpython-action-library-ci-failed@v1 20 | -------------------------------------------------------------------------------- /.github/workflows/release_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/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 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2022 Kattni Rembor, written for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: MIT 4 | 5 | # Do not include files and directories created by your personal work environment, such as the IDE 6 | # you use, except for those already listed here. Pull requests including changes to this file will 7 | # not be accepted. 8 | 9 | # This .gitignore file contains rules for files generated by working with CircuitPython libraries, 10 | # including building Sphinx, testing with pip, and creating a virual environment, as well as the 11 | # MacOS and IDE-specific files generated by using MacOS in general, or the PyCharm or VSCode IDEs. 12 | 13 | # If you find that there are files being generated on your machine that should not be included in 14 | # your git commit, you should create a .gitignore_global file on your computer to include the 15 | # files created by your personal setup. To do so, follow the two steps below. 16 | 17 | # First, create a file called .gitignore_global somewhere convenient for you, and add rules for 18 | # the files you want to exclude from git commits. 19 | 20 | # Second, configure Git to use the exclude file for all Git repositories by running the 21 | # following via commandline, replacing "path/to/your/" with the actual path to your newly created 22 | # .gitignore_global file: 23 | # git config --global core.excludesfile path/to/your/.gitignore_global 24 | 25 | # CircuitPython-specific files 26 | *.mpy 27 | 28 | # Python-specific files 29 | __pycache__ 30 | *.pyc 31 | 32 | # Sphinx build-specific files 33 | _build 34 | 35 | # This file results from running `pip -e install .` in a local repository 36 | *.egg-info 37 | 38 | # Virtual environment-specific files 39 | .env 40 | .venv 41 | 42 | # MacOS-specific files 43 | *.DS_Store 44 | 45 | # IDE-specific files 46 | .idea 47 | .vscode 48 | *~ 49 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | 5 | repos: 6 | - repo: https://github.com/pre-commit/pre-commit-hooks 7 | rev: v4.5.0 8 | hooks: 9 | - id: check-yaml 10 | - id: end-of-file-fixer 11 | - id: trailing-whitespace 12 | - repo: https://github.com/astral-sh/ruff-pre-commit 13 | rev: v0.3.4 14 | hooks: 15 | - id: ruff-format 16 | - id: ruff 17 | args: ["--fix"] 18 | - repo: https://github.com/fsfe/reuse-tool 19 | rev: v3.0.1 20 | hooks: 21 | - id: reuse 22 | -------------------------------------------------------------------------------- /.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-20.04 16 | tools: 17 | python: "3" 18 | 19 | python: 20 | install: 21 | - requirements: docs/requirements.txt 22 | - requirements: requirements.txt 23 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2021 Scott Shawcroft 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/CC-BY-4.0.txt: -------------------------------------------------------------------------------- 1 | Creative Commons Attribution 4.0 International Creative Commons Corporation 2 | ("Creative Commons") is not a law firm and does not provide legal services 3 | or legal advice. Distribution of Creative Commons public licenses does not 4 | create a lawyer-client or other relationship. Creative Commons makes its licenses 5 | and related information available on an "as-is" basis. Creative Commons gives 6 | no warranties regarding its licenses, any material licensed under their terms 7 | and conditions, or any related information. Creative Commons disclaims all 8 | liability for damages resulting from their use to the fullest extent possible. 9 | 10 | Using Creative Commons Public Licenses 11 | 12 | Creative Commons public licenses provide a standard set of terms and conditions 13 | that creators and other rights holders may use to share original works of 14 | authorship and other material subject to copyright and certain other rights 15 | specified in the public license below. The following considerations are for 16 | informational purposes only, are not exhaustive, and do not form part of our 17 | licenses. 18 | 19 | Considerations for licensors: Our public licenses are intended for use by 20 | those authorized to give the public permission to use material in ways otherwise 21 | restricted by copyright and certain other rights. Our licenses are irrevocable. 22 | Licensors should read and understand the terms and conditions of the license 23 | they choose before applying it. Licensors should also secure all rights necessary 24 | before applying our licenses so that the public can reuse the material as 25 | expected. Licensors should clearly mark any material not subject to the license. 26 | This includes other CC-licensed material, or material used under an exception 27 | or limitation to copyright. More considerations for licensors : wiki.creativecommons.org/Considerations_for_licensors 28 | 29 | Considerations for the public: By using one of our public licenses, a licensor 30 | grants the public permission to use the licensed material under specified 31 | terms and conditions. If the licensor's permission is not necessary for any 32 | reason–for example, because of any applicable exception or limitation to copyright–then 33 | that use is not regulated by the license. Our licenses grant only permissions 34 | under copyright and certain other rights that a licensor has authority to 35 | grant. Use of the licensed material may still be restricted for other reasons, 36 | including because others have copyright or other rights in the material. A 37 | licensor may make special requests, such as asking that all changes be marked 38 | or described. Although not required by our licenses, you are encouraged to 39 | respect those requests where reasonable. More considerations for the public 40 | : wiki.creativecommons.org/Considerations_for_licensees Creative Commons Attribution 41 | 4.0 International Public License 42 | 43 | By exercising the Licensed Rights (defined below), You accept and agree to 44 | be bound by the terms and conditions of this Creative Commons Attribution 45 | 4.0 International Public License ("Public License"). To the extent this Public 46 | License may be interpreted as a contract, You are granted the Licensed Rights 47 | in consideration of Your acceptance of these terms and conditions, and the 48 | Licensor grants You such rights in consideration of benefits the Licensor 49 | receives from making the Licensed Material available under these terms and 50 | conditions. 51 | 52 | Section 1 – Definitions. 53 | 54 | a. Adapted Material means material subject to Copyright and Similar Rights 55 | that is derived from or based upon the Licensed Material and in which the 56 | Licensed Material is translated, altered, arranged, transformed, or otherwise 57 | modified in a manner requiring permission under the Copyright and Similar 58 | Rights held by the Licensor. For purposes of this Public License, where the 59 | Licensed Material is a musical work, performance, or sound recording, Adapted 60 | Material is always produced where the Licensed Material is synched in timed 61 | relation with a moving image. 62 | 63 | b. Adapter's License means the license You apply to Your Copyright and Similar 64 | Rights in Your contributions to Adapted Material in accordance with the terms 65 | and conditions of this Public License. 66 | 67 | c. Copyright and Similar Rights means copyright and/or similar rights closely 68 | related to copyright including, without limitation, performance, broadcast, 69 | sound recording, and Sui Generis Database Rights, without regard to how the 70 | rights are labeled or categorized. For purposes of this Public License, the 71 | rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. 72 | 73 | d. Effective Technological Measures means those measures that, in the absence 74 | of proper authority, may not be circumvented under laws fulfilling obligations 75 | under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, 76 | and/or similar international agreements. 77 | 78 | e. Exceptions and Limitations means fair use, fair dealing, and/or any other 79 | exception or limitation to Copyright and Similar Rights that applies to Your 80 | use of the Licensed Material. 81 | 82 | f. Licensed Material means the artistic or literary work, database, or other 83 | material to which the Licensor applied this Public License. 84 | 85 | g. Licensed Rights means the rights granted to You subject to the terms and 86 | conditions of this Public License, which are limited to all Copyright and 87 | Similar Rights that apply to Your use of the Licensed Material and that the 88 | Licensor has authority to license. 89 | 90 | h. Licensor means the individual(s) or entity(ies) granting rights under this 91 | Public License. 92 | 93 | i. Share means to provide material to the public by any means or process that 94 | requires permission under the Licensed Rights, such as reproduction, public 95 | display, public performance, distribution, dissemination, communication, or 96 | importation, and to make material available to the public including in ways 97 | that members of the public may access the material from a place and at a time 98 | individually chosen by them. 99 | 100 | j. Sui Generis Database Rights means rights other than copyright resulting 101 | from Directive 96/9/EC of the European Parliament and of the Council of 11 102 | March 1996 on the legal protection of databases, as amended and/or succeeded, 103 | as well as other essentially equivalent rights anywhere in the world. 104 | 105 | k. You means the individual or entity exercising the Licensed Rights under 106 | this Public License. Your has a corresponding meaning. 107 | 108 | Section 2 – Scope. 109 | 110 | a. License grant. 111 | 112 | 1. Subject to the terms and conditions of this Public License, the Licensor 113 | hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, 114 | irrevocable license to exercise the Licensed Rights in the Licensed Material 115 | to: 116 | 117 | A. reproduce and Share the Licensed Material, in whole or in part; and 118 | 119 | B. produce, reproduce, and Share Adapted Material. 120 | 121 | 2. Exceptions and Limitations. For the avoidance of doubt, where Exceptions 122 | and Limitations apply to Your use, this Public License does not apply, and 123 | You do not need to comply with its terms and conditions. 124 | 125 | 3. Term. The term of this Public License is specified in Section 6(a). 126 | 127 | 4. Media and formats; technical modifications allowed. The Licensor authorizes 128 | You to exercise the Licensed Rights in all media and formats whether now known 129 | or hereafter created, and to make technical modifications necessary to do 130 | so. The Licensor waives and/or agrees not to assert any right or authority 131 | to forbid You from making technical modifications necessary to exercise the 132 | Licensed Rights, including technical modifications necessary to circumvent 133 | Effective Technological Measures. For purposes of this Public License, simply 134 | making modifications authorized by this Section 2(a)(4) never produces Adapted 135 | Material. 136 | 137 | 5. Downstream recipients. 138 | 139 | A. Offer from the Licensor – Licensed Material. Every recipient of the Licensed 140 | Material automatically receives an offer from the Licensor to exercise the 141 | Licensed Rights under the terms and conditions of this Public License. 142 | 143 | B. No downstream restrictions. You may not offer or impose any additional 144 | or different terms or conditions on, or apply any Effective Technological 145 | Measures to, the Licensed Material if doing so restricts exercise of the Licensed 146 | Rights by any recipient of the Licensed Material. 147 | 148 | 6. No endorsement. Nothing in this Public License constitutes or may be construed 149 | as permission to assert or imply that You are, or that Your use of the Licensed 150 | Material is, connected with, or sponsored, endorsed, or granted official status 151 | by, the Licensor or others designated to receive attribution as provided in 152 | Section 3(a)(1)(A)(i). 153 | 154 | b. Other rights. 155 | 156 | 1. Moral rights, such as the right of integrity, are not licensed under this 157 | Public License, nor are publicity, privacy, and/or other similar personality 158 | rights; however, to the extent possible, the Licensor waives and/or agrees 159 | not to assert any such rights held by the Licensor to the limited extent necessary 160 | to allow You to exercise the Licensed Rights, but not otherwise. 161 | 162 | 2. Patent and trademark rights are not licensed under this Public License. 163 | 164 | 3. To the extent possible, the Licensor waives any right to collect royalties 165 | from You for the exercise of the Licensed Rights, whether directly or through 166 | a collecting society under any voluntary or waivable statutory or compulsory 167 | licensing scheme. In all other cases the Licensor expressly reserves any right 168 | to collect such royalties. 169 | 170 | Section 3 – License Conditions. 171 | 172 | Your exercise of the Licensed Rights is expressly made subject to the following 173 | conditions. 174 | 175 | a. Attribution. 176 | 177 | 1. If You Share the Licensed Material (including in modified form), You must: 178 | 179 | A. retain the following if it is supplied by the Licensor with the Licensed 180 | Material: 181 | 182 | i. identification of the creator(s) of the Licensed Material and any others 183 | designated to receive attribution, in any reasonable manner requested by the 184 | Licensor (including by pseudonym if designated); 185 | 186 | ii. a copyright notice; 187 | 188 | iii. a notice that refers to this Public License; 189 | 190 | iv. a notice that refers to the disclaimer of warranties; 191 | 192 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 193 | 194 | B. indicate if You modified the Licensed Material and retain an indication 195 | of any previous modifications; and 196 | 197 | C. indicate the Licensed Material is licensed under this Public License, and 198 | include the text of, or the URI or hyperlink to, this Public License. 199 | 200 | 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner 201 | based on the medium, means, and context in which You Share the Licensed Material. 202 | For example, it may be reasonable to satisfy the conditions by providing a 203 | URI or hyperlink to a resource that includes the required information. 204 | 205 | 3. If requested by the Licensor, You must remove any of the information required 206 | by Section 3(a)(1)(A) to the extent reasonably practicable. 207 | 208 | 4. If You Share Adapted Material You produce, the Adapter's License You apply 209 | must not prevent recipients of the Adapted Material from complying with this 210 | Public License. 211 | 212 | Section 4 – Sui Generis Database Rights. 213 | 214 | Where the Licensed Rights include Sui Generis Database Rights that apply to 215 | Your use of the Licensed Material: 216 | 217 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, 218 | reuse, reproduce, and Share all or a substantial portion of the contents of 219 | the database; 220 | 221 | b. if You include all or a substantial portion of the database contents in 222 | a database in which You have Sui Generis Database Rights, then the database 223 | in which You have Sui Generis Database Rights (but not its individual contents) 224 | is Adapted Material; and 225 | 226 | c. You must comply with the conditions in Section 3(a) if You Share all or 227 | a substantial portion of the contents of the database. 228 | 229 | For the avoidance of doubt, this Section 4 supplements and does not replace 230 | Your obligations under this Public License where the Licensed Rights include 231 | other Copyright and Similar Rights. 232 | 233 | Section 5 – Disclaimer of Warranties and Limitation of Liability. 234 | 235 | a. Unless otherwise separately undertaken by the Licensor, to the extent possible, 236 | the Licensor offers the Licensed Material as-is and as-available, and makes 237 | no representations or warranties of any kind concerning the Licensed Material, 238 | whether express, implied, statutory, or other. This includes, without limitation, 239 | warranties of title, merchantability, fitness for a particular purpose, non-infringement, 240 | absence of latent or other defects, accuracy, or the presence or absence of 241 | errors, whether or not known or discoverable. Where disclaimers of warranties 242 | are not allowed in full or in part, this disclaimer may not apply to You. 243 | 244 | b. To the extent possible, in no event will the Licensor be liable to You 245 | on any legal theory (including, without limitation, negligence) or otherwise 246 | for any direct, special, indirect, incidental, consequential, punitive, exemplary, 247 | or other losses, costs, expenses, or damages arising out of this Public License 248 | or use of the Licensed Material, even if the Licensor has been advised of 249 | the possibility of such losses, costs, expenses, or damages. Where a limitation 250 | of liability is not allowed in full or in part, this limitation may not apply 251 | to You. 252 | 253 | c. The disclaimer of warranties and limitation of liability provided above 254 | shall be interpreted in a manner that, to the extent possible, most closely 255 | approximates an absolute disclaimer and waiver of all liability. 256 | 257 | Section 6 – Term and Termination. 258 | 259 | a. This Public License applies for the term of the Copyright and Similar Rights 260 | licensed here. However, if You fail to comply with this Public License, then 261 | Your rights under this Public License terminate automatically. 262 | 263 | b. Where Your right to use the Licensed Material has terminated under Section 264 | 6(a), it reinstates: 265 | 266 | 1. automatically as of the date the violation is cured, provided it is cured 267 | within 30 days of Your discovery of the violation; or 268 | 269 | 2. upon express reinstatement by the Licensor. 270 | 271 | c. For the avoidance of doubt, this Section 6(b) does not affect any right 272 | the Licensor may have to seek remedies for Your violations of this Public 273 | License. 274 | 275 | d. For the avoidance of doubt, the Licensor may also offer the Licensed Material 276 | under separate terms or conditions or stop distributing the Licensed Material 277 | at any time; however, doing so will not terminate this Public License. 278 | 279 | e. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 280 | 281 | Section 7 – Other Terms and Conditions. 282 | 283 | a. The Licensor shall not be bound by any additional or different terms or 284 | conditions communicated by You unless expressly agreed. 285 | 286 | b. Any arrangements, understandings, or agreements regarding the Licensed 287 | Material not stated herein are separate from and independent of the terms 288 | and conditions of this Public License. 289 | 290 | Section 8 – Interpretation. 291 | 292 | a. For the avoidance of doubt, this Public License does not, and shall not 293 | be interpreted to, reduce, limit, restrict, or impose conditions on any use 294 | of the Licensed Material that could lawfully be made without permission under 295 | this Public License. 296 | 297 | b. To the extent possible, if any provision of this Public License is deemed 298 | unenforceable, it shall be automatically reformed to the minimum extent necessary 299 | to make it enforceable. If the provision cannot be reformed, it shall be severed 300 | from this Public License without affecting the enforceability of the remaining 301 | terms and conditions. 302 | 303 | c. No term or condition of this Public License will be waived and no failure 304 | to comply consented to unless expressly agreed to by the Licensor. 305 | 306 | d. Nothing in this Public License constitutes or may be interpreted as a limitation 307 | upon, or waiver of, any privileges and immunities that apply to the Licensor 308 | or You, including from the legal processes of any jurisdiction or authority. 309 | 310 | Creative Commons is not a party to its public licenses. Notwithstanding, Creative 311 | Commons may elect to apply one of its public licenses to material it publishes 312 | and in those instances will be considered the "Licensor." The text of the 313 | Creative Commons public licenses is dedicated to the public domain under the 314 | CC0 Public Domain Dedication. Except for the limited purpose of indicating 315 | that material is shared under a Creative Commons public license or as otherwise 316 | permitted by the Creative Commons policies published at creativecommons.org/policies, 317 | Creative Commons does not authorize the use of the trademark "Creative Commons" 318 | or any other trademark or logo of Creative Commons without its prior written 319 | consent including, without limitation, in connection with any unauthorized 320 | modifications to any of its public licenses or any other arrangements, understandings, 321 | or agreements concerning use of licensed material. For the avoidance of doubt, 322 | this paragraph does not form part of the public licenses. 323 | 324 | Creative Commons may be contacted at creativecommons.org. 325 | -------------------------------------------------------------------------------- /LICENSES/MIT.txt: -------------------------------------------------------------------------------- 1 | MIT License Copyright (c) 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is furnished 8 | to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice (including the next 11 | paragraph) shall be included in all copies or substantial portions of the 12 | Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 16 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 17 | OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 18 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF 19 | OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /LICENSES/Unlicense.txt: -------------------------------------------------------------------------------- 1 | This is free and unencumbered software released into the public domain. 2 | 3 | Anyone is free to copy, modify, publish, use, compile, sell, or distribute 4 | this software, either in source code form or as a compiled binary, for any 5 | purpose, commercial or non-commercial, and by any means. 6 | 7 | In jurisdictions that recognize copyright laws, the author or authors of this 8 | software dedicate any and all copyright interest in the software to the public 9 | domain. We make this dedication for the benefit of the public at large and 10 | to the detriment of our heirs and successors. We intend this dedication to 11 | be an overt act of relinquishment in perpetuity of all present and future 12 | rights to this software under copyright law. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 16 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS 17 | BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 18 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH 19 | THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, 20 | please refer to 21 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Introduction 2 | ============ 3 | 4 | 5 | .. image:: https://readthedocs.org/projects/adafruit-circuitpython-ble_file_transfer/badge/?version=latest 6 | :target: https://docs.circuitpython.org/projects/ble_file_transfer/en/latest/ 7 | :alt: Documentation Status 8 | 9 | 10 | .. image:: https://github.com/adafruit/Adafruit_CircuitPython_Bundle/blob/main/badges/adafruit_discord.svg 11 | :target: https://adafru.it/discord 12 | :alt: Discord 13 | 14 | 15 | .. image:: https://github.com/adafruit/Adafruit_CircuitPython_BLE_File_Transfer/workflows/Build%20CI/badge.svg 16 | :target: https://github.com/adafruit/Adafruit_CircuitPython_BLE_File_Transfer/actions 17 | :alt: Build Status 18 | 19 | 20 | .. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json 21 | :target: https://github.com/astral-sh/ruff 22 | :alt: Code Style: Ruff 23 | 24 | Simple BLE Service for reading and writing files over BLE. This BLE service is geared towards file 25 | transfer to and from a device running the service. A core part of the protocol is free space 26 | responses so that the server can be a memory limited device. The free space responses allow for 27 | small buffer sizes that won't be overwhelmed by the client. 28 | 29 | 30 | Dependencies 31 | ============= 32 | This driver depends on: 33 | 34 | * `Adafruit CircuitPython `_ 35 | 36 | Please ensure all dependencies are available on the CircuitPython filesystem. 37 | This is easily achieved by downloading 38 | `the Adafruit library and driver bundle `_ 39 | or individual libraries can be installed using 40 | `circup `_. 41 | 42 | 43 | Installing from PyPI 44 | ===================== 45 | 46 | On supported GNU/Linux systems like the Raspberry Pi, you can install the driver locally `from 47 | PyPI `_. 48 | To install for current user: 49 | 50 | .. code-block:: shell 51 | 52 | pip3 install adafruit-circuitpython-ble-file-transfer 53 | 54 | To install system-wide (this may be required in some cases): 55 | 56 | .. code-block:: shell 57 | 58 | sudo pip3 install adafruit-circuitpython-ble-file-transfer 59 | 60 | To install in a virtual environment in your current project: 61 | 62 | .. code-block:: shell 63 | 64 | mkdir project-name && cd project-name 65 | python3 -m venv .venv 66 | source .venv/bin/activate 67 | pip3 install adafruit-circuitpython-ble-file-transfer 68 | 69 | 70 | 71 | Usage Examples 72 | ============== 73 | 74 | See `examples/ble_file_transfer_simpletest.py `_ for a client example. A stub server implementation is in `examples/ble_file_transfer_stub_server.py `_. 75 | 76 | Protocol 77 | ========= 78 | 79 | The file transfer protocol is meant to be simple and easy to implement. It uses free space counts as a way to rate limit file content data transfer. All multi-byte numbers are encoded with the least significant byte first ("<" in CPython's struct module). 80 | 81 | GATT Service 82 | -------------- 83 | 84 | The UUID of the service is ``0xfebb``, Adafruit's 16-bit service UUID. 85 | 86 | The base UUID used in characteristics is ``ADAFxxxx-4669-6C65-5472-616E73666572``. The 16-bit numbers below are substituted into the ``xxxx`` portion. 87 | 88 | The service has two characteristics: 89 | 90 | * version (``0x0100``) - Simple unsigned 32-bit integer version number. May be 1 - 4. 91 | * raw transfer (``0x0200``) - Bidirectional link with a custom protocol. The client does WRITE_NO_RESPONSE to the characteristic and then server replies via NOTIFY. (This is similar to the Nordic UART Service but on a single characteristic rather than two.) The commands over the transfer characteristic are idempotent and stateless. A disconnect during a command will reset the state. 92 | 93 | Time resolution 94 | --------------- 95 | 96 | Time resolution varies based filesystem type. FATFS can only get down to the 2 second bound after 1980. Littlefs can do 64-bit nanoseconds after January 1st, 1970. 97 | 98 | To account for this, the protocol has time in 64-bit nanoseconds after January 1st, 1970. However, the server will respond with a potentially truncated version that is the value stored. 99 | 100 | Also note that devices serving the file transfer protocol may not have it's own clock so do not rely on time ordering. Any internal writes may set the time incorrectly. So, we only recommend using the value as a cache key. 101 | 102 | Commands 103 | --------- 104 | 105 | Commands always start with a fixed header. The first entry is always the command number itself encoded in a single byte. The number of subsequent entries in the header will vary by command. The entire header must be sent as a unit so set the characteristic with the full header packet. You can combine multiple commands into a single write as long as the complete header is in the packet. 106 | 107 | Paths use ``/`` as a separator and full paths must start with ``/``. 108 | 109 | All numbers are unsigned. 110 | 111 | All values are aligned with respect to the start of the packet. 112 | 113 | Status bytes are ``0x01`` for OK and ``0x02`` for error. Values other than ``0x01`` are errors. ``0x00`` should not be used for a specific error but still considered an error. ``0x05`` is an error for trying to modify a read-only filesystem. 114 | 115 | ``0x10`` - Read a file 116 | ++++++++++++++++++++++ 117 | 118 | Given a full path, returns the full contents of the file. 119 | 120 | The header is four fixed entries and a variable length path: 121 | 122 | * Command: Single byte. Always ``0x10``. 123 | * 1 Byte reserved for padding. 124 | * Path length: 16-bit number encoding the encoded length of the path string. 125 | * Chunk offset: 32-bit number encoding the offset into the file to start the first chunk. 126 | * Chunk size: 32-bit number encoding the amount of data that the client can handle in the first reply. 127 | * Path: UTF-8 encoded string that is *not* null terminated. (We send the length instead.) 128 | 129 | The server will respond with: 130 | 131 | * Command: Single byte. Always ``0x11``. 132 | * Status: Single byte. 133 | * 2 Bytes reserved for padding. 134 | * Chunk offset: 32-bit number encoding the offset into the file of this chunk. 135 | * Total length: 32-bit number encoding the total file length. 136 | * Chunk length: 32-bit number encoding the length of the read data up to the chunk size provided in the header. 137 | * Chunk-length contents of the file starting from the current position. 138 | 139 | If the chunk length is smaller than the total length, then the client will request more data by sending: 140 | 141 | * Command: Single byte. Always ``0x12``. 142 | * Status: Single byte. Always OK for now. 143 | * 2 Bytes reserved for padding. 144 | * Chunk offset: 32-bit number encoding the offset into the file to start the next chunk. 145 | * Chunk size: 32-bit number encoding the number of bytes to read. May be different than the original size. Does not need to be limited by the total size. 146 | 147 | The transaction is complete after the server has replied with all data. (No acknowledgement needed from the client.) 148 | 149 | ``0x20`` - Write a file 150 | +++++++++++++++++++++++ 151 | 152 | Writes the content to the given full path. If the file exists, it will be overwritten. Content may be written as received so an interrupted transfer may lead to a truncated file. 153 | 154 | Offset larger than the existing file size will introduce zeros into the gap. 155 | 156 | The header is four fixed entries and a variable length path: 157 | 158 | * Command: Single byte. Always ``0x20``. 159 | * 1 Byte reserved for padding. 160 | * Path length: 16-bit number encoding the encoded length of the path string. 161 | * Offset: 32-bit number encoding the starting offset to write. 162 | * Current time: 64-bit number encoding nanoseconds since January 1st, 1970. Used as the file modification time. Not all system will support the full resolution. Use the truncated time response value for caching. 163 | * Total size: 32-bit number encoding the total length of the file contents. 164 | * Path: UTF-8 encoded string that is *not* null terminated. (We send the length instead.) 165 | 166 | The server will repeatedly respond until the total length has been transferred with: 167 | 168 | * Command: Single byte. Always ``0x21``. 169 | * Status: Single byte. ``0x01`` if OK. ``0x05`` if the filesystem is read-only. ``0x02`` if any parent directory is missing or a file. 170 | * 2 Bytes reserved for padding. 171 | * Offset: 32-bit number encoding the starting offset to write. (Should match the offset from the previous 0x20 or 0x22 message) 172 | * Truncated time: 64-bit number encoding nanoseconds since January 1st, 1970 as stored by the file system. The resolution may be less that the protocol. It is sent back for use in caching on the host side. 173 | * Free space: 32-bit number encoding the amount of data the client can send. 174 | 175 | The client will repeatedly respond until the total length has been transferred with: 176 | 177 | * Command: Single byte. Always ``0x22``. 178 | * Status: Single byte. Always ``0x01`` for OK. 179 | * 2 Bytes reserved for padding. 180 | * Offset: 32-bit number encoding the offset to write. 181 | * Data size: 32-bit number encoding the amount of data the client is sending. 182 | * Data 183 | 184 | The transaction is complete after the server has received all data and replied with a status with 0 free space and offset set to the content length. 185 | 186 | **NOTE**: Current time was added in version 3. The rest of the packets remained the same. 187 | 188 | 189 | ``0x30`` - Delete a file or directory 190 | +++++++++++++++++++++++++++++++++++++ 191 | 192 | Deletes the file or directory at the given full path. Non-empty directories will have their contents deleted as well. 193 | 194 | The header is two fixed entries and a variable length path: 195 | 196 | * Command: Single byte. Always ``0x30``. 197 | * 1 Byte reserved for padding. 198 | * Path length: 16-bit number encoding the encoded length of the path string. 199 | * Path: UTF-8 encoded string that is *not* null terminated. (We send the length instead.) 200 | 201 | The server will reply with: 202 | 203 | * Command: Single byte. Always ``0x31``. 204 | * Status: Single byte. ``0x01`` if the file or directory was deleted, ``0x05`` if the filesystem is read-only or ``0x02`` if the path is non-existent. 205 | 206 | **NOTE**: In version 2, this command now deletes contents of a directory as well. It won't error. 207 | 208 | ``0x40`` - Make a directory 209 | +++++++++++++++++++++++++++ 210 | 211 | Creates a new directory at the given full path. If a parent directory does not exist, then it will also be created. If any name conflicts with an existing file, an error will be returned. 212 | 213 | The header is two fixed entries and a variable length path: 214 | 215 | * Command: Single byte. Always ``0x40``. 216 | * 1 Byte reserved for padding. 217 | * Path length: 16-bit number encoding the encoded length of the path string. 218 | * 4 Bytes reserved for padding. 219 | * Current time: 64-bit number encoding nanoseconds since January 1st, 1970. Used as the file modification time. Not all system will support the full resolution. Use the truncated time response value for caching. 220 | * Path: UTF-8 encoded string that is *not* null terminated. (We send the length instead.) 221 | 222 | The server will reply with: 223 | 224 | * Command: Single byte. Always ``0x41``. 225 | * Status: Single byte. ``0x01`` if the directory(s) were created, ``0x05`` if the filesystem is read-only or ``0x02`` if any parent of the path is an existing file. 226 | * 6 Bytes reserved for padding. 227 | * Truncated time: 64-bit number encoding nanoseconds since January 1st, 1970 as stored by the file system. The resolution may be less that the protocol. It is sent back for use in caching on the host side. 228 | 229 | ``0x50`` - List a directory 230 | +++++++++++++++++++++++++++ 231 | 232 | Lists all of the contents in a directory given a full path. Returned paths are *relative* to the given path to reduce duplication. 233 | 234 | The header is two fixed entries and a variable length path: 235 | 236 | * Command: Single byte. Always ``0x50``. 237 | * 1 Byte reserved for padding. 238 | * Path length: 16-bit number encoding the encoded length of the path string. 239 | * Path: UTF-8 encoded string that is *not* null terminated. (We send the length instead.) 240 | 241 | The server will reply with n+1 entries for a directory with n files: 242 | 243 | * Command: Single byte. Always ``0x51``. 244 | * Status: Single byte. ``0x01`` if the directory exists or ``0x02`` if it doesn't. 245 | * Path length: 16-bit number encoding the encoded length of the path string. 246 | * Entry number: 32-bit number encoding the entry number. 247 | * Total entries: 32-bit number encoding the total number of entries. 248 | * Flags: 32-bit number encoding data about the entries. 249 | 250 | - Bit 0: Set when the entry is a directory 251 | - Bits 1-7: Reserved 252 | 253 | * Modification time: 64-bit number of nanoseconds since January 1st, 1970. *However*, files modifiers may not have an accurate clock so do *not* assume it is correct. Instead, only use it to determine cacheability vs a local copy. 254 | * File size: 32-bit number encoding the size of the file. Ignore for directories. Value may change. 255 | * Path: UTF-8 encoded string that is *not* null terminated. (We send the length instead.) These paths are relative so they won't contain ``/`` at all. 256 | 257 | The transaction is complete when the final entry is sent from the server. It will have entry number == total entries and zeros for flags, file size and path length. 258 | 259 | ``0x60`` - Move a file or directory 260 | +++++++++++++++++++++++++++++++++++ 261 | 262 | Moves a file or directory at a given path to a different path. Can be used to 263 | rename as well. The two paths are sent separated by a byte so that the server 264 | may null-terminate the string itself. The client may send anything there. 265 | 266 | The header is two fixed entries and a variable length path: 267 | 268 | * Command: Single byte. Always ``0x60``. 269 | * 1 Byte reserved for padding. 270 | * Old Path length: 16-bit number encoding the encoded length of the path string. 271 | * New Path length: 16-bit number encoding the encoded length of the path string. 272 | * Old Path: UTF-8 encoded string that is *not* null terminated. (We send the length instead.) 273 | * One padding byte. This can be used to null terminate the old path string. 274 | * New Path: UTF-8 encoded string that is *not* null terminated. (We send the length instead.) 275 | 276 | The server will reply with: 277 | 278 | * Command: Single byte. Always ``0x61``. 279 | * Status: Single byte. ``0x01`` on success, ``0x05`` if read-only, or ``0x02`` on other error. 280 | 281 | **NOTE**: This is added in version 4. 282 | 283 | Versions 284 | ========= 285 | 286 | Version 2 287 | --------- 288 | * Changes delete to delete contents of non-empty directories automatically. 289 | 290 | Version 3 291 | --------- 292 | * Adds modification time. 293 | * Adds current time to file write command. 294 | * Adds current time to make directory command. 295 | * Adds modification time to directory listing entries. 296 | 297 | Version 4 298 | --------- 299 | * Adds move command. 300 | * Adds 0x05 error for read-only filesystems. This is commonly that USB is editing the same filesystem. 301 | * Removes requirement that directory paths end with /. 302 | 303 | Contributing 304 | ============ 305 | 306 | Contributions are welcome! Please read our `Code of Conduct 307 | `_ 308 | before contributing to help this project stay welcoming. 309 | 310 | Documentation 311 | ============= 312 | 313 | For information on building library documentation, please check out 314 | `this guide `_. 315 | -------------------------------------------------------------------------------- /README.rst.license: -------------------------------------------------------------------------------- 1 | SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries 3 | SPDX-License-Identifier: MIT 4 | -------------------------------------------------------------------------------- /adafruit_ble_file_transfer.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | # SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries 3 | # 4 | # SPDX-License-Identifier: MIT 5 | """ 6 | `adafruit_ble_file_transfer` 7 | ================================================================================ 8 | 9 | Simple BLE Service for reading and writing files over BLE 10 | 11 | 12 | * Author(s): Scott Shawcroft 13 | """ 14 | 15 | import struct 16 | import time 17 | 18 | import _bleio 19 | from adafruit_ble.attributes import Attribute 20 | from adafruit_ble.characteristics import Characteristic, ComplexCharacteristic 21 | from adafruit_ble.characteristics.int import Uint32Characteristic 22 | from adafruit_ble.services import Service 23 | from adafruit_ble.uuid import StandardUUID, VendorUUID 24 | 25 | try: 26 | from typing import List, Optional 27 | 28 | from circuitpython_typing import ReadableBuffer, WriteableBuffer 29 | except ImportError: 30 | pass 31 | 32 | __version__ = "0.0.0+auto.0" 33 | __repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_BLE_File_Transfer.git" 34 | 35 | CHUNK_SIZE = 490 36 | 37 | 38 | class FileTransferUUID(VendorUUID): 39 | """UUIDs with the CircuitPython base UUID.""" 40 | 41 | def __init__(self, uuid16: int) -> None: 42 | uuid128 = bytearray(b"refsnarTeliF" + b"\x00\x00\xaf\xad") 43 | uuid128[-3] = uuid16 >> 8 44 | uuid128[-4] = uuid16 & 0xFF 45 | super().__init__(uuid128) 46 | 47 | 48 | class _TransferCharacteristic(ComplexCharacteristic): 49 | """Endpoint for sending commands to a media player. The value read will list all available 50 | commands.""" 51 | 52 | uuid = FileTransferUUID(0x0200) 53 | 54 | def __init__(self) -> None: 55 | super().__init__( 56 | properties=Characteristic.WRITE_NO_RESPONSE 57 | | Characteristic.READ 58 | | Characteristic.NOTIFY, 59 | read_perm=Attribute.ENCRYPT_NO_MITM, 60 | write_perm=Attribute.ENCRYPT_NO_MITM, 61 | max_length=512, 62 | fixed_length=False, 63 | ) 64 | 65 | def bind(self, service: "FileTransferService") -> _bleio.PacketBuffer: 66 | """Binds the characteristic to the given Service.""" 67 | bound_characteristic = super().bind(service) 68 | return _bleio.PacketBuffer(bound_characteristic, buffer_size=4, max_packet_size=512) 69 | 70 | 71 | class FileTransferService(Service): 72 | """Simple (not necessarily fast) BLE file transfer service. It implements basic CRUD operations. 73 | 74 | The server dictates data transfer chunk sizes so it can minimize buffer sizes on its end. 75 | """ 76 | 77 | uuid = StandardUUID(0xFEBB) 78 | version = Uint32Characteristic(uuid=FileTransferUUID(0x0100), initial_value=4) 79 | raw = _TransferCharacteristic() 80 | # _raw gets shadowed for each MIDIService instance by a PacketBuffer. 81 | 82 | # Commands 83 | INVALID = 0x00 84 | READ = 0x10 85 | READ_DATA = 0x11 86 | READ_PACING = 0x12 87 | WRITE = 0x20 88 | WRITE_PACING = 0x21 89 | WRITE_DATA = 0x22 90 | DELETE = 0x30 91 | DELETE_STATUS = 0x31 92 | MKDIR = 0x40 93 | MKDIR_STATUS = 0x41 94 | LISTDIR = 0x50 95 | LISTDIR_ENTRY = 0x51 96 | MOVE = 0x60 97 | MOVE_STATUS = 0x61 98 | 99 | # Responses 100 | # 0x00 is INVALID 101 | OK = 0x01 102 | ERROR = 0x02 103 | ERROR_NO_FILE = 0x03 104 | ERROR_PROTOCOL = 0x04 105 | 106 | # Flags 107 | DIRECTORY = 0x01 108 | 109 | 110 | class ProtocolError(BaseException): 111 | """Error thrown when expected bytes don't match""" 112 | 113 | 114 | class FileTransferClient: 115 | """Helper class to communicating with a File Transfer server""" 116 | 117 | def __init__(self, service: Service) -> None: 118 | self._service = service 119 | 120 | if service.version < 3: 121 | raise RuntimeError("Service on other device too old") 122 | 123 | def _write(self, buffer: ReadableBuffer) -> None: 124 | # print("write", binascii.hexlify(buffer)) 125 | sent = 0 126 | while sent < len(buffer): 127 | remaining = len(buffer) - sent 128 | next_send = min(self._service.raw.outgoing_packet_length, remaining) 129 | self._service.raw.write(buffer[sent : sent + next_send]) 130 | sent += next_send 131 | 132 | def _readinto(self, buffer: WriteableBuffer) -> bytearray: 133 | read = 0 134 | long_buffer = bytearray(512) 135 | # Read back how much we can write 136 | while read == 0: 137 | try: 138 | read = self._service.raw.readinto(buffer) 139 | except ValueError: 140 | read = self._service.raw.readinto(long_buffer) 141 | buffer[:read] = long_buffer[:read] 142 | return read 143 | 144 | def read(self, path: str, *, offset: int = 0) -> bytearray: 145 | """Returns the contents of the file at the given path starting at the given offset""" 146 | path = path.encode("utf-8") 147 | chunk_size = CHUNK_SIZE 148 | start_offset = offset 149 | encoded = ( 150 | struct.pack(" int: 211 | """Writes the given contents to the given path starting at the given offset. 212 | Returns the trunctated modification time. 213 | 214 | If the file is shorter than the offset, zeros will be added in the gap.""" 215 | path = path.encode("utf-8") 216 | total_length = len(contents) + offset 217 | if modification_time is None: 218 | modification_time = int(time.time() * 1_000_000_000) 219 | encoded = ( 220 | struct.pack( 221 | " int: 271 | """Makes the directory and any missing parents. Returns the truncated time""" 272 | path = path.encode("utf-8") 273 | if modification_time is None: 274 | modification_time = int(time.time() * 1_000_000_000) 275 | encoded = ( 276 | struct.pack(" List[tuple]: 290 | """Returns a list of tuples, one tuple for each file or directory in the given path""" 291 | paths = [] 292 | path = path.encode("utf-8") 293 | encoded = struct.pack(" 0: 310 | path = str( 311 | encoded_path, 312 | "utf-8", 313 | ) 314 | paths.append((path, file_size, flags, modification_time)) 315 | ( 316 | cmd, 317 | status, 318 | path_length, 319 | i, 320 | total, 321 | flags, 322 | modification_time, 323 | file_size, 324 | ) = struct.unpack_from("= total: 332 | break 333 | 334 | path_read = min(path_length - len(encoded_path), read - offset) 335 | encoded_path += b[offset : offset + path_read] 336 | offset += path_read 337 | return paths 338 | 339 | def delete(self, path: str) -> None: 340 | """Deletes the file or directory at the given path.""" 341 | path = path.encode("utf-8") 342 | encoded = struct.pack(" None: 354 | """Moves the file or directory from old_path to new_path.""" 355 | if self._service.version < 4: 356 | raise RuntimeError("Service on other device too old") 357 | old_path = old_path.encode("utf-8") 358 | new_path = new_path.encode("utf-8") 359 | encoded = ( 360 | struct.pack(" 34 | Download Library Bundle 35 | CircuitPython Reference Documentation 36 | CircuitPython Support Forum 37 | Discord Chat 38 | Adafruit Learning System 39 | Adafruit Blog 40 | Adafruit Store 41 | 42 | Indices and tables 43 | ================== 44 | 45 | * :ref:`genindex` 46 | * :ref:`modindex` 47 | * :ref:`search` 48 | -------------------------------------------------------------------------------- /docs/index.rst.license: -------------------------------------------------------------------------------- 1 | SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries 2 | SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries 3 | 4 | SPDX-License-Identifier: MIT 5 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /examples/ble_file_transfer_listdirs.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2020 ladyada for Adafruit Industries 2 | # SPDX-License-Identifier: MIT 3 | 4 | """ 5 | Used with ble_uart_echo_test.py. Transmits "echo" to the UARTService and receives it back. 6 | """ 7 | 8 | import sys 9 | 10 | from adafruit_ble import BLERadio 11 | from adafruit_ble.advertising.standard import ( 12 | Advertisement, 13 | ProvideServicesAdvertisement, 14 | ) 15 | 16 | import adafruit_ble_file_transfer 17 | 18 | # Connect to a file transfer device 19 | ble = BLERadio() 20 | connection = None 21 | print("disconnected, scanning") 22 | for advertisement in ble.start_scan(ProvideServicesAdvertisement, Advertisement, timeout=1): 23 | # print(advertisement.address, advertisement.address.type) 24 | if ( 25 | not hasattr(advertisement, "services") 26 | or adafruit_ble_file_transfer.FileTransferService not in advertisement.services 27 | ): 28 | continue 29 | connection = ble.connect(advertisement) 30 | peer_address = advertisement.address 31 | print("connected to", advertisement.address) 32 | break 33 | ble.stop_scan() 34 | 35 | if not connection: 36 | print("No advertisement found") 37 | sys.exit(1) 38 | 39 | # Prep the connection 40 | if adafruit_ble_file_transfer.FileTransferService not in connection: 41 | print("Connected device missing file transfer service") 42 | sys.exit(1) 43 | if not connection.paired: 44 | print("pairing") 45 | connection.pair() 46 | print("paired") 47 | print() 48 | service = connection[adafruit_ble_file_transfer.FileTransferService] 49 | client = adafruit_ble_file_transfer.FileTransferClient(service) 50 | 51 | # Do the file operations 52 | print(client.listdir("/")) 53 | print(client.listdir("/lib/")) 54 | -------------------------------------------------------------------------------- /examples/ble_file_transfer_simpletest.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: 2020 ladyada for Adafruit Industries 2 | # SPDX-License-Identifier: MIT 3 | 4 | """ 5 | Used with ble_uart_echo_test.py. Transmits "echo" to the UARTService and receives it back. 6 | """ 7 | 8 | import binascii 9 | import random 10 | import time 11 | 12 | from adafruit_ble import BLERadio 13 | from adafruit_ble.advertising.standard import ( 14 | Advertisement, 15 | ProvideServicesAdvertisement, 16 | ) 17 | 18 | import adafruit_ble_file_transfer 19 | 20 | 21 | def _write(client, filename, contents, *, offset=0): 22 | start = time.monotonic() 23 | try: 24 | client.write(filename, contents, offset=offset) 25 | duration = time.monotonic() - start 26 | client = wait_for_reconnect() 27 | except RuntimeError: 28 | print("write failed. is usb connected?") 29 | return client 30 | print("wrote", filename, "at rate", len(contents) / duration, "B/s") 31 | return client 32 | 33 | 34 | def _read(client, filename, *, offset=0): 35 | start = time.monotonic() 36 | try: 37 | contents = client.read(filename, offset=offset) 38 | duration = time.monotonic() - start 39 | except ValueError: 40 | print("missing file:", filename) 41 | return b"" 42 | print("read", filename, "at rate", len(contents) / duration, "B/s") 43 | return contents 44 | 45 | 46 | ble = BLERadio() 47 | 48 | peer_address = None 49 | 50 | 51 | def wait_for_reconnect(): 52 | print("reconnecting", end="") 53 | while ble.connected: 54 | pass 55 | print(".", end="") 56 | new_connection = ble.connect(peer_address) 57 | print(".", end="") 58 | if not new_connection.paired: 59 | print(".", end="") 60 | new_connection.pair() 61 | new_service = new_connection[adafruit_ble_file_transfer.FileTransferService] 62 | new_client = adafruit_ble_file_transfer.FileTransferClient(new_service) 63 | print(".", end="") 64 | time.sleep(2) 65 | print("done") 66 | return new_client 67 | 68 | 69 | # ble._adapter.erase_bonding() 70 | # print("erased") 71 | while True: 72 | try: 73 | while ble.connected: 74 | for connection in ble.connections: 75 | if adafruit_ble_file_transfer.FileTransferService not in connection: 76 | continue 77 | if not connection.paired: 78 | print("pairing") 79 | connection.pair() 80 | print("paired") 81 | print() 82 | service = connection[adafruit_ble_file_transfer.FileTransferService] 83 | client = adafruit_ble_file_transfer.FileTransferClient(service) 84 | 85 | print("Testing write") 86 | client = _write(client, "/hello.txt", b"Hello world") 87 | time.sleep(1) 88 | c = _read(client, "/hello.txt") 89 | print(len(c), c) 90 | print() 91 | 92 | print("Testing mkdir") 93 | try: 94 | client.mkdir("/world/") 95 | except ValueError: 96 | print("path exists or isn't valid") 97 | print(client.listdir("/")) 98 | print(client.listdir("/world/")) 99 | print() 100 | 101 | print("Test writing within dir") 102 | client = _write(client, "/world/hi.txt", b"Hi world") 103 | 104 | hello_world = b"Hello world" 105 | client = _write(client, "/world/hello.txt", hello_world) 106 | c = _read(client, "/world/hello.txt") 107 | print(c) 108 | print() 109 | 110 | # Test offsets 111 | print("Testing offsets") 112 | hello = len(b"Hello ") 113 | c = _read(client, "/world/hello.txt", offset=hello) 114 | print(c) 115 | 116 | client = _write(client, "/world/hello.txt", b"offsets!", offset=hello) 117 | c = _read(client, "/world/hello.txt", offset=0) 118 | print(c) 119 | print() 120 | 121 | # Test deleting 122 | print("Testing delete in /world/") 123 | print(client.listdir("/world/")) 124 | try: 125 | client.delete("/world/hello.txt") 126 | except ValueError: 127 | print("delete failed") 128 | 129 | try: 130 | client.delete("/world/") 131 | print("deleted /world/") 132 | except ValueError: 133 | print("delete failed") 134 | print(client.listdir("/world/")) 135 | try: 136 | client.delete("/world/hi.txt") 137 | except ValueError: 138 | pass 139 | try: 140 | client.delete("/world/") 141 | except ValueError: 142 | pass 143 | print() 144 | 145 | # Test move 146 | print("Testing move") 147 | print(client.listdir("/")) 148 | try: 149 | client.move("/hello.txt", "/world/hi.txt") 150 | except ValueError: 151 | pass 152 | try: 153 | client.move("/hello.txt", "/hi.txt") 154 | except ValueError: 155 | print("move failed") 156 | print(client.listdir("/")) 157 | client.delete("/hi.txt") 158 | print() 159 | 160 | # Test larger files 161 | print("Testing larger files") 162 | large_1k = bytearray(1024) 163 | for i, _ in enumerate(large_1k): 164 | large_1k[i] = random.randint(0, 255) 165 | client = _write(client, "/random.txt", large_1k) 166 | contents = _read(client, "/random.txt") 167 | if large_1k != contents: 168 | print(binascii.hexlify(large_1k)) 169 | print(binascii.hexlify(contents)) 170 | raise RuntimeError("large contents don't match!") 171 | print() 172 | time.sleep(20) 173 | except ConnectionError: 174 | pass 175 | 176 | print("disconnected, scanning") 177 | for advertisement in ble.start_scan(ProvideServicesAdvertisement, Advertisement, timeout=1): 178 | # print(advertisement.address, advertisement.address.type) 179 | if ( 180 | not hasattr(advertisement, "services") 181 | or adafruit_ble_file_transfer.FileTransferService not in advertisement.services 182 | ): 183 | continue 184 | ble.connect(advertisement) 185 | peer_address = advertisement.address 186 | print("connected to", advertisement.address) 187 | break 188 | ble.stop_scan() 189 | -------------------------------------------------------------------------------- /examples/ble_file_transfer_stub_server.py: -------------------------------------------------------------------------------- 1 | # SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries 2 | # 3 | # SPDX-License-Identifier: Unlicense 4 | 5 | """This example broadcasts out the creation id based on the CircuitPython machine 6 | string and provides a stub FileTransferService.""" 7 | 8 | import binascii 9 | import os 10 | import struct 11 | import time 12 | 13 | import adafruit_ble 14 | import adafruit_ble_creation 15 | 16 | import adafruit_ble_file_transfer 17 | from adafruit_ble_file_transfer import FileTransferService 18 | 19 | cid = adafruit_ble_creation.creation_ids[os.uname().machine] 20 | 21 | ble = adafruit_ble.BLERadio() 22 | # ble._adapter.erase_bonding() 23 | 24 | service = FileTransferService() 25 | print(ble.name) 26 | advert = adafruit_ble_creation.Creation(creation_id=cid, services=[service]) 27 | print(binascii.hexlify(bytes(advert)), len(bytes(advert))) 28 | 29 | CHUNK_SIZE = 4000 30 | 31 | stored_data = {} 32 | # path to timestamp, no nesting 33 | stored_timestamps = {} 34 | 35 | 36 | def find_dir(full_path): 37 | parts = full_path.split("/") 38 | parent_dir = stored_data 39 | k = 1 40 | while k < len(parts) - 1: 41 | part = parts[k] 42 | if part not in parent_dir: 43 | return None 44 | parent_dir = parent_dir[part] 45 | k += 1 46 | return parent_dir 47 | 48 | 49 | def read_packets(buf, *, target_size=None): 50 | if not target_size: 51 | target_size = len(buf) 52 | total_read = 0 53 | buf = memoryview(buf) 54 | while total_read < target_size: 55 | count = service.raw.readinto(buf[total_read:]) 56 | total_read += count 57 | 58 | return total_read 59 | 60 | 61 | def write_packets(buf): 62 | packet_length = service.raw.outgoing_packet_length 63 | if len(buf) <= packet_length: 64 | service.raw.write(buf) 65 | return 66 | 67 | full_packet = memoryview(bytearray(packet_length)) 68 | sent = 0 69 | while offset < len(buf): 70 | this_packet = full_packet[: len(buf) - sent] 71 | for k in range(len(this_packet)): 72 | this_packet[k] = buf[sent + k] 73 | sent += len(this_packet) 74 | service.raw.write(this_packet) 75 | 76 | 77 | def read_complete_path(starting_path, total_length): 78 | complete_path = bytearray(total_length) 79 | current_path_length = len(starting_path) 80 | remaining_path = total_length - current_path_length 81 | complete_path[:current_path_length] = starting_path 82 | if remaining_path > 0: 83 | read_packets(memoryview(complete_path)[current_path_length:], target_size=remaining_path) 84 | return str(complete_path, "utf-8") 85 | 86 | 87 | packet_buffer = bytearray(CHUNK_SIZE + 20) 88 | # Mimic the disconnections that happen when a CP device reloads and resets BLE. 89 | disconnect_after = None 90 | while True: 91 | ble.start_advertising(advert) 92 | while not ble.connected: 93 | pass 94 | print("connected") 95 | while ble.connected: 96 | try: 97 | read = service.raw.readinto(packet_buffer) 98 | except ConnectionError: 99 | continue 100 | if disconnect_after is not None and time.monotonic() > disconnect_after: 101 | for c in ble.connections: 102 | c.disconnect() 103 | disconnect_after = None 104 | continue 105 | if read == 0: 106 | continue 107 | 108 | p = packet_buffer[:read] 109 | command = struct.unpack_from(" content_length: 129 | contents = d[filename][:content_length] 130 | else: 131 | contents = d[filename] 132 | d[filename] = contents 133 | contents_read = start_offset 134 | write_data_header_size = struct.calcsize("