diff --git a/.codespellrc b/.codespellrc new file mode 100644 index 00000000..15692792 --- /dev/null +++ b/.codespellrc @@ -0,0 +1,7 @@ +# See: https://github.com/codespell-project/codespell#using-a-config-file +[codespell] +# In the event of a false positive, add the problematic word, in all lowercase, to a comma-separated list here: +ignore-words-list = wan +check-filenames = +check-hidden = +skip = ./.git diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..fa738ec4 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,12 @@ +# See: https://docs.github.com/en/github/administering-a-repository/configuration-options-for-dependency-updates#about-the-dependabotyml-file +version: 2 + +updates: + # Configure check for outdated GitHub Actions actions in workflows. + # See: https://docs.github.com/en/github/administering-a-repository/keeping-your-actions-up-to-date-with-dependabot + - package-ecosystem: github-actions + directory: / # Check the repository's workflows under /.github/workflows/ + schedule: + interval: daily + labels: + - "topic: infrastructure" diff --git a/.github/workflows/check-arduino.yml b/.github/workflows/check-arduino.yml new file mode 100644 index 00000000..97b2bf2a --- /dev/null +++ b/.github/workflows/check-arduino.yml @@ -0,0 +1,28 @@ +name: Check Arduino + +# See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows +on: + push: + pull_request: + schedule: + # Run every Tuesday at 8 AM UTC to catch breakage caused by new rules added to Arduino Lint. + - cron: "0 8 * * TUE" + workflow_dispatch: + repository_dispatch: + +jobs: + lint: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v6 + + - name: Arduino Lint + uses: arduino/arduino-lint-action@v2 + with: + compliance: specification + library-manager: update + # Always use this setting for official repositories. Remove for 3rd party projects. + official: true + project-type: library diff --git a/.github/workflows/compile-examples.yml b/.github/workflows/compile-examples.yml index f5876041..27478a98 100644 --- a/.github/workflows/compile-examples.yml +++ b/.github/workflows/compile-examples.yml @@ -4,49 +4,204 @@ on: pull_request: paths: - ".github/workflows/compile-examples.yml" + - "library.properties" - "examples/**" - "src/**" push: paths: - ".github/workflows/compile-examples.yml" + - "library.properties" - "examples/**" - "src/**" + schedule: + # Run every Tuesday at 8 AM UTC to catch breakage caused by changes to external resources (libraries, platforms). + - cron: "0 8 * * TUE" + workflow_dispatch: + repository_dispatch: jobs: build: + name: ${{ matrix.board.fqbn }} runs-on: ubuntu-latest env: - LIBRARIES: Arduino_DebugUtils WiFi101 WiFiNINA MKRGSM MKRNB MKRWAN + LIBRARIES: | + # Install the Arduino_ConnectionHandler library from the repository + - source-path: ./ + - name: Arduino_DebugUtils + - name: WiFi101 + - name: WiFiNINA + - name: MKRGSM + - name: MKRNB + - name: MKRWAN + - name: Arduino_Cellular + SKETCH_PATHS: | + - examples/ConnectionHandlerDemo + - examples/CheckInternetAvailabilityDemo + ARDUINOCORE_MBED_STAGING_PATH: extras/ArduinoCore-mbed + ARDUINOCORE_API_STAGING_PATH: extras/ArduinoCore-API + SKETCHES_REPORTS_PATH: sketches-reports strategy: matrix: - fqbn: [ - "arduino:samd:mkr1000", - "arduino:samd:mkrwifi1010", - "arduino:samd:nano_33_iot", - "arduino:samd:mkrgsm1400", - "arduino:samd:mkrnb1500", - "arduino:samd:mkrwan1300", - "arduino:samd:mkrwan1310", - '"esp8266:esp8266:huzzah" "https://arduino.esp8266.com/stable/package_esp8266com_index.json"' - ] + board: + - fqbn: "arduino:samd:mkr1000" + platform-name: arduino:samd + artifact-name-suffix: arduino-samd-mkr1000 + - fqbn: "arduino:samd:mkrwifi1010" + platform-name: arduino:samd + artifact-name-suffix: arduino-samd-mkrwifi1010 + - fqbn: "arduino:samd:nano_33_iot" + platform-name: arduino:samd + artifact-name-suffix: arduino-samd-nano_33_iot + - fqbn: "arduino:samd:mkrgsm1400" + platform-name: arduino:samd + artifact-name-suffix: arduino-samd-mkrgsm1400 + - fqbn: "arduino:samd:mkrnb1500" + platform-name: arduino:samd + artifact-name-suffix: arduino-samd-mkrnb1500 + - fqbn: "arduino:samd:mkrwan1300" + platform-name: arduino:samd + artifact-name-suffix: arduino-samd-mkrwan1300 + - fqbn: "arduino:samd:mkrwan1310" + platform-name: arduino:samd + artifact-name-suffix: arduino-samd-mkrwan1310 + - fqbn: "arduino:mbed:envie_m7" + platform-name: arduino:mbed + artifact-name-suffix: arduino-mbed-envie_m7 + - fqbn: "arduino:mbed_portenta:envie_m7" + platform-name: arduino:mbed_portenta + artifact-name-suffix: arduino-mbed_portenta-envie_m7 + - fqbn: "esp8266:esp8266:huzzah" + platform-name: esp8266:esp8266 + artifact-name-suffix: esp8266-esp8266-huzzah + - fqbn: "esp32:esp32:esp32" + platform-name: esp32:esp32 + artifact-name-suffix: esp32-esp32-esp32 + - fqbn: arduino:mbed_nano:nanorp2040connect + platform-name: arduino:mbed_nano + artifact-name-suffix: arduino-mbed_nano-nanorp2040connect + - fqbn: arduino:mbed_nicla:nicla_vision + platform-name: arduino:mbed_nicla + artifact-name-suffix: arduino-mbed_nicla-nicla_vision + - fqbn: arduino:mbed_opta:opta + platform-name: arduino:mbed_opta + artifact-name-suffix: arduino-mbed_opta-opta + - fqbn: arduino:mbed_giga:giga + platform-name: arduino:mbed_giga + artifact-name-suffix: arduino-mbed_giga-giga + - fqbn: arduino:renesas_portenta:portenta_c33 + platform-name: arduino:renesas_portenta + artifact-name-suffix: arduino-renesas_portenta-portenta_c33 + - fqbn: arduino:renesas_uno:unor4wifi + platform-name: arduino:renesas_uno + artifact-name-suffix: arduino-renesas_uno-unor4wifi + - fqbn: arduino:esp32:nano_nora + platform-name: arduino:esp32 + artifact-name-suffix: arduino-esp32-nano_nora + - fqbn: arduino:mbed_edge:edge_control + platform-name: arduino:mbed_edge + artifact-name-suffix: arduino-mbed_edge-edge_control + - fqbn: "rp2040:rp2040:rpipicow" + platform-name: rp2040:rp2040 + artifact-name-suffix: rp2040-rp2040-rpipicow + + # Make board type-specific customizations to the matrix jobs + include: + - board: + platform-name: arduino:samd + platforms: | + # Install Arduino SAMD Boards via Boards Manager + - name: arduino:samd + - board: + platform-name: arduino:mbed + platforms: | + # Install Arduino mbed-Enabled Boards via Boards Manager for the toolchain + - name: arduino:mbed + # Overwrite the Arduino mbed-Enabled Boards release version with version from the tip of the default branch (located in local path because of the need to first install ArduinoCore-API) + - source-path: extras/ArduinoCore-mbed + name: arduino:mbed + - board: + platform-name: arduino:renesas_portenta + platforms: | + # Install Arduino Renesas portenta Boards via Boards Manager + - name: arduino:renesas_portenta + - board: + platform-name: arduino:renesas_uno + platforms: | + # Install Arduino Renesas uno Boards via Boards Manager + - name: arduino:renesas_uno + - board: + platform-name: arduino:esp32 + platforms: | + # Install Arduino ESP32 Boards via Boards Manager + - name: arduino:esp32 + - board: + platform-name: esp8266:esp8266 + platforms: | + # Install ESP8266 platform via Boards Manager + - name: esp8266:esp8266 + source-url: https://arduino.esp8266.com/stable/package_esp8266com_index.json + version: 2.5.0 + - board: + platform-name: esp32:esp32 + platforms: | + # Install ESP32 platform via Boards Manager + - name: esp32:esp32 + source-url: https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json + - board: + platform-name: rp2040:rp2040 + platforms: | + # Install rp2040 platform via Boards Manager + - name: rp2040:rp2040 + source-url: https://github.com/earlephilhower/arduino-pico/releases/download/global/package_rp2040_index.json steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v6 + + # It's necessary to checkout the platform before installing it so that the ArduinoCore-API dependency can be added + - name: Checkout ArduinoCore-mbed + # this step only needed when the Arduino mbed-Enabled Boards platform sourced from the repository is being used + if: matrix.board.platform-name == 'arduino:mbed' + uses: actions/checkout@v6 + with: + repository: arduino/ArduinoCore-mbed + # The arduino/actions/libraries/compile-examples action will install the platform from this path + path: ${{ env.ARDUINOCORE_MBED_STAGING_PATH }} + + - name: Checkout ArduinoCore-API + # This step only needed when the Arduino mbed-Enabled Boards platform sourced from the repository is being used + if: matrix.board.platform-name == 'arduino:mbed' + uses: actions/checkout@v6 with: - fetch-depth: 1 + repository: arduino/ArduinoCore-API + path: ${{ env.ARDUINOCORE_API_STAGING_PATH }} + + - name: Install ArduinoCore-API + # This step only needed when the Arduino mbed-Enabled Boards platform sourced from the repository is being used + if: matrix.board.platform-name == 'arduino:mbed' + run: | + mv "${{ env.ARDUINOCORE_API_STAGING_PATH }}/api" "${{ env.ARDUINOCORE_MBED_STAGING_PATH }}/cores/arduino" + + - name: Install ESP32 platform dependencies + if: matrix.board.platform-name == 'esp32:esp32' + run: pip3 install pyserial - name: Compile examples - uses: arduino/actions/libraries/compile-examples@master + uses: arduino/compile-sketches@v1 with: - fqbn: ${{ matrix.fqbn }} + platforms: ${{ matrix.platforms }} + fqbn: ${{ matrix.board.fqbn }} libraries: ${{ env.LIBRARIES }} - size-report-sketch: 'ConnectionHandlerDemo' - enable-size-deltas-report: 'true' + sketch-paths: | + ${{ env.SKETCH_PATHS }} + ${{ matrix.sketch-paths }} + enable-deltas-report: 'true' + sketches-report-path: ${{ env.SKETCHES_REPORTS_PATH }} - name: Save memory usage change report as artifact if: github.event_name == 'pull_request' - uses: actions/upload-artifact@v1 + uses: actions/upload-artifact@v5 with: - name: 'size-deltas-reports' - path: 'size-deltas-reports' + if-no-files-found: error + name: sketches-report-${{ matrix.board.artifact-name-suffix }} + path: ${{ env.SKETCHES_REPORTS_PATH }} diff --git a/.github/workflows/report-size-deltas.yml b/.github/workflows/report-size-deltas.yml index 8af849fe..d7b942ed 100644 --- a/.github/workflows/report-size-deltas.yml +++ b/.github/workflows/report-size-deltas.yml @@ -1,8 +1,13 @@ name: Report PR Size Deltas on: + push: + paths: + - ".github/workflows/report-size-deltas.yml" schedule: - cron: '*/5 * * * *' + workflow_dispatch: + repository_dispatch: jobs: report: @@ -10,4 +15,7 @@ jobs: steps: - name: Comment size deltas reports to PRs - uses: arduino/actions/libraries/report-size-deltas@master + uses: arduino/report-size-deltas@v1 + with: + # Regex matching the names of the workflow artifacts created by the "Compile Examples" workflow + sketches-reports-source: ^sketches-report-.+ diff --git a/.github/workflows/spell-check.yml b/.github/workflows/spell-check.yml index b7be756a..8fc4b8c6 100644 --- a/.github/workflows/spell-check.yml +++ b/.github/workflows/spell-check.yml @@ -1,14 +1,22 @@ name: Spell Check -on: [push, pull_request] + +# See: https://docs.github.com/en/free-pro-team@latest/actions/reference/events-that-trigger-workflows +on: + push: + pull_request: + schedule: + # Run every Tuesday at 8 AM UTC to catch new misspelling detections resulting from dictionary updates. + - cron: "0 8 * * TUE" + workflow_dispatch: + repository_dispatch: + jobs: - build: - runs-on: ubuntu-latest + spellcheck: + runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v1 - with: - fetch-depth: 1 - - uses: arduino/actions/libraries/spell-check@master - with: - ignore-words-list: extras/codespell-ignore-words-list.txt + steps: + - name: Checkout repository + uses: actions/checkout@v6 + - name: Spell check + uses: codespell-project/actions-codespell@master diff --git a/.github/workflows/sync-labels.yml b/.github/workflows/sync-labels.yml new file mode 100644 index 00000000..d49c1cb6 --- /dev/null +++ b/.github/workflows/sync-labels.yml @@ -0,0 +1,138 @@ +# Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/sync-labels.md +name: Sync Labels + +# See: https://docs.github.com/en/actions/reference/events-that-trigger-workflows +on: + push: + paths: + - ".github/workflows/sync-labels.ya?ml" + - ".github/label-configuration-files/*.ya?ml" + pull_request: + paths: + - ".github/workflows/sync-labels.ya?ml" + - ".github/label-configuration-files/*.ya?ml" + schedule: + # Run daily at 8 AM UTC to sync with changes to shared label configurations. + - cron: "0 8 * * *" + workflow_dispatch: + repository_dispatch: + +env: + CONFIGURATIONS_FOLDER: .github/label-configuration-files + CONFIGURATIONS_ARTIFACT: label-configuration-files + +jobs: + check: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v6 + + - name: Download JSON schema for labels configuration file + id: download-schema + uses: carlosperate/download-file-action@v2 + with: + file-url: https://raw.githubusercontent.com/arduino/tooling-project-assets/main/workflow-templates/assets/sync-labels/arduino-tooling-gh-label-configuration-schema.json + location: ${{ runner.temp }}/label-configuration-schema + + - name: Install JSON schema validator + run: | + sudo npm install \ + --global \ + ajv-cli \ + ajv-formats + + - name: Validate local labels configuration + run: | + # See: https://github.com/ajv-validator/ajv-cli#readme + ajv validate \ + --all-errors \ + -c ajv-formats \ + -s "${{ steps.download-schema.outputs.file-path }}" \ + -d "${{ env.CONFIGURATIONS_FOLDER }}/*.{yml,yaml}" + + download: + needs: check + runs-on: ubuntu-latest + + strategy: + matrix: + filename: + # Filenames of the shared configurations to apply to the repository in addition to the local configuration. + # https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/assets/sync-labels + - universal.yml + + steps: + - name: Download + uses: carlosperate/download-file-action@v2 + with: + file-url: https://raw.githubusercontent.com/arduino/tooling-project-assets/main/workflow-templates/assets/sync-labels/${{ matrix.filename }} + + - name: Pass configuration files to next job via workflow artifact + uses: actions/upload-artifact@v5 + with: + path: | + *.yaml + *.yml + if-no-files-found: error + name: ${{ env.CONFIGURATIONS_ARTIFACT }} + + sync: + needs: download + runs-on: ubuntu-latest + + steps: + - name: Set environment variables + run: | + # See: https://docs.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-environment-variable + echo "MERGED_CONFIGURATION_PATH=${{ runner.temp }}/labels.yml" >> "$GITHUB_ENV" + + - name: Determine whether to dry run + id: dry-run + if: > + github.event_name == 'pull_request' || + ( + ( + github.event_name == 'push' || + github.event_name == 'workflow_dispatch' + ) && + github.ref != format('refs/heads/{0}', github.event.repository.default_branch) + ) + run: | + # Use of this flag in the github-label-sync command will cause it to only check the validity of the + # configuration. + echo "::set-output name=flag::--dry-run" + + - name: Checkout repository + uses: actions/checkout@v6 + + - name: Download configuration files artifact + uses: actions/download-artifact@v6 + with: + name: ${{ env.CONFIGURATIONS_ARTIFACT }} + path: ${{ env.CONFIGURATIONS_FOLDER }} + + - name: Remove unneeded artifact + uses: geekyeggo/delete-artifact@v5 + with: + name: ${{ env.CONFIGURATIONS_ARTIFACT }} + + - name: Merge label configuration files + run: | + # Merge all configuration files + shopt -s extglob + cat "${{ env.CONFIGURATIONS_FOLDER }}"/*.@(yml|yaml) > "${{ env.MERGED_CONFIGURATION_PATH }}" + + - name: Install github-label-sync + run: sudo npm install --global github-label-sync + + - name: Sync labels + env: + GITHUB_ACCESS_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + # See: https://github.com/Financial-Times/github-label-sync + github-label-sync \ + --labels "${{ env.MERGED_CONFIGURATION_PATH }}" \ + ${{ steps.dry-run.outputs.flag }} \ + ${{ github.repository }} diff --git a/LICENSE b/LICENSE index f288702d..dbdb0fa8 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,373 @@ - GNU GENERAL PUBLIC LICENSE - Version 3, 29 June 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU General Public License is a free, copyleft license for -software and other kinds of works. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -the GNU General Public License is intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. We, the Free Software Foundation, use the -GNU General Public License for most of our software; it applies also to -any other work released this way by its authors. You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - To protect your rights, we need to prevent others from denying you -these rights or asking you to surrender the rights. Therefore, you have -certain responsibilities if you distribute copies of the software, or if -you modify it: responsibilities to respect the freedom of others. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must pass on to the recipients the same -freedoms that you received. You must make sure that they, too, receive -or can get the source code. And you must show them these terms so they -know their rights. - - Developers that use the GNU GPL protect your rights with two steps: -(1) assert copyright on the software, and (2) offer you this License -giving you legal permission to copy, distribute and/or modify it. - - For the developers' and authors' protection, the GPL clearly explains -that there is no warranty for this free software. For both users' and -authors' sake, the GPL requires that modified versions be marked as -changed, so that their problems will not be attributed erroneously to -authors of previous versions. - - Some devices are designed to deny users access to install or run -modified versions of the software inside them, although the manufacturer -can do so. This is fundamentally incompatible with the aim of -protecting users' freedom to change the software. The systematic -pattern of such abuse occurs in the area of products for individuals to -use, which is precisely where it is most unacceptable. Therefore, we -have designed this version of the GPL to prohibit the practice for those -products. If such problems arise substantially in other domains, we -stand ready to extend this provision to those domains in future versions -of the GPL, as needed to protect the freedom of users. - - Finally, every program is threatened constantly by software patents. -States should not allow patents to restrict development and use of -software on general-purpose computers, but in those that do, we wish to -avoid the special danger that patents applied to a free program could -make it effectively proprietary. To prevent this, the GPL assures that -patents cannot be used to render the program non-free. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Use with the GNU Affero General Public License. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU Affero General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the special requirements of the GNU Affero General Public License, -section 13, concerning interaction through a network will apply to the -combination as such. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If the program does terminal interaction, make it output a short -notice like this when it starts in an interactive mode: - - Copyright (C) - This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, your program's commands -might be different; for a GUI interface, you would use an "about box". - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU GPL, see -. - - The GNU General Public License does not permit incorporating your program -into proprietary programs. If your program is a subroutine library, you -may consider it more useful to permit linking proprietary applications with -the library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. But first, please read -. +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at https://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. \ No newline at end of file diff --git a/README.md b/README.md index ba80cf02..40f9ee09 100644 --- a/README.md +++ b/README.md @@ -1,22 +1,27 @@ Arduino Library for network connections management ================================================== -![](https://github.com/arduino-libraries/Arduino_ConnectionHandler/workflows/Compile%20Examples/badge.svg) -![](https://github.com/arduino-libraries/Arduino_ConnectionHandler/workflows/Spell%20Check/badge.svg) +[![Check Arduino status](https://github.com/arduino-libraries/Arduino_ConnectionHandler/actions/workflows/check-arduino.yml/badge.svg)](https://github.com/arduino-libraries/Arduino_ConnectionHandler/actions/workflows/check-arduino.yml) +[![Compile Examples status](https://github.com/arduino-libraries/Arduino_ConnectionHandler/actions/workflows/compile-examples.yml/badge.svg)](https://github.com/arduino-libraries/Arduino_ConnectionHandler/actions/workflows/compile-examples.yml) +[![Spell Check status](https://github.com/arduino-libraries/Arduino_ConnectionHandler/actions/workflows/spell-check.yml/badge.svg)](https://github.com/arduino-libraries/Arduino_ConnectionHandler/actions/workflows/spell-check.yml) Library for handling and managing network connections by providing keep-alive functionality and automatic reconnection in case of connection-loss. It supports the following boards: -* **WiFi**: [`MKR 1000`](https://store.arduino.cc/arduino-mkr1000-wifi), [`MKR WiFi 1010`](https://store.arduino.cc/arduino-mkr-wifi-1010), [`Nano 33 IoT`](https://store.arduino.cc/arduino-nano-33-iot), `ESP8266` + +* **WiFi**: [`MKR 1000`](https://store.arduino.cc/arduino-mkr1000-wifi), [`MKR WiFi 1010`](https://store.arduino.cc/arduino-mkr-wifi-1010), [`Nano 33 IoT`](https://store.arduino.cc/arduino-nano-33-iot), [`Portenta H7`](https://store.arduino.cc/products/portenta-h7), [`Nano RP2040 Connect`](https://store.arduino.cc/products/arduino-nano-rp2040-connect), [`Nicla Vision`](https://store.arduino.cc/products/nicla-vision), [`OPTA WiFi`](https://store.arduino.cc/products/opta-wifi), [`GIGA R1 WiFi`](https://store.arduino.cc/products/giga-r1-wifi), [`Portenta C33`](https://store.arduino.cc/products/portenta-c33), [`UNO R4 WiFi`](https://store.arduino.cc/products/uno-r4-wifi), [`Nano ESP32`](https://store.arduino.cc/products/nano-esp32), [`ESP8266`](https://github.com/esp8266/Arduino/releases/tag/2.5.0), [`ESP32`](https://github.com/espressif/arduino-esp32) * **GSM**: [`MKR GSM 1400`](https://store.arduino.cc/arduino-mkr-gsm-1400-1415) * **5G**: [`MKR NB 1500`](https://store.arduino.cc/arduino-mkr-nb-1500-1413) * **LoRa**: [`MKR WAN 1300/1310`](https://store.arduino.cc/mkr-wan-1310) +* **Ethernet**: [`Portenta H7`](https://store.arduino.cc/products/portenta-h7) + [`Vision Shield Ethernet`](https://store.arduino.cc/products/arduino-portenta-vision-shield-ethernet), [`Max Carrier`](https://store.arduino.cc/products/portenta-max-carrier), [`Breakout`](https://store.arduino.cc/products/arduino-portenta-breakout), [`Portenta Machine Control`](https://store.arduino.cc/products/arduino-portenta-machine-control), [`OPTA WiFi`](https://store.arduino.cc/products/opta-wifi), [`OPTA RS485`](https://store.arduino.cc/products/opta-rs485), [`OPTA Lite`](https://store.arduino.cc/products/opta-lite), [`Portenta C33`](https://store.arduino.cc/products/portenta-c33) + [`Vision Shield Ethernet`](https://store.arduino.cc/products/arduino-portenta-vision-shield-ethernet) ### How-to-use ```C++ #include /* ... */ -#if defined(BOARD_HAS_WIFI) -WiFiConnectionHandler conMan("SECRET_SSID", "SECRET_PASS"); +#if defined(BOARD_HAS_ETHERNET) +EthernetConnectionHandler conMan; +#elif defined(BOARD_HAS_WIFI) +WiFiConnectionHandler conMan("SECRET_WIFI_SSID", "SECRET_WIFI_PASS"); #elif defined(BOARD_HAS_GSM) GSMConnectionHandler conMan("SECRET_PIN", "SECRET_APN", "SECRET_GSM_LOGIN", "SECRET_GSM_PASS"); #elif defined(BOARD_HAS_NB) diff --git a/examples/CheckInternetAvailabilityDemo/CheckInternetAvailabilityDemo.ino b/examples/CheckInternetAvailabilityDemo/CheckInternetAvailabilityDemo.ino new file mode 100644 index 00000000..ca530ddf --- /dev/null +++ b/examples/CheckInternetAvailabilityDemo/CheckInternetAvailabilityDemo.ino @@ -0,0 +1,152 @@ +/* SECRET_ fields are in `arduino_secrets.h` (included below) + * + * If using a WiFi board (Arduino MKR1000, MKR WiFi 1010, Nano 33 IoT, UNO + * WiFi Rev 2 or ESP8266/32), create a WiFiConnectionHandler object by adding + * Network Name (SECRET_WIFI_SSID) and password (SECRET_WIFI_PASS) in the + * arduino_secrets.h file (or Secrets tab in Create Web Editor). + * + * WiFiConnectionHandler conMan(SECRET_WIFI_SSID, SECRET_WIFI_PASS); + * + * If using a MKR GSM 1400 or other GSM boards supporting the same API you'll + * need a GSMConnectionHandler object as follows + * + * GSMConnectionHandler conMan(SECRET_PIN, SECRET_APN, SECRET_GSM_USER, SECRET_GSM_PASS); + * + * If using a MKR NB1500 you'll need a NBConnectionHandler object as follows + * + * NBConnectionHandler conMan(SECRET_PIN); + * + * If using a Portenta + Ethernet shield you'll need a EthernetConnectionHandler object as follows: + * + * DHCP mode + * EthernetConnectionHandler conMan; + * + * Manual configuration + * EthernetConnectionHandler conMan(SECRET_IP, SECRET_DNS, SECRET_GATEWAY, SECRET_NETMASK); + * + * Manual configuration will fallback on DHCP mode if SECRET_IP is invalid or equal to INADDR_NONE. + * + * This sketch enables the ConnectionHandler to check for internet availability (only for IP based connectivity) + * before reporting the Connected state. By default the check is disabled. + * + */ + +#include + +#include "arduino_secrets.h" + +#define CONN_TOGGLE_MS 60000 + +#if !(defined(BOARD_HAS_WIFI) || defined(BOARD_HAS_GSM) || defined(BOARD_HAS_LORA) || \ + defined(BOARD_HAS_NB) || defined(BOARD_HAS_ETHERNET) || defined(BOARD_HAS_CATM1_NBIOT)) + #error "Please check Arduino Connection Handler supported boards list: https://github.com/arduino-libraries/Arduino_ConnectionHandler/blob/master/README.md" +#endif + +#if defined(BOARD_HAS_ETHERNET) +EthernetConnectionHandler conMan(SECRET_IP, SECRET_DNS, SECRET_GATEWAY, SECRET_NETMASK); +#elif defined(BOARD_HAS_WIFI) +WiFiConnectionHandler conMan(SECRET_WIFI_SSID, SECRET_WIFI_PASS); +#elif defined(BOARD_HAS_GSM) +GSMConnectionHandler conMan(SECRET_PIN, SECRET_APN, SECRET_GSM_USER, SECRET_GSM_PASS); +#elif defined(BOARD_HAS_NB) +NBConnectionHandler conMan(SECRET_PIN); +#elif defined(BOARD_HAS_LORA) +LoRaConnectionHandler conMan(SECRET_APP_EUI, SECRET_APP_KEY); +#elif defined(BOARD_HAS_CATM1_NBIOT) +CatM1ConnectionHandler conMan(SECRET_PIN, SECRET_APN, SECRET_GSM_USER, SECRET_GSM_PASS); +#elif defined(BOARD_HAS_CELLULAR) +CellularConnectionHandler conMan(SECRET_PIN, SECRET_APN, SECRET_GSM_USER, SECRET_GSM_PASS); +#endif + +bool attemptConnect = false; +uint32_t lastConnToggleMs = 0; + +void setup() { + /* Initialize serial debug port and wait up to 5 seconds for port to open */ + Serial.begin(9600); + for(unsigned long const serialBeginTime = millis(); !Serial && (millis() - serialBeginTime <= 5000); ) { } + +#ifndef __AVR__ + /* Set the debug message level: + * - DBG_ERROR: Only show error messages + * - DBG_WARNING: Show warning and error messages + * - DBG_INFO: Show info, warning, and error messages + * - DBG_DEBUG: Show debug, info, warning, and error messages + * - DBG_VERBOSE: Show all messages + */ + setDebugMessageLevel(DBG_INFO); +#endif + /* Enable the connection handler to check for internet availability. + * By default is disabled. + */ + conMan.enableCheckInternetAvailability(true); + /* Add callbacks to the ConnectionHandler object to get notified of network + * connection events. */ + conMan.addCallback(NetworkConnectionEvent::CONNECTED, onNetworkConnect); + conMan.addCallback(NetworkConnectionEvent::DISCONNECTED, onNetworkDisconnect); + conMan.addCallback(NetworkConnectionEvent::ERROR, onNetworkError); + + Serial.print("Network Adapter Interface: "); + switch (conMan.getInterface()) { + case NetworkAdapter::WIFI: + Serial.println("Wi-Fi"); + break; + case NetworkAdapter::ETHERNET: + Serial.println("Ethernet"); + break; + case NetworkAdapter::NB: + Serial.println("Narrowband"); + break; + case NetworkAdapter::GSM: + Serial.println("GSM"); + break; + case NetworkAdapter::LORA: + Serial.println("LoRa"); + break; + case NetworkAdapter::CATM1: + Serial.println("Category M1"); + break; + case NetworkAdapter::CELL: + Serial.println("Cellular"); + break; + default: + Serial.println("Unknown"); + break; + } +} + +void loop() { + /* Toggle the connection every `CONN_TOGGLE_MS` milliseconds */ + if ((millis() - lastConnToggleMs) > CONN_TOGGLE_MS) { + Serial.println("Toggling connection..."); + if (attemptConnect) { + conMan.connect(); + } else { + conMan.disconnect(); + } + attemptConnect = !attemptConnect; + lastConnToggleMs = millis(); + } + + /* The following code keeps on running connection workflows on our + * ConnectionHandler object, hence allowing reconnection in case of failure + * and notification of connect/disconnect event if enabled (see + * addConnectCallback/addDisconnectCallback) NOTE: any use of delay() within + * the loop or methods called from it will delay the execution of .update(), + * which might not guarantee the correct functioning of the ConnectionHandler + * object. + */ + conMan.check(); +} + +void onNetworkConnect() { + Serial.println(">>>> CONNECTED to network"); +} + +void onNetworkDisconnect() { + Serial.println(">>>> DISCONNECTED from network"); +} + +void onNetworkError() { + Serial.println(">>>> ERROR"); +} diff --git a/examples/CheckInternetAvailabilityDemo/arduino_secrets.h b/examples/CheckInternetAvailabilityDemo/arduino_secrets.h new file mode 100644 index 00000000..f9906f69 --- /dev/null +++ b/examples/CheckInternetAvailabilityDemo/arduino_secrets.h @@ -0,0 +1,19 @@ +// Required for WiFiConnectionHandler +const char SECRET_WIFI_SSID[] = "NETWORK NAME"; +const char SECRET_WIFI_PASS[] = "NETWORK PASSWORD"; + +// Required for GSMConnectionHandler +const char SECRET_APN[] = "MOBILE PROVIDER APN ADDRESS"; +const char SECRET_PIN[] = "0000"; // Required for NBConnectionHandler +const char SECRET_GSM_USER[] = "GSM USERNAME"; +const char SECRET_GSM_PASS[] = "GSM PASSWORD"; + +// Required for LoRaConnectionHandler +const char SECRET_APP_EUI[] = "APP_EUI"; +const char SECRET_APP_KEY[] = "APP_KEY"; + +// Required for EthernetConnectionHandler (without DHCP mode) +const char SECRET_IP[] = "IP ADDRESS"; +const char SECRET_DNS[] = "DNS ADDRESS"; +const char SECRET_GATEWAY[] = "GATEWAY ADDRESS"; +const char SECRET_NETMASK[] = "NETWORK MASK"; diff --git a/examples/ConnectionHandlerDemo/ConnectionHandlerDemo.ino b/examples/ConnectionHandlerDemo/ConnectionHandlerDemo.ino index 2246fc10..46a0c9d4 100644 --- a/examples/ConnectionHandlerDemo/ConnectionHandlerDemo.ino +++ b/examples/ConnectionHandlerDemo/ConnectionHandlerDemo.ino @@ -1,10 +1,11 @@ -/* SECRET_ fields are in arduino_secrets.h included above - * if using a WiFi board (Arduino MKR1000, MKR WiFi 1010, Nano 33 IoT, UNO +/* SECRET_ fields are in `arduino_secrets.h` (included below) + * + * If using a WiFi board (Arduino MKR1000, MKR WiFi 1010, Nano 33 IoT, UNO * WiFi Rev 2 or ESP8266/32), create a WiFiConnectionHandler object by adding - * Network Name (SECRET_SSID) and password (SECRET_PASS) in the arduino_secrets.h - * file (or Secrets tab in Create Web Editor). + * Network Name (SECRET_WIFI_SSID) and password (SECRET_WIFI_PASS) in the + * arduino_secrets.h file (or Secrets tab in Create Web Editor). * - * WiFiConnectionHandler conMan(SECRET_SSID, SECRET_PASS); + * WiFiConnectionHandler conMan(SECRET_WIFI_SSID, SECRET_WIFI_PASS); * * If using a MKR GSM 1400 or other GSM boards supporting the same API you'll * need a GSMConnectionHandler object as follows @@ -14,35 +15,113 @@ * If using a MKR NB1500 you'll need a NBConnectionHandler object as follows * * NBConnectionHandler conMan(SECRET_PIN); + * + * If using a Portenta + Ethernet shield you'll need a EthernetConnectionHandler object as follows: + * + * DHCP mode + * EthernetConnectionHandler conMan; + * + * Manual configuration + * EthernetConnectionHandler conMan(SECRET_IP, SECRET_DNS, SECRET_GATEWAY, SECRET_NETMASK); + * + * Manual configuration will fallback on DHCP mode if SECRET_IP is invalid or equal to INADDR_NONE. + * */ +#include + #include "arduino_secrets.h" -#include +#define CONN_TOGGLE_MS 60000 -#if defined(BOARD_HAS_WIFI) -WiFiConnectionHandler conMan(SECRET_SSID, SECRET_PASS); +#if !(defined(BOARD_HAS_WIFI) || defined(BOARD_HAS_GSM) || defined(BOARD_HAS_LORA) || \ + defined(BOARD_HAS_NB) || defined(BOARD_HAS_ETHERNET) || defined(BOARD_HAS_CATM1_NBIOT)) + #error "Please check Arduino Connection Handler supported boards list: https://github.com/arduino-libraries/Arduino_ConnectionHandler/blob/master/README.md" +#endif + +#if defined(BOARD_HAS_ETHERNET) +EthernetConnectionHandler conMan(SECRET_IP, SECRET_DNS, SECRET_GATEWAY, SECRET_NETMASK); +#elif defined(BOARD_HAS_WIFI) +WiFiConnectionHandler conMan(SECRET_WIFI_SSID, SECRET_WIFI_PASS); #elif defined(BOARD_HAS_GSM) -GSMConnectionHandler conMan(SECRET_APN, SECRET_PIN, SECRET_GSM_USER, SECRET_GSM_PASS); +GSMConnectionHandler conMan(SECRET_PIN, SECRET_APN, SECRET_GSM_USER, SECRET_GSM_PASS); #elif defined(BOARD_HAS_NB) NBConnectionHandler conMan(SECRET_PIN); #elif defined(BOARD_HAS_LORA) LoRaConnectionHandler conMan(SECRET_APP_EUI, SECRET_APP_KEY); +#elif defined(BOARD_HAS_CATM1_NBIOT) +CatM1ConnectionHandler conMan(SECRET_PIN, SECRET_APN, SECRET_GSM_USER, SECRET_GSM_PASS); +#elif defined(BOARD_HAS_CELLULAR) +CellularConnectionHandler conMan(SECRET_PIN, SECRET_APN, SECRET_GSM_USER, SECRET_GSM_PASS); #endif +bool attemptConnect = false; +uint32_t lastConnToggleMs = 0; + void setup() { + /* Initialize serial debug port and wait up to 5 seconds for port to open */ Serial.begin(9600); - /* Give a few seconds for the Serial connection to be available */ - delay(4000); + for(unsigned long const serialBeginTime = millis(); !Serial && (millis() - serialBeginTime <= 5000); ) { } +#ifndef __AVR__ + /* Set the debug message level: + * - DBG_ERROR: Only show error messages + * - DBG_WARNING: Show warning and error messages + * - DBG_INFO: Show info, warning, and error messages + * - DBG_DEBUG: Show debug, info, warning, and error messages + * - DBG_VERBOSE: Show all messages + */ setDebugMessageLevel(DBG_INFO); +#endif + /* Add callbacks to the ConnectionHandler object to get notified of network + * connection events. */ conMan.addCallback(NetworkConnectionEvent::CONNECTED, onNetworkConnect); conMan.addCallback(NetworkConnectionEvent::DISCONNECTED, onNetworkDisconnect); conMan.addCallback(NetworkConnectionEvent::ERROR, onNetworkError); + + Serial.print("Network Adapter Interface: "); + switch (conMan.getInterface()) { + case NetworkAdapter::WIFI: + Serial.println("Wi-Fi"); + break; + case NetworkAdapter::ETHERNET: + Serial.println("Ethernet"); + break; + case NetworkAdapter::NB: + Serial.println("Narrowband"); + break; + case NetworkAdapter::GSM: + Serial.println("GSM"); + break; + case NetworkAdapter::LORA: + Serial.println("LoRa"); + break; + case NetworkAdapter::CATM1: + Serial.println("Category M1"); + break; + case NetworkAdapter::CELL: + Serial.println("Cellular"); + break; + default: + Serial.println("Unknown"); + break; + } } void loop() { + /* Toggle the connection every `CONN_TOGGLE_MS` milliseconds */ + if ((millis() - lastConnToggleMs) > CONN_TOGGLE_MS) { + Serial.println("Toggling connection..."); + if (attemptConnect) { + conMan.connect(); + } else { + conMan.disconnect(); + } + attemptConnect = !attemptConnect; + lastConnToggleMs = millis(); + } + /* The following code keeps on running connection workflows on our * ConnectionHandler object, hence allowing reconnection in case of failure * and notification of connect/disconnect event if enabled (see @@ -51,7 +130,6 @@ void loop() { * which might not guarantee the correct functioning of the ConnectionHandler * object. */ - conMan.check(); } diff --git a/examples/ConnectionHandlerDemo/arduino_secrets.h b/examples/ConnectionHandlerDemo/arduino_secrets.h index 0a2a2fe6..f9906f69 100644 --- a/examples/ConnectionHandlerDemo/arduino_secrets.h +++ b/examples/ConnectionHandlerDemo/arduino_secrets.h @@ -1,10 +1,19 @@ -const char SECRET_SSID[] = "NETWORK NAME"; -const char SECRET_PASS[] = "NETWORK PASSWORD"; +// Required for WiFiConnectionHandler +const char SECRET_WIFI_SSID[] = "NETWORK NAME"; +const char SECRET_WIFI_PASS[] = "NETWORK PASSWORD"; -const char SECRET_APN[] = "MOBILE PROVIDER APN ADDRESS"; -const char SECRET_PIN[] = "0000"; -const char SECRET_GSM_USER[] = "GSM USERNAME"; -const char SECRET_GSM_PASS[] = "GSM PASSWORD"; +// Required for GSMConnectionHandler +const char SECRET_APN[] = "MOBILE PROVIDER APN ADDRESS"; +const char SECRET_PIN[] = "0000"; // Required for NBConnectionHandler +const char SECRET_GSM_USER[] = "GSM USERNAME"; +const char SECRET_GSM_PASS[] = "GSM PASSWORD"; +// Required for LoRaConnectionHandler const char SECRET_APP_EUI[] = "APP_EUI"; const char SECRET_APP_KEY[] = "APP_KEY"; + +// Required for EthernetConnectionHandler (without DHCP mode) +const char SECRET_IP[] = "IP ADDRESS"; +const char SECRET_DNS[] = "DNS ADDRESS"; +const char SECRET_GATEWAY[] = "GATEWAY ADDRESS"; +const char SECRET_NETMASK[] = "NETWORK MASK"; diff --git a/examples/ConnectionHandlerTimeoutTable/ConnectionHandlerTimeoutTable.ino b/examples/ConnectionHandlerTimeoutTable/ConnectionHandlerTimeoutTable.ino new file mode 100644 index 00000000..ab629053 --- /dev/null +++ b/examples/ConnectionHandlerTimeoutTable/ConnectionHandlerTimeoutTable.ino @@ -0,0 +1,83 @@ +/* SECRET_ fields are in `arduino_secrets.h` (included below) + * + * This example is a lightly modified version of ConnectionHandlerDemo to showcase + * the possibility of changing the timeout values for the different states a connectionhandler have + */ + +#include + +#include "arduino_secrets.h" + +#if !(defined(BOARD_HAS_WIFI) || defined(BOARD_HAS_GSM) || defined(BOARD_HAS_LORA) || \ + defined(BOARD_HAS_NB) || defined(BOARD_HAS_ETHERNET) || defined(BOARD_HAS_CATM1_NBIOT)) + #error "Please check Arduino Connection Handler supported boards list: https://github.com/arduino-libraries/Arduino_ConnectionHandler/blob/master/README.md" +#endif + +#if defined(BOARD_HAS_ETHERNET) +EthernetConnectionHandler conMan(SECRET_IP, SECRET_DNS, SECRET_GATEWAY, SECRET_NETMASK); +#elif defined(BOARD_HAS_WIFI) +WiFiConnectionHandler conMan(SECRET_WIFI_SSID, SECRET_WIFI_PASS); +#elif defined(BOARD_HAS_GSM) +GSMConnectionHandler conMan(SECRET_PIN, SECRET_APN, SECRET_GSM_USER, SECRET_GSM_PASS); +#elif defined(BOARD_HAS_NB) +NBConnectionHandler conMan(SECRET_PIN); +#elif defined(BOARD_HAS_LORA) +LoRaConnectionHandler conMan(SECRET_APP_EUI, SECRET_APP_KEY); +#elif defined(BOARD_HAS_CATM1_NBIOT) +CatM1ConnectionHandler conMan(SECRET_PIN, SECRET_APN, SECRET_GSM_USER, SECRET_GSM_PASS); +#elif defined(BOARD_HAS_CELLULAR) +CellularConnectionHandler conMan(SECRET_PIN, SECRET_APN, SECRET_GSM_USER, SECRET_GSM_PASS); +#endif + +bool attemptConnect = false; +uint32_t lastConnToggleMs = 0; + +void setup() { + /* Initialize serial debug port and wait up to 5 seconds for port to open */ + Serial.begin(9600); + for(unsigned long const serialBeginTime = millis(); !Serial && (millis() - serialBeginTime <= 5000); ) { } + +#ifndef __AVR__ + /* Set the debug message level: + * - DBG_ERROR: Only show error messages + * - DBG_WARNING: Show warning and error messages + * - DBG_INFO: Show info, warning, and error messages + * - DBG_DEBUG: Show debug, info, warning, and error messages + * - DBG_VERBOSE: Show all messages + */ + setDebugMessageLevel(DBG_INFO); +#endif + + /* Add callbacks to the ConnectionHandler object to get notified of network + * connection events. */ + conMan.addCallback(NetworkConnectionEvent::CONNECTED, onNetworkConnect); + conMan.addCallback(NetworkConnectionEvent::DISCONNECTED, onNetworkDisconnect); + conMan.addCallback(NetworkConnectionEvent::ERROR, onNetworkError); + + /* By using updateTimeoutInterval I can change the timeout value for a specific + * state of the connection handler + */ + conMan.updateTimeoutInterval(NetworkConnectionState::INIT, 8000); + conMan.updateTimeoutInterval(NetworkConnectionState::CONNECTING, 1000); + conMan.updateTimeoutInterval(NetworkConnectionState::CONNECTED, 20000); + conMan.updateTimeoutInterval(NetworkConnectionState::DISCONNECTING, 200); + conMan.updateTimeoutInterval(NetworkConnectionState::DISCONNECTED, 2000); + conMan.updateTimeoutInterval(NetworkConnectionState::CLOSED, 2000); + conMan.updateTimeoutInterval(NetworkConnectionState::ERROR, 2000); +} + +void loop() { + conMan.check(); +} + +void onNetworkConnect() { + Serial.println(">>>> CONNECTED to network"); +} + +void onNetworkDisconnect() { + Serial.println(">>>> DISCONNECTED from network"); +} + +void onNetworkError() { + Serial.println(">>>> ERROR"); +} diff --git a/examples/ConnectionHandlerTimeoutTable/arduino_secrets.h b/examples/ConnectionHandlerTimeoutTable/arduino_secrets.h new file mode 100644 index 00000000..cecefa42 --- /dev/null +++ b/examples/ConnectionHandlerTimeoutTable/arduino_secrets.h @@ -0,0 +1,19 @@ +// Required for WiFiConnectionHandler +const char SECRET_WIFI_SSID[] = "SSID"; +const char SECRET_WIFI_PASS[] = "PASSWORD"; + +// Required for GSMConnectionHandler +const char SECRET_APN[] = "MOBILE PROVIDER APN ADDRESS"; +const char SECRET_PIN[] = "0000"; // Required for NBConnectionHandler +const char SECRET_GSM_USER[] = "GSM USERNAME"; +const char SECRET_GSM_PASS[] = "GSM PASSWORD"; + +// Required for LoRaConnectionHandler +const char SECRET_APP_EUI[] = "APP_EUI"; +const char SECRET_APP_KEY[] = "APP_KEY"; + +// Required for EthernetConnectionHandler (without DHCP mode) +const char SECRET_IP[] = "IP ADDRESS"; +const char SECRET_DNS[] = "DNS ADDRESS"; +const char SECRET_GATEWAY[] = "GATEWAY ADDRESS"; +const char SECRET_NETMASK[] = "NETWORK MASK"; diff --git a/examples/GenericConnectionHandlerDemo/GenericConnectionHandlerDemo.ino b/examples/GenericConnectionHandlerDemo/GenericConnectionHandlerDemo.ino new file mode 100644 index 00000000..2ce18f7e --- /dev/null +++ b/examples/GenericConnectionHandlerDemo/GenericConnectionHandlerDemo.ino @@ -0,0 +1,139 @@ +/* SECRET_ fields are in `arduino_secrets.h` (included below) + * + * If using a WiFi board (Arduino MKR1000, MKR WiFi 1010, Nano 33 IoT, UNO + * WiFi Rev 2 or ESP8266/32), create a WiFiConnectionHandler object by adding + * Network Name (SECRET_WIFI_SSID) and password (SECRET_WIFI_PASS) in the + * arduino_secrets.h file (or Secrets tab in Create Web Editor). + * + * WiFiConnectionHandler conMan(SECRET_WIFI_SSID, SECRET_WIFI_PASS); + * + * If using a MKR GSM 1400 or other GSM boards supporting the same API you'll + * need a GSMConnectionHandler object as follows + * + * GSMConnectionHandler conMan(SECRET_PIN, SECRET_APN, SECRET_GSM_USER, SECRET_GSM_PASS); + * + * If using a MKR NB1500 you'll need a NBConnectionHandler object as follows + * + * NBConnectionHandler conMan(SECRET_PIN); + * + * If using a Portenta + Ethernet shield you'll need a EthernetConnectionHandler object as follows: + * + * DHCP mode + * EthernetConnectionHandler conMan; + * + * Manual configuration + * EthernetConnectionHandler conMan(SECRET_IP, SECRET_DNS, SECRET_GATEWAY, SECRET_NETMASK); + * + * Manual configuration will fallback on DHCP mode if SECRET_IP is invalid or equal to INADDR_NONE. + * + */ + +#include + +#include "arduino_secrets.h" + +#define CONN_TOGGLE_MS 60000 + +#if !(defined(BOARD_HAS_WIFI) || defined(BOARD_HAS_GSM) || defined(BOARD_HAS_LORA) || \ + defined(BOARD_HAS_NB) || defined(BOARD_HAS_ETHERNET) || defined(BOARD_HAS_CATM1_NBIOT)) + #error "Please check Arduino Connection Handler supported boards list: https://github.com/arduino-libraries/Arduino_ConnectionHandler/blob/master/README.md" +#endif + +GenericConnectionHandler conMan; + + +bool attemptConnect = false; +uint32_t lastConnToggleMs = 0; + +void setup() { + /* Initialize serial debug port and wait up to 5 seconds for port to open */ + Serial.begin(9600); + for(unsigned long const serialBeginTime = millis(); !Serial && (millis() - serialBeginTime <= 5000); ) { } + +#ifndef __AVR__ + /* Set the debug message level: + * - DBG_ERROR: Only show error messages + * - DBG_WARNING: Show warning and error messages + * - DBG_INFO: Show info, warning, and error messages + * - DBG_DEBUG: Show debug, info, warning, and error messages + * - DBG_VERBOSE: Show all messages + */ + setDebugMessageLevel(DBG_INFO); +#endif + + models::NetworkSetting setting = models::settingsDefault(NetworkAdapter::WIFI); + + strcpy(setting.wifi.ssid, SECRET_WIFI_SSID); + strcpy(setting.wifi.pwd, SECRET_WIFI_PASS); + + /* Add callbacks to the ConnectionHandler object to get notified of network + * connection events. */ + conMan.addCallback(NetworkConnectionEvent::CONNECTED, onNetworkConnect); + conMan.addCallback(NetworkConnectionEvent::DISCONNECTED, onNetworkDisconnect); + conMan.addCallback(NetworkConnectionEvent::ERROR, onNetworkError); + + conMan.updateSetting(setting); + Serial.print("Network Adapter Interface: "); + switch (conMan.getInterface()) { + case NetworkAdapter::WIFI: + Serial.println("Wi-Fi"); + break; + case NetworkAdapter::ETHERNET: + Serial.println("Ethernet"); + break; + case NetworkAdapter::NB: + Serial.println("Narrowband"); + break; + case NetworkAdapter::GSM: + Serial.println("GSM"); + break; + case NetworkAdapter::LORA: + Serial.println("LoRa"); + break; + case NetworkAdapter::CATM1: + Serial.println("Category M1"); + break; + case NetworkAdapter::CELL: + Serial.println("Cellular"); + break; + default: + Serial.println("Unknown"); + break; + } +} + +void loop() { + /* Toggle the connection every `CONN_TOGGLE_MS` milliseconds */ + if ((millis() - lastConnToggleMs) > CONN_TOGGLE_MS) { + Serial.println("Toggling connection..."); + if (attemptConnect) { + conMan.connect(); + } else { + conMan.disconnect(); + } + attemptConnect = !attemptConnect; + lastConnToggleMs = millis(); + } + + /* The following code keeps on running connection workflows on our + * ConnectionHandler object, hence allowing reconnection in case of failure + * and notification of connect/disconnect event if enabled (see + * addConnectCallback/addDisconnectCallback) NOTE: any use of delay() within + * the loop or methods called from it will delay the execution of .update(), + * which might not guarantee the correct functioning of the ConnectionHandler + * object. + */ + conMan.check(); +} + +void onNetworkConnect() { + Serial.println(">>>> CONNECTED to network"); +} + +void onNetworkDisconnect() { + Serial.println(">>>> DISCONNECTED from network"); +} + +void onNetworkError() { + Serial.println(">>>> ERROR"); +} diff --git a/examples/GenericConnectionHandlerDemo/arduino_secrets.h b/examples/GenericConnectionHandlerDemo/arduino_secrets.h new file mode 100644 index 00000000..cecefa42 --- /dev/null +++ b/examples/GenericConnectionHandlerDemo/arduino_secrets.h @@ -0,0 +1,19 @@ +// Required for WiFiConnectionHandler +const char SECRET_WIFI_SSID[] = "SSID"; +const char SECRET_WIFI_PASS[] = "PASSWORD"; + +// Required for GSMConnectionHandler +const char SECRET_APN[] = "MOBILE PROVIDER APN ADDRESS"; +const char SECRET_PIN[] = "0000"; // Required for NBConnectionHandler +const char SECRET_GSM_USER[] = "GSM USERNAME"; +const char SECRET_GSM_PASS[] = "GSM PASSWORD"; + +// Required for LoRaConnectionHandler +const char SECRET_APP_EUI[] = "APP_EUI"; +const char SECRET_APP_KEY[] = "APP_KEY"; + +// Required for EthernetConnectionHandler (without DHCP mode) +const char SECRET_IP[] = "IP ADDRESS"; +const char SECRET_DNS[] = "DNS ADDRESS"; +const char SECRET_GATEWAY[] = "GATEWAY ADDRESS"; +const char SECRET_NETMASK[] = "NETWORK MASK"; diff --git a/extras/codespell-ignore-words-list.txt b/extras/codespell-ignore-words-list.txt deleted file mode 100644 index a991d7cd..00000000 --- a/extras/codespell-ignore-words-list.txt +++ /dev/null @@ -1 +0,0 @@ -wan \ No newline at end of file diff --git a/keywords.txt b/keywords.txt index 8d9e9434..f2176d69 100644 --- a/keywords.txt +++ b/keywords.txt @@ -10,12 +10,17 @@ WiFiConnectionHandler KEYWORD1 GSMConnectionHandler KEYWORD1 NBConnectionHandler KEYWORD1 LoRaConnectionHandler KEYWORD1 +EthernetConnectionHandler KEYWORD1 +CatM1ConnectionHandler KEYWORD1 #################################################### # Methods and Functions (KEYWORD2) #################################################### ConnectionHandler KEYWORD2 +available KEYWORD2 +read KEYWORD2 +write KEYWORD2 check KEYWORD2 connect KEYWORD2 disconnect KEYWORD2 diff --git a/library.properties b/library.properties index ca969568..48f42491 100644 --- a/library.properties +++ b/library.properties @@ -1,10 +1,10 @@ name=Arduino_ConnectionHandler -version=0.4.7 +version=1.2.0 author=Ubi de Feo, Cristian Maglie, Andrea Catozzi, Alexander Entinger et al. -maintainer=Arduino.cc +maintainer=Arduino sentence=Arduino Library for network connection management (WiFi, GSM, NB, [Ethernet]) paragraph=Originally part of ArduinoIoTCloud category=Communication url=https://github.com/arduino-libraries/Arduino_ConnectionHandler -architectures=samd,esp32,esp8266 +architectures=samd,esp32,esp8266,mbed,megaavr,mbed_nano,mbed_portenta,mbed_nicla,mbed_opta,mbed_giga,renesas_portenta,renesas_uno,mbed_edge,stm32,rp2040 depends=Arduino_DebugUtils, WiFi101, WiFiNINA, MKRGSM, MKRNB, MKRWAN diff --git a/src/Arduino_ConnectionHandler.cpp b/src/Arduino_ConnectionHandler.cpp deleted file mode 100644 index 51f63fc8..00000000 --- a/src/Arduino_ConnectionHandler.cpp +++ /dev/null @@ -1,124 +0,0 @@ -/* - This file is part of ArduinoIoTCloud. - - Copyright 2019 ARDUINO SA (http://www.arduino.cc/) - - This software is released under the GNU General Public License version 3, - which covers the main part of arduino-cli. - The terms of this license can be found at: - https://www.gnu.org/licenses/gpl-3.0.en.html - - You can be released from the requirements of the above licenses by purchasing - a commercial license. Buying such a license is mandatory if you want to modify or - otherwise use the software for commercial activities involving the Arduino - software without disclosing the source code of your own applications. To purchase - a commercial license, send an email to license@arduino.cc. -*/ - -/****************************************************************************** - INCLUDE - ******************************************************************************/ - -#include "Arduino_ConnectionHandler.h" - -/****************************************************************************** - CONSTRUCTOR/DESTRUCTOR - ******************************************************************************/ - -ConnectionHandler::ConnectionHandler(bool const keep_alive) -: _keep_alive{keep_alive} -, _current_net_connection_state{NetworkConnectionState::INIT} -, _lastConnectionTickTime{millis()} -{ - -} - -/****************************************************************************** - PUBLIC MEMBER FUNCTIONS - ******************************************************************************/ - -NetworkConnectionState ConnectionHandler::check() -{ - unsigned long const now = millis(); - unsigned int const connectionTickTimeInterval = CHECK_INTERVAL_TABLE[static_cast(_current_net_connection_state)]; - - if((now - _lastConnectionTickTime) > connectionTickTimeInterval) - { - _lastConnectionTickTime = now; - NetworkConnectionState next_net_connection_state = _current_net_connection_state; - - /* While the state machine is implemented here, the concrete implementation of the - * states is done in the derived connection handlers. - */ - switch (_current_net_connection_state) - { - case NetworkConnectionState::INIT: next_net_connection_state = update_handleInit (); break; - case NetworkConnectionState::CONNECTING: next_net_connection_state = update_handleConnecting (); break; - case NetworkConnectionState::CONNECTED: next_net_connection_state = update_handleConnected (); break; - case NetworkConnectionState::DISCONNECTING: next_net_connection_state = update_handleDisconnecting(); break; - case NetworkConnectionState::DISCONNECTED: next_net_connection_state = update_handleDisconnected (); break; - case NetworkConnectionState::ERROR: break; - case NetworkConnectionState::CLOSED: break; - } - - /* Here we are determining whether a state transition from one state to the next has - * occurred - and if it has, we call eventually registered callbacks. - */ - if(next_net_connection_state != _current_net_connection_state) - { - /* Check the next state to determine the kind of state conversion which has occurred (and call the appropriate callback) */ - if(next_net_connection_state == NetworkConnectionState::CONNECTED) - { - if(_on_connect_event_callback) _on_connect_event_callback(); - } - if(next_net_connection_state == NetworkConnectionState::DISCONNECTED) - { - if(_on_disconnect_event_callback) _on_disconnect_event_callback(); - } - if(next_net_connection_state == NetworkConnectionState::ERROR) - { - if(_on_error_event_callback) _on_error_event_callback(); - } - - /* Assign new state to the member variable holding the state */ - _current_net_connection_state = next_net_connection_state; - } - } - - return _current_net_connection_state; -} - -void ConnectionHandler::connect() -{ - if (_current_net_connection_state != NetworkConnectionState::INIT && _current_net_connection_state != NetworkConnectionState::CONNECTING) - { - _keep_alive = true; - _current_net_connection_state = NetworkConnectionState::INIT; - } -} - -void ConnectionHandler::disconnect() -{ - _keep_alive = false; - _current_net_connection_state = NetworkConnectionState::DISCONNECTING; -} - -void ConnectionHandler::addCallback(NetworkConnectionEvent const event, OnNetworkEventCallback callback) -{ - switch (event) - { - case NetworkConnectionEvent::CONNECTED: _on_connect_event_callback = callback; break; - case NetworkConnectionEvent::DISCONNECTED: _on_disconnect_event_callback = callback; break; - case NetworkConnectionEvent::ERROR: _on_error_event_callback = callback; break; - } -} - -void ConnectionHandler::addConnectCallback(OnNetworkEventCallback callback) { - _on_connect_event_callback = callback; -} -void ConnectionHandler::addDisconnectCallback(OnNetworkEventCallback callback) { - _on_disconnect_event_callback = callback; -} -void ConnectionHandler::addErrorCallback(OnNetworkEventCallback callback) { - _on_error_event_callback = callback; -} diff --git a/src/Arduino_ConnectionHandler.h b/src/Arduino_ConnectionHandler.h index 64520189..8153c45e 100644 --- a/src/Arduino_ConnectionHandler.h +++ b/src/Arduino_ConnectionHandler.h @@ -1,215 +1,53 @@ /* - This file is part of ArduinoIoTCloud. + This file is part of the Arduino_ConnectionHandler library. - Copyright 2019 ARDUINO SA (http://www.arduino.cc/) + Copyright (c) 2019 Arduino SA - This software is released under the GNU General Public License version 3, - which covers the main part of arduino-cli. - The terms of this license can be found at: - https://www.gnu.org/licenses/gpl-3.0.en.html - - You can be released from the requirements of the above licenses by purchasing - a commercial license. Buying such a license is mandatory if you want to modify or - otherwise use the software for commercial activities involving the Arduino - software without disclosing the source code of your own applications. To purchase - a commercial license, send an email to license@arduino.cc. + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef ARDUINO_CONNECTION_HANDLER_H_ #define ARDUINO_CONNECTION_HANDLER_H_ -#ifdef ARDUINO_SAMD_MKR1000 - #include - #include +/****************************************************************************** + INCLUDES + ******************************************************************************/ - #define BOARD_HAS_WIFI - #define NETWORK_HARDWARE_ERROR WL_NO_SHIELD - #define NETWORK_IDLE_STATUS WL_IDLE_STATUS - #define NETWORK_CONNECTED WL_CONNECTED - #define WIFI_FIRMWARE_VERSION_REQUIRED WIFI_FIRMWARE_REQUIRED +#if !defined(__AVR__) +# include #endif -#if defined(ARDUINO_SAMD_MKRWIFI1010) || defined(ARDUINO_SAMD_NANO_33_IOT) - #include - #include +#include +#include "ConnectionHandlerDefinitions.h" - #define BOARD_HAS_WIFI - #define NETWORK_HARDWARE_ERROR WL_NO_MODULE - #define NETWORK_IDLE_STATUS WL_IDLE_STATUS - #define NETWORK_CONNECTED WL_CONNECTED - #define WIFI_FIRMWARE_VERSION_REQUIRED WIFI_FIRMWARE_LATEST_VERSION +#if defined(BOARD_HAS_WIFI) + #include "WiFiConnectionHandler.h" #endif -#ifdef ARDUINO_SAMD_MKRGSM1400 - #include - #define BOARD_HAS_GSM - #define NETWORK_HARDWARE_ERROR GPRS_PING_ERROR - #define NETWORK_IDLE_STATUS GSM3_NetworkStatus_t::IDLE - #define NETWORK_CONNECTED GSM3_NetworkStatus_t::GPRS_READY +#if defined(BOARD_HAS_GSM) + #include "GSMConnectionHandler.h" #endif -#ifdef ARDUINO_SAMD_MKRNB1500 - #include - #define BOARD_HAS_NB - #define NETWORK_HARDWARE_ERROR - #define NETWORK_IDLE_STATUS NB_NetworkStatus_t::IDLE - #define NETWORK_CONNECTED NB_NetworkStatus_t::GPRS_READY +#if defined(BOARD_HAS_NB) + #include "NBConnectionHandler.h" #endif -#if defined(ARDUINO_SAMD_MKRWAN1300) || defined(ARDUINO_SAMD_MKRWAN1310) - #include - #define BOARD_HAS_LORA +#if defined(BOARD_HAS_LORA) + #include "LoRaConnectionHandler.h" #endif -#if defined(ARDUINO_ESP8266_ESP12) \ - || defined(ESP8266) \ - || defined(ESP8266_ESP01) \ - || defined(ESP8266_ESP13) \ - || defined(ESP8266_GENERIC) \ - || defined(ESP8266_ESPRESSO_LITE_V1) \ - || defined(ESP8266_ESPRESSO_LITE_V2) \ - || defined(ESP8266_PHOENIX_V1) \ - || defined(ESP8266_PHOENIX_V2) \ - || defined(ESP8266_NODEMCU) \ - || defined(MOD_WIFI_ESP8266) \ - || defined(ESP8266_THING) \ - || defined(ESP8266_THING_DEV) \ - || defined(ESP8266_ESP210) \ - || defined(ESP8266_WEMOS_D1MINI) \ - || defined(ESP8266_WEMOS_D1MINIPRO) \ - || defined(ESP8266_WEMOS_D1MINILITE) \ - || defined(ESP8266_WEMOS_D1R1) \ - || defined(ESP8266_ESP12) \ - || defined(WIFINFO) \ - || defined(ESP8266_ARDUINO) \ - || defined(GEN4_IOD) \ - || defined(ESP8266_OAK) \ - || defined(WIFIDUINO_ESP8266) \ - || defined(AMPERKA_WIFI_SLOT) \ - || defined(ESP8266_WIO_LINK) \ - || defined(ESP8266_ESPECTRO_CORE) - - #define BOARD_ESP8266 +#if defined(BOARD_HAS_ETHERNET) + #include "EthernetConnectionHandler.h" #endif -#if defined(BOARD_ESP8266) - #include - #include - - #define BOARD_HAS_WIFI - #define NETWORK_HARDWARE_ERROR WL_NO_SHIELD - #define NETWORK_IDLE_STATUS WL_IDLE_STATUS - #define NETWORK_CONNECTED WL_CONNECTED - #define WIFI_FIRMWARE_VERSION_REQUIRED WIFI_FIRMWARE_REQUIRED +#if defined(BOARD_HAS_CATM1_NBIOT) + #include "CatM1ConnectionHandler.h" #endif -/****************************************************************************** - INCLUDES - ******************************************************************************/ - -#include - -/****************************************************************************** - TYPEDEFS - ******************************************************************************/ - -enum class NetworkConnectionState : unsigned int { - INIT = 0, - CONNECTING = 1, - CONNECTED = 2, - DISCONNECTING = 3, - DISCONNECTED = 4, - CLOSED = 5, - ERROR = 6 -}; - -enum class NetworkConnectionEvent { - CONNECTED, - DISCONNECTED, - ERROR -}; - -typedef void (*OnNetworkEventCallback)(); - -/****************************************************************************** - CONSTANTS - ******************************************************************************/ - -static unsigned int const CHECK_INTERVAL_TABLE[] = -{ - /* INIT */ 100, - /* CONNECTING */ 500, - /* CONNECTED */ 10000, - /* DISCONNECTING */ 100, - /* DISCONNECTED */ 1000, - /* CLOSED */ 1000, - /* ERROR */ 1000 -}; - -/****************************************************************************** - CLASS DECLARATION - ******************************************************************************/ - -class ConnectionHandler { - public: - - ConnectionHandler(bool const keep_alive); - - - NetworkConnectionState check(); - - #if defined(BOARD_HAS_WIFI) || defined(BOARD_HAS_GSM) || defined(BOARD_HAS_NB) - virtual unsigned long getTime() = 0; - virtual Client &getClient() = 0; - virtual UDP &getUDP() = 0; - #endif - - #if defined(BOARD_HAS_LORA) - virtual int write(const uint8_t *buf, size_t size) = 0; - virtual int read() = 0; - virtual bool available() = 0; - #endif - - NetworkConnectionState getStatus() __attribute__((deprecated)) { - return _current_net_connection_state; - } - - void connect(); - void disconnect(); - - void addCallback(NetworkConnectionEvent const event, OnNetworkEventCallback callback); - void addConnectCallback(OnNetworkEventCallback callback) __attribute__((deprecated)); - void addDisconnectCallback(OnNetworkEventCallback callback) __attribute__((deprecated)); - void addErrorCallback(OnNetworkEventCallback callback) __attribute__((deprecated)); - - protected: - - bool _keep_alive; - - virtual NetworkConnectionState update_handleInit () = 0; - virtual NetworkConnectionState update_handleConnecting () = 0; - virtual NetworkConnectionState update_handleConnected () = 0; - virtual NetworkConnectionState update_handleDisconnecting() = 0; - virtual NetworkConnectionState update_handleDisconnected () = 0; - - - private: - - unsigned long _lastConnectionTickTime; - NetworkConnectionState _current_net_connection_state; - OnNetworkEventCallback _on_connect_event_callback = NULL, - _on_disconnect_event_callback = NULL, - _on_error_event_callback = NULL; -}; - -#if defined(BOARD_HAS_WIFI) - #include "Arduino_WiFiConnectionHandler.h" -#elif defined(BOARD_HAS_GSM) - #include "Arduino_GSMConnectionHandler.h" -#elif defined(BOARD_HAS_NB) - #include "Arduino_NBConnectionHandler.h" -#elif defined(BOARD_HAS_LORA) - #include "Arduino_LoRaConnectionHandler.h" +#if defined(BOARD_HAS_CELLULAR) + #include "CellularConnectionHandler.h" #endif #endif /* CONNECTION_HANDLER_H_ */ diff --git a/src/Arduino_GSMConnectionHandler.cpp b/src/Arduino_GSMConnectionHandler.cpp deleted file mode 100644 index 629699b6..00000000 --- a/src/Arduino_GSMConnectionHandler.cpp +++ /dev/null @@ -1,128 +0,0 @@ -/* - This file is part of ArduinoIoTCloud. - - Copyright 2019 ARDUINO SA (http://www.arduino.cc/) - - This software is released under the GNU General Public License version 3, - which covers the main part of arduino-cli. - The terms of this license can be found at: - https://www.gnu.org/licenses/gpl-3.0.en.html - - You can be released from the requirements of the above licenses by purchasing - a commercial license. Buying such a license is mandatory if you want to modify or - otherwise use the software for commercial activities involving the Arduino - software without disclosing the source code of your own applications. To purchase - a commercial license, send an email to license@arduino.cc. -*/ - -/****************************************************************************** - INCLUDE - ******************************************************************************/ - -#include "Arduino_GSMConnectionHandler.h" - -#ifdef BOARD_HAS_GSM /* Only compile if this is a board with GSM */ - -/****************************************************************************** - CONSTANTS - ******************************************************************************/ - -static int const GSM_TIMEOUT = 30000; - -/****************************************************************************** - CTOR/DTOR - ******************************************************************************/ - -GSMConnectionHandler::GSMConnectionHandler(const char * pin, const char * apn, const char * login, const char * pass, bool const keep_alive) -: ConnectionHandler{keep_alive} -, _pin(pin) -, _apn(apn) -, _login(login) -, _pass(pass) -{ - -} - -/****************************************************************************** - PUBLIC MEMBER FUNCTIONS - ******************************************************************************/ - -unsigned long GSMConnectionHandler::getTime() -{ - return _gsm.getTime(); -} - -/****************************************************************************** - PROTECTED MEMBER FUNCTIONS - ******************************************************************************/ - -NetworkConnectionState GSMConnectionHandler::update_handleInit() -{ - if (_gsm.begin(_pin) != GSM_READY) - { - Debug.print(DBG_ERROR, "SIM not present or wrong PIN"); - return NetworkConnectionState::ERROR; - } - - Debug.print(DBG_INFO, "SIM card ok"); - _gsm.setTimeout(GSM_TIMEOUT); - - GSM3_NetworkStatus_t const network_status = _gprs.attachGPRS(_apn, _login, _pass, true); - Debug.print(DBG_DEBUG, "GPRS.attachGPRS(): %d", network_status); - if (network_status == GSM3_NetworkStatus_t::ERROR) - { - Debug.print(DBG_ERROR, "GPRS attach failed"); - Debug.print(DBG_ERROR, "Make sure the antenna is connected and reset your board."); - return NetworkConnectionState::ERROR; - } - - return NetworkConnectionState::CONNECTING; -} - -NetworkConnectionState GSMConnectionHandler::update_handleConnecting() -{ - Debug.print(DBG_INFO, "Sending PING to outer space..."); - int const ping_result = _gprs.ping("time.arduino.cc"); - Debug.print(DBG_INFO, "GPRS.ping(): %d", ping_result); - if (ping_result < 0) - { - Debug.print(DBG_ERROR, "PING failed"); - Debug.print(DBG_INFO, "Retrying in \"%d\" milliseconds", CHECK_INTERVAL_TABLE[static_cast(NetworkConnectionState::CONNECTING)]); - return NetworkConnectionState::CONNECTING; - } - else - { - Debug.print(DBG_INFO, "Connected to GPRS Network"); - return NetworkConnectionState::CONNECTED; - } -} - -NetworkConnectionState GSMConnectionHandler::update_handleConnected() -{ - int const is_gsm_access_alive = _gsm.isAccessAlive(); - if (is_gsm_access_alive != 1) - { - return NetworkConnectionState::DISCONNECTED; - } - return NetworkConnectionState::CONNECTED; -} - -NetworkConnectionState GSMConnectionHandler::update_handleDisconnecting() -{ - _gsm.shutdown(); - return NetworkConnectionState::DISCONNECTED; -} - -NetworkConnectionState GSMConnectionHandler::update_handleDisconnected() -{ - if (_keep_alive) - { - return NetworkConnectionState::INIT; - } - else - { - return NetworkConnectionState::CLOSED; - } -} - -#endif /* #ifdef BOARD_HAS_GSM */ diff --git a/src/Arduino_LoRaConnectionHandler.cpp b/src/Arduino_LoRaConnectionHandler.cpp deleted file mode 100644 index d3b86c97..00000000 --- a/src/Arduino_LoRaConnectionHandler.cpp +++ /dev/null @@ -1,170 +0,0 @@ -/* - This file is part of ArduinoIoTCloud. - - Copyright 2019 ARDUINO SA (http://www.arduino.cc/) - - This software is released under the GNU General Public License version 3, - which covers the main part of arduino-cli. - The terms of this license can be found at: - https://www.gnu.org/licenses/gpl-3.0.en.html - - You can be released from the requirements of the above licenses by purchasing - a commercial license. Buying such a license is mandatory if you want to modify or - otherwise use the software for commercial activities involving the Arduino - software without disclosing the source code of your own applications. To purchase - a commercial license, send an email to license@arduino.cc. -*/ - -/****************************************************************************** - INCLUDE - ******************************************************************************/ - -#if defined(ARDUINO_SAMD_MKRWAN1300) || defined(ARDUINO_SAMD_MKRWAN1310) /* Only compile if the board has LoRa */ - -#include "Arduino_LoRaConnectionHandler.h" - -/****************************************************************************** - TYPEDEF - ******************************************************************************/ - -typedef enum -{ - LORA_ERROR_ACK_NOT_RECEIVED = -1, - LORA_ERROR_GENERIC = -2, - LORA_ERROR_WRONG_PARAM = -3, - LORA_ERROR_COMMUNICATION_BUSY = -4, - LORA_ERROR_MESSAGE_OVERFLOW = -5, - LORA_ERROR_NO_NETWORK_AVAILABLE = -6, - LORA_ERROR_RX_PACKET = -7, - LORA_ERROR_REASON_UNKNOWN = -8, - LORA_ERROR_MAX_PACKET_SIZE = -20 -} LoRaCommunicationError; - -/****************************************************************************** - CTOR/DTOR - ******************************************************************************/ - -LoRaConnectionHandler::LoRaConnectionHandler(char const * appeui, char const * appkey, _lora_band const band, _lora_class const device_class) -: ConnectionHandler{false} -, _appeui(appeui) -, _appkey(appkey) -, _band(band) -, _device_class(device_class) -{ - -} - -/****************************************************************************** - PUBLIC MEMBER FUNCTIONS - ******************************************************************************/ - -int LoRaConnectionHandler::write(const uint8_t * buf, size_t size) -{ - _modem.beginPacket(); - _modem.write(buf, size); - int const err = _modem.endPacket(true); - - if (err != size) - { - switch (err) - { - case LoRaCommunicationError::LORA_ERROR_ACK_NOT_RECEIVED: Debug.print(DBG_ERROR, "Message ack was not received, the message could not be delivered"); break; - case LoRaCommunicationError::LORA_ERROR_GENERIC: Debug.print(DBG_ERROR, "LoRa generic error (LORA_ERROR)"); break; - case LoRaCommunicationError::LORA_ERROR_WRONG_PARAM: Debug.print(DBG_ERROR, "LoRa malformed param error (LORA_ERROR_PARAM"); break; - case LoRaCommunicationError::LORA_ERROR_COMMUNICATION_BUSY: Debug.print(DBG_ERROR, "LoRa chip is busy (LORA_ERROR_BUSY)"); break; - case LoRaCommunicationError::LORA_ERROR_MESSAGE_OVERFLOW: Debug.print(DBG_ERROR, "LoRa chip overflow error (LORA_ERROR_OVERFLOW)"); break; - case LoRaCommunicationError::LORA_ERROR_NO_NETWORK_AVAILABLE: Debug.print(DBG_ERROR, "LoRa no network error (LORA_ERROR_NO_NETWORK)"); break; - case LoRaCommunicationError::LORA_ERROR_RX_PACKET: Debug.print(DBG_ERROR, "LoRa rx error (LORA_ERROR_RX)"); break; - case LoRaCommunicationError::LORA_ERROR_REASON_UNKNOWN: Debug.print(DBG_ERROR, "LoRa unknown error (LORA_ERROR_UNKNOWN)"); break; - case LoRaCommunicationError::LORA_ERROR_MAX_PACKET_SIZE: Debug.print(DBG_ERROR, "Message length is bigger than max LoRa packet!"); break; - } - } - else - { - Debug.print(DBG_INFO, "Message sent correctly!"); - } - return err; -} - -int LoRaConnectionHandler::read() -{ - return _modem.read(); -} - -bool LoRaConnectionHandler::available() -{ - return _modem.available(); -} - -/****************************************************************************** - PROTECTED MEMBER FUNCTIONS - ******************************************************************************/ - -NetworkConnectionState LoRaConnectionHandler::update_handleInit() -{ - if (!_modem.begin(_band)) - { - Debug.print(DBG_ERROR, "Something went wrong; are you indoor? Move near a window, then reset and retry."); - return NetworkConnectionState::ERROR; - } - //A delay is required between _modem.begin(band) and _modem.joinOTAA(appeui, appkey) in order to let the chip to be correctly initialized before the connection attempt - delay(100); - _modem.configureClass(_device_class); - delay(100); - Debug.print(DBG_INFO, "Connecting to the network"); - return NetworkConnectionState::CONNECTING; -} - -NetworkConnectionState LoRaConnectionHandler::update_handleConnecting() -{ - bool const network_status = _modem.joinOTAA(_appeui, _appkey); - if (network_status != true) - { - Debug.print(DBG_ERROR, "Something went wrong; are you indoor? Move near a window, then reset and retry."); - return NetworkConnectionState::ERROR; - } - else - { - Debug.print(DBG_INFO, "Connected to the network"); - return NetworkConnectionState::CONNECTED; - } -} - -NetworkConnectionState LoRaConnectionHandler::update_handleConnected() -{ - bool const network_status = _modem.connected(); - if (network_status != true) - { - Debug.print(DBG_ERROR, "Connection to the network lost."); - if (_keep_alive) - { - Debug.print(DBG_ERROR, "Attempting reconnection"); - } - return NetworkConnectionState::DISCONNECTED; - } - return NetworkConnectionState::CONNECTED; -} - -NetworkConnectionState LoRaConnectionHandler::update_handleDisconnecting() -{ - Debug.print(DBG_ERROR, "Connection to the network lost."); - if (_keep_alive) - { - Debug.print(DBG_ERROR, "Attempting reconnection"); - } - return NetworkConnectionState::DISCONNECTED; -} - -NetworkConnectionState LoRaConnectionHandler::update_handleDisconnected() -{ - if (_keep_alive) - { - return NetworkConnectionState::INIT; - } - else - { - return NetworkConnectionState::CLOSED; - } -} - -#endif diff --git a/src/Arduino_LoRaConnectionHandler.h b/src/Arduino_LoRaConnectionHandler.h deleted file mode 100644 index a0cff734..00000000 --- a/src/Arduino_LoRaConnectionHandler.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - This file is part of ArduinoIoTCloud. - - Copyright 2019 ARDUINO SA (http://www.arduino.cc/) - - This software is released under the GNU General Public License version 3, - which covers the main part of arduino-cli. - The terms of this license can be found at: - https://www.gnu.org/licenses/gpl-3.0.en.html - - You can be released from the requirements of the above licenses by purchasing - a commercial license. Buying such a license is mandatory if you want to modify or - otherwise use the software for commercial activities involving the Arduino - software without disclosing the source code of your own applications. To purchase - a commercial license, send an email to license@arduino.cc. -*/ - -#ifndef ARDUINO_LORA_CONNECTION_HANDLER_H_ -#define ARDUINO_LORA_CONNECTION_HANDLER_H_ - -/****************************************************************************** - INCLUDE - ******************************************************************************/ - -#include "Arduino_ConnectionHandler.h" - -/****************************************************************************** - CLASS DECLARATION - ******************************************************************************/ - -class LoRaConnectionHandler : public ConnectionHandler -{ - public: - - LoRaConnectionHandler(char const * appeui, char const * appkey, _lora_band const band = _lora_band::EU868, _lora_class const device_class = _lora_class::CLASS_A); - - - virtual int write(const uint8_t *buf, size_t size) override; - virtual int read() override; - virtual bool available() override; - - - protected: - - virtual NetworkConnectionState update_handleInit () override; - virtual NetworkConnectionState update_handleConnecting () override; - virtual NetworkConnectionState update_handleConnected () override; - virtual NetworkConnectionState update_handleDisconnecting() override; - virtual NetworkConnectionState update_handleDisconnected () override; - - - private: - - char const * _appeui; - char const * _appkey; - _lora_band _band; - _lora_class _device_class; - LoRaModem _modem; -}; - -#endif /* ARDUINO_LORA_CONNECTION_HANDLER_H_ */ diff --git a/src/Arduino_WiFiConnectionHandler.cpp b/src/Arduino_WiFiConnectionHandler.cpp deleted file mode 100644 index 24bbceb0..00000000 --- a/src/Arduino_WiFiConnectionHandler.cpp +++ /dev/null @@ -1,148 +0,0 @@ -/* - This file is part of ArduinoIoTCloud. - - Copyright 2019 ARDUINO SA (http://www.arduino.cc/) - - This software is released under the GNU General Public License version 3, - which covers the main part of arduino-cli. - The terms of this license can be found at: - https://www.gnu.org/licenses/gpl-3.0.en.html - - You can be released from the requirements of the above licenses by purchasing - a commercial license. Buying such a license is mandatory if you want to modify or - otherwise use the software for commercial activities involving the Arduino - software without disclosing the source code of your own applications. To purchase - a commercial license, send an email to license@arduino.cc. -*/ - -/****************************************************************************** - INCLUDE - ******************************************************************************/ - -#include "Arduino_WiFiConnectionHandler.h" - -#ifdef BOARD_HAS_WIFI /* Only compile if the board has WiFi */ - -/****************************************************************************** - CTOR/DTOR - ******************************************************************************/ - -WiFiConnectionHandler::WiFiConnectionHandler(char const * ssid, char const * pass, bool const keep_alive) -: ConnectionHandler{keep_alive} -, _ssid{ssid} -, _pass{pass} -{ - -} - -/****************************************************************************** - PUBLIC MEMBER FUNCTIONS - ******************************************************************************/ - -unsigned long WiFiConnectionHandler::getTime() -{ -#if !defined(BOARD_ESP8266) - return WiFi.getTime(); -#else - return 0; -#endif -} - -/****************************************************************************** - PROTECTED MEMBER FUNCTIONS - ******************************************************************************/ - -NetworkConnectionState WiFiConnectionHandler::update_handleInit() -{ -#ifndef BOARD_ESP8266 - Debug.print(DBG_INFO, "WiFi.status(): %d", WiFi.status()); - if (WiFi.status() == NETWORK_HARDWARE_ERROR) - { - Debug.print(DBG_ERROR, "WiFi Hardware failure.\nMake sure you are using a WiFi enabled board/shield."); - Debug.print(DBG_ERROR, "Then reset and retry."); - return NetworkConnectionState::ERROR; - } - - Debug.print(DBG_ERROR, "Current WiFi Firmware: %s", WiFi.firmwareVersion()); - - if (WiFi.firmwareVersion() < WIFI_FIRMWARE_VERSION_REQUIRED) - { - Debug.print(DBG_ERROR, "Latest WiFi Firmware: %s", WIFI_FIRMWARE_VERSION_REQUIRED); - Debug.print(DBG_ERROR, "Please update to the latest version for best performance."); - delay(5000); - } -#else - Debug.print(DBG_ERROR, "WiFi status ESP: %d", WiFi.status()); - WiFi.disconnect(); - delay(300); - WiFi.begin(_ssid, _pass); - delay(1000); -#endif /* ifndef BOARD_ESP8266 */ - - return NetworkConnectionState::CONNECTING; -} - -NetworkConnectionState WiFiConnectionHandler::update_handleConnecting() -{ -#ifndef BOARD_ESP8266 - if (WiFi.status() != WL_CONNECTED) - { - WiFi.begin(_ssid, _pass); - } -#endif /* ifndef BOARD_ESP8266 */ - - if (WiFi.status() != NETWORK_CONNECTED) - { - Debug.print(DBG_ERROR, "Connection to \"%s\" failed", _ssid); - Debug.print(DBG_INFO, "Retrying in \"%d\" milliseconds", CHECK_INTERVAL_TABLE[static_cast(NetworkConnectionState::CONNECTING)]); - return NetworkConnectionState::CONNECTING; - } - else - { - Debug.print(DBG_INFO, "Connected to \"%s\"", _ssid); -#ifdef BOARD_ESP8266 - configTime(0, 0, "time.arduino.cc", "pool.ntp.org", "time.nist.gov"); -#endif - return NetworkConnectionState::CONNECTED; - } -} - -NetworkConnectionState WiFiConnectionHandler::update_handleConnected() -{ - if (WiFi.status() != WL_CONNECTED) - { - Debug.print(DBG_VERBOSE, "WiFi.status(): %d", WiFi.status()); - Debug.print(DBG_ERROR, "Connection to \"%s\" lost.", _ssid); - - if (_keep_alive) - { - Debug.print(DBG_ERROR, "Attempting reconnection"); - } - - return NetworkConnectionState::DISCONNECTED; - } - return NetworkConnectionState::CONNECTED; -} - -NetworkConnectionState WiFiConnectionHandler::update_handleDisconnecting() -{ - WiFi.disconnect(); - return NetworkConnectionState::DISCONNECTED; -} - -NetworkConnectionState WiFiConnectionHandler::update_handleDisconnected() -{ -#ifndef BOARD_ESP8266 - WiFi.end(); -#endif /* ifndef BOARD_ESP8266 */ - if (_keep_alive) - { - return NetworkConnectionState::INIT; - } - else - { - return NetworkConnectionState::CLOSED; - } -} - -#endif /* #ifdef BOARD_HAS_WIFI */ diff --git a/src/Arduino_WiFiConnectionHandler.h b/src/Arduino_WiFiConnectionHandler.h deleted file mode 100644 index 56670793..00000000 --- a/src/Arduino_WiFiConnectionHandler.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - This file is part of ArduinoIoTCloud. - - Copyright 2019 ARDUINO SA (http://www.arduino.cc/) - - This software is released under the GNU General Public License version 3, - which covers the main part of arduino-cli. - The terms of this license can be found at: - https://www.gnu.org/licenses/gpl-3.0.en.html - - You can be released from the requirements of the above licenses by purchasing - a commercial license. Buying such a license is mandatory if you want to modify or - otherwise use the software for commercial activities involving the Arduino - software without disclosing the source code of your own applications. To purchase - a commercial license, send an email to license@arduino.cc. -*/ - -#ifndef ARDUINO_WIFI_CONNECTION_HANDLER_H_ -#define ARDUINO_WIFI_CONNECTION_HANDLER_H_ - -/****************************************************************************** - INCLUDE - ******************************************************************************/ - -#include "Arduino_ConnectionHandler.h" - -#ifdef BOARD_HAS_WIFI /* Only compile if the board has WiFi */ - -/****************************************************************************** - CLASS DECLARATION - ******************************************************************************/ - -class WiFiConnectionHandler : public ConnectionHandler -{ - public: - - WiFiConnectionHandler(char const * ssid, char const * pass, bool const keep_alive = true); - - - virtual unsigned long getTime() override; - virtual Client & getClient() override{ return _wifi_client; } - virtual UDP & getUDP() override { return _wifi_udp; } - - - protected: - - virtual NetworkConnectionState update_handleInit () override; - virtual NetworkConnectionState update_handleConnecting () override; - virtual NetworkConnectionState update_handleConnected () override; - virtual NetworkConnectionState update_handleDisconnecting() override; - virtual NetworkConnectionState update_handleDisconnected () override; - - private: - - char const * _ssid; - char const * _pass; - - WiFiUDP _wifi_udp; - WiFiClient _wifi_client; -}; - -#endif /* #ifdef BOARD_HAS_WIFI */ - -#endif /* ARDUINO_WIFI_CONNECTION_HANDLER_H_ */ diff --git a/src/CatM1ConnectionHandler.cpp b/src/CatM1ConnectionHandler.cpp new file mode 100644 index 00000000..16f0db93 --- /dev/null +++ b/src/CatM1ConnectionHandler.cpp @@ -0,0 +1,143 @@ +/* + This file is part of the Arduino_ConnectionHandler library. + + Copyright (c) 2023 Arduino SA + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ + +/****************************************************************************** + INCLUDE + ******************************************************************************/ + +#include "ConnectionHandlerDefinitions.h" + +#ifdef BOARD_HAS_CATM1_NBIOT /* Only compile if the board has CatM1 BN-IoT */ +#include "CatM1ConnectionHandler.h" + +/****************************************************************************** + CTOR/DTOR + ******************************************************************************/ + +CatM1ConnectionHandler::CatM1ConnectionHandler() +: ConnectionHandler(true, NetworkAdapter::CATM1) { } + +CatM1ConnectionHandler::CatM1ConnectionHandler( + const char * pin, const char * apn, const char * login, const char * pass, + RadioAccessTechnologyType rat, uint32_t band, bool const keep_alive) +: ConnectionHandler{keep_alive, NetworkAdapter::CATM1} +{ + _settings.type = NetworkAdapter::CATM1; + // To keep the backward compatibility, the user can call enableCheckInternetAvailability(false) for disabling the check + _check_internet_availability = true; + strncpy(_settings.catm1.pin, pin, sizeof(_settings.catm1.pin)-1); + strncpy(_settings.catm1.apn, apn, sizeof(_settings.catm1.apn)-1); + strncpy(_settings.catm1.login, login, sizeof(_settings.catm1.login)-1); + strncpy(_settings.catm1.pass, pass, sizeof(_settings.catm1.pass)-1); + _settings.catm1.rat = static_cast(rat); + _settings.catm1.band = band; + _reset = false; +} + +/****************************************************************************** + PUBLIC MEMBER FUNCTIONS + ******************************************************************************/ + +unsigned long CatM1ConnectionHandler::getTime() +{ + /* It is not safe to call GSM.getTime() since we don't know if modem internal + * RTC is in sync with current time. + */ + return 0; +} + +/****************************************************************************** + PROTECTED MEMBER FUNCTIONS + ******************************************************************************/ + +NetworkConnectionState CatM1ConnectionHandler::update_handleInit() +{ +#if defined (ARDUINO_EDGE_CONTROL) + /* Power on module */ + pinMode(ON_MKR2, OUTPUT); + digitalWrite(ON_MKR2, HIGH); +#endif + + if(!GSM.begin( + _settings.catm1.pin, + _settings.catm1.apn, + _settings.catm1.login, + _settings.catm1.pass, + static_cast(_settings.catm1.rat) , + _settings.catm1.band, + _reset)) + { + DEBUG_ERROR(F("The board was not able to register to the network...")); + _reset = true; + return NetworkConnectionState::DISCONNECTED; + } + _reset = false; + return NetworkConnectionState::CONNECTING; +} + +NetworkConnectionState CatM1ConnectionHandler::update_handleConnecting() +{ + if (!GSM.isConnected()) + { + DEBUG_ERROR(F("GSM connection not alive... disconnecting")); + return NetworkConnectionState::DISCONNECTED; + } + + if(!_check_internet_availability){ + return NetworkConnectionState::CONNECTED; + } + + DEBUG_INFO(F("Sending PING to outer space...")); + int const ping_result = GSM.ping("time.arduino.cc"); + DEBUG_INFO(F("GSM.ping(): %d"), ping_result); + if (ping_result < 0) + { + DEBUG_ERROR(F("Internet check failed")); + DEBUG_INFO(F("Retrying in \"%d\" milliseconds"), _timeoutTable.timeout.connecting); + return NetworkConnectionState::CONNECTING; + } + else + { + DEBUG_INFO(F("Connected to Internet")); + return NetworkConnectionState::CONNECTED; + } +} + +NetworkConnectionState CatM1ConnectionHandler::update_handleConnected() +{ + int const is_gsm_access_alive = GSM.isConnected(); + if (is_gsm_access_alive != 1) + { + DEBUG_ERROR(F("GSM connection not alive... disconnecting")); + return NetworkConnectionState::DISCONNECTED; + } + return NetworkConnectionState::CONNECTED; +} + +NetworkConnectionState CatM1ConnectionHandler::update_handleDisconnecting() +{ + GSM.disconnect(); + return NetworkConnectionState::DISCONNECTED; +} + +NetworkConnectionState CatM1ConnectionHandler::update_handleDisconnected() +{ + GSM.end(); + if (_keep_alive) + { + return NetworkConnectionState::INIT; + } + else + { + return NetworkConnectionState::CLOSED; + } +} + +#endif /* #ifdef BOARD_HAS_CATM1_NBIOT */ diff --git a/src/CatM1ConnectionHandler.h b/src/CatM1ConnectionHandler.h new file mode 100644 index 00000000..23115898 --- /dev/null +++ b/src/CatM1ConnectionHandler.h @@ -0,0 +1,62 @@ +/* + This file is part of the Arduino_ConnectionHandler library. + + Copyright (c) 2023 Arduino SA + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ + +#ifndef ARDUINO_CATM1_CONNECTION_HANDLER_H_ +#define ARDUINO_CATM1_CONNECTION_HANDLER_H_ + +/****************************************************************************** + INCLUDE + ******************************************************************************/ + +#include "ConnectionHandlerInterface.h" + +#if defined(ARDUINO_PORTENTA_H7_M7) || defined(ARDUINO_EDGE_CONTROL) + #include +#endif + +#ifndef BOARD_HAS_CATM1_NBIOT + #error "Board doesn't support CATM1_NBIOT" +#endif + +/****************************************************************************** + CLASS DECLARATION + ******************************************************************************/ + +class CatM1ConnectionHandler : public ConnectionHandler +{ + public: + + CatM1ConnectionHandler(); + CatM1ConnectionHandler(const char * pin, const char * apn, const char * login, const char * pass, RadioAccessTechnologyType rat = CATM1, uint32_t band = BAND_3 | BAND_20 | BAND_19, bool const keep_alive = true); + + + virtual unsigned long getTime() override; + virtual Client & getClient() override { return _gsm_client; }; + virtual UDP & getUDP() override { return _gsm_udp; }; + + + protected: + + virtual NetworkConnectionState update_handleInit () override; + virtual NetworkConnectionState update_handleConnecting () override; + virtual NetworkConnectionState update_handleConnected () override; + virtual NetworkConnectionState update_handleDisconnecting() override; + virtual NetworkConnectionState update_handleDisconnected () override; + + + private: + + bool _reset; + + GSMUDP _gsm_udp; + GSMClient _gsm_client; +}; + +#endif /* #ifndef ARDUINO_CATM1_CONNECTION_HANDLER_H_ */ diff --git a/src/CellularConnectionHandler.cpp b/src/CellularConnectionHandler.cpp new file mode 100644 index 00000000..b73f5866 --- /dev/null +++ b/src/CellularConnectionHandler.cpp @@ -0,0 +1,114 @@ +/* + This file is part of the Arduino_ConnectionHandler library. + + Copyright (c) 2024 Arduino SA + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ + + +/****************************************************************************** + INCLUDE + ******************************************************************************/ + +#include "ConnectionHandlerDefinitions.h" + +#ifdef BOARD_HAS_CELLULAR /* Only compile if the board has Cellular */ +#include "CellularConnectionHandler.h" + +/****************************************************************************** + CTOR/DTOR + ******************************************************************************/ +CellularConnectionHandler::CellularConnectionHandler() +: ConnectionHandler(true, NetworkAdapter::CELL) {} + +CellularConnectionHandler::CellularConnectionHandler(const char * pin, const char * apn, const char * login, const char * pass, bool const keep_alive) +: ConnectionHandler{keep_alive, NetworkAdapter::CELL} +{ + _settings.type = NetworkAdapter::CELL; + strncpy(_settings.cell.pin, pin, sizeof(_settings.cell.pin)-1); + strncpy(_settings.cell.apn, apn, sizeof(_settings.cell.apn)-1); + strncpy(_settings.cell.login, login, sizeof(_settings.cell.login)-1); + strncpy(_settings.cell.pass, pass, sizeof(_settings.cell.pass)-1); + +} + +/****************************************************************************** + PUBLIC MEMBER FUNCTIONS + ******************************************************************************/ + +unsigned long CellularConnectionHandler::getTime() +{ + return _cellular.getCellularTime().getUNIXTimestamp(); +} + +UDP & CellularConnectionHandler::getUDP() +{ + DEBUG_ERROR(F("CellularConnectionHandler has no UDP support")); + while(1) {}; +} + +/****************************************************************************** + PROTECTED MEMBER FUNCTIONS + ******************************************************************************/ + +NetworkConnectionState CellularConnectionHandler::update_handleInit() +{ + _cellular.begin(); + _cellular.setDebugStream(Serial); + if (strlen(_settings.cell.pin) > 0 && !_cellular.unlockSIM(_settings.cell.pin)) { + DEBUG_ERROR(F("SIM not present or wrong PIN")); + return NetworkConnectionState::ERROR; + } + + if (!_cellular.connect(String(_settings.cell.apn), String(_settings.cell.login), String(_settings.cell.pass))) { + DEBUG_ERROR(F("The board was not able to register to the network...")); + return NetworkConnectionState::ERROR; + } + DEBUG_INFO(F("Connected to Network")); + return NetworkConnectionState::CONNECTING; +} + +NetworkConnectionState CellularConnectionHandler::update_handleConnecting() +{ + if (!_cellular.isConnectedToInternet()) { + return NetworkConnectionState::INIT; + } + + if (!_check_internet_availability) { + return NetworkConnectionState::CONNECTED; + } + + if(getTime() == 0){ + DEBUG_ERROR(F("Internet check failed")); + DEBUG_INFO(F("Retrying in \"%d\" milliseconds"), _timeoutTable.timeout.connecting); + return NetworkConnectionState::CONNECTING; + } + + return NetworkConnectionState::CONNECTED; +} + +NetworkConnectionState CellularConnectionHandler::update_handleConnected() +{ + if (!_cellular.isConnectedToInternet()) { + return NetworkConnectionState::DISCONNECTED; + } + return NetworkConnectionState::CONNECTED; +} + +NetworkConnectionState CellularConnectionHandler::update_handleDisconnecting() +{ + return NetworkConnectionState::DISCONNECTED; +} + +NetworkConnectionState CellularConnectionHandler::update_handleDisconnected() +{ + if (_keep_alive) { + return NetworkConnectionState::INIT; + } + return NetworkConnectionState::CLOSED; +} + +#endif /* #ifdef BOARD_HAS_CELLULAR */ diff --git a/src/CellularConnectionHandler.h b/src/CellularConnectionHandler.h new file mode 100644 index 00000000..7a5f00b1 --- /dev/null +++ b/src/CellularConnectionHandler.h @@ -0,0 +1,60 @@ +/* + This file is part of the Arduino_ConnectionHandler library. + + Copyright (c) 2024 Arduino SA + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ + + +#ifndef ARDUINO_CELLULAR_CONNECTION_HANDLER_H_ +#define ARDUINO_CELLULAR_CONNECTION_HANDLER_H_ + +/****************************************************************************** + INCLUDE + ******************************************************************************/ + +#include "ConnectionHandlerInterface.h" + +#if defined(ARDUINO_PORTENTA_C33) || defined(ARDUINO_PORTENTA_H7_M7) +#include +#endif + +#ifndef BOARD_HAS_CELLULAR + #error "Board doesn't support CELLULAR" +#endif + +/****************************************************************************** + CLASS DECLARATION + ******************************************************************************/ + +class CellularConnectionHandler : public ConnectionHandler +{ + public: + CellularConnectionHandler(); + CellularConnectionHandler(const char * pin, const char * apn, const char * login, const char * pass, bool const keep_alive = true); + + + virtual unsigned long getTime() override; + virtual Client & getClient() override { return _gsm_client; }; + virtual UDP & getUDP() override; + + + protected: + + virtual NetworkConnectionState update_handleInit () override; + virtual NetworkConnectionState update_handleConnecting () override; + virtual NetworkConnectionState update_handleConnected () override; + virtual NetworkConnectionState update_handleDisconnecting() override; + virtual NetworkConnectionState update_handleDisconnected () override; + + + private: + + ArduinoCellular _cellular; + TinyGsmClient _gsm_client = _cellular.getNetworkClient(); +}; + +#endif /* #ifndef ARDUINO_CELLULAR_CONNECTION_HANDLER_H_ */ diff --git a/src/ConnectionHandlerDefinitions.h b/src/ConnectionHandlerDefinitions.h new file mode 100644 index 00000000..969ecd19 --- /dev/null +++ b/src/ConnectionHandlerDefinitions.h @@ -0,0 +1,201 @@ +/* + This file is part of the Arduino_ConnectionHandler library. + + Copyright (c) 2024 Arduino SA + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +/****************************************************************************** + INCLUDES + ******************************************************************************/ + +#include + +#ifdef ARDUINO_SAMD_MKR1000 + #define BOARD_HAS_WIFI + #define NETWORK_HARDWARE_ERROR WL_NO_SHIELD + #define NETWORK_IDLE_STATUS WL_IDLE_STATUS + #define NETWORK_CONNECTED WL_CONNECTED + #define WIFI_FIRMWARE_VERSION_REQUIRED WIFI_FIRMWARE_REQUIRED +#endif + +#if defined(ARDUINO_SAMD_MKRWIFI1010) || defined(ARDUINO_SAMD_NANO_33_IOT) || \ + defined(ARDUINO_AVR_UNO_WIFI_REV2) || defined (ARDUINO_NANO_RP2040_CONNECT) + + #define BOARD_HAS_WIFI + #define NETWORK_HARDWARE_ERROR WL_NO_MODULE + #define NETWORK_IDLE_STATUS WL_IDLE_STATUS + #define NETWORK_CONNECTED WL_CONNECTED + #define WIFI_FIRMWARE_VERSION_REQUIRED WIFI_FIRMWARE_LATEST_VERSION +#endif + +#if defined(ARDUINO_PORTENTA_H7_M7) + #define BOARD_HAS_WIFI + #define BOARD_HAS_ETHERNET + #define BOARD_HAS_CATM1_NBIOT + #define BOARD_HAS_CELLULAR + #define BOARD_HAS_PORTENTA_CATM1_NBIOT_SHIELD + #define BOARD_HAS_PORTENTA_VISION_SHIELD_ETHERNET + #define NETWORK_HARDWARE_ERROR WL_NO_SHIELD + #define NETWORK_IDLE_STATUS WL_IDLE_STATUS + #define NETWORK_CONNECTED WL_CONNECTED +#endif + +#if defined(ARDUINO_PORTENTA_C33) + #define BOARD_HAS_WIFI + #define BOARD_HAS_ETHERNET + #define BOARD_HAS_CELLULAR + #define BOARD_HAS_PORTENTA_VISION_SHIELD_ETHERNET + #define NETWORK_HARDWARE_ERROR WL_NO_SHIELD + #define NETWORK_IDLE_STATUS WL_IDLE_STATUS + #define NETWORK_CONNECTED WL_CONNECTED +#endif + +#if defined(ARDUINO_NICLA_VISION) + #define BOARD_HAS_WIFI + #define NETWORK_HARDWARE_ERROR WL_NO_SHIELD + #define NETWORK_IDLE_STATUS WL_IDLE_STATUS + #define NETWORK_CONNECTED WL_CONNECTED +#endif + +#if defined(ARDUINO_OPTA) + #define BOARD_HAS_WIFI + #define BOARD_HAS_ETHERNET + #define NETWORK_HARDWARE_ERROR WL_NO_SHIELD + #define NETWORK_IDLE_STATUS WL_IDLE_STATUS + #define NETWORK_CONNECTED WL_CONNECTED +#endif + +#if defined(ARDUINO_GIGA) + + #define BOARD_HAS_WIFI + #define NETWORK_HARDWARE_ERROR WL_NO_SHIELD + #define NETWORK_IDLE_STATUS WL_IDLE_STATUS + #define NETWORK_CONNECTED WL_CONNECTED +#endif + +#ifdef ARDUINO_SAMD_MKRGSM1400 + #define BOARD_HAS_GSM + #define NETWORK_HARDWARE_ERROR GPRS_PING_ERROR + #define NETWORK_IDLE_STATUS GSM3_NetworkStatus_t::IDLE + #define NETWORK_CONNECTED GSM3_NetworkStatus_t::GPRS_READY +#endif + +#ifdef ARDUINO_SAMD_MKRNB1500 + #define BOARD_HAS_NB + #define NETWORK_HARDWARE_ERROR + #define NETWORK_IDLE_STATUS NB_NetworkStatus_t::IDLE + #define NETWORK_CONNECTED NB_NetworkStatus_t::GPRS_READY +#endif + +#if defined(ARDUINO_SAMD_MKRWAN1300) || defined(ARDUINO_SAMD_MKRWAN1310) + #define BOARD_HAS_LORA +#endif + +#if defined(ARDUINO_ARCH_ESP8266) + + #define BOARD_HAS_WIFI + #define NETWORK_HARDWARE_ERROR WL_NO_SHIELD + #define NETWORK_IDLE_STATUS WL_IDLE_STATUS + #define NETWORK_CONNECTED WL_CONNECTED + #define WIFI_FIRMWARE_VERSION_REQUIRED WIFI_FIRMWARE_REQUIRED +#endif + +#if defined(ARDUINO_ARCH_ESP32) + #define BOARD_HAS_WIFI + #define NETWORK_HARDWARE_ERROR WL_NO_SHIELD + #define NETWORK_IDLE_STATUS WL_IDLE_STATUS + #define NETWORK_CONNECTED WL_CONNECTED + #define WIFI_FIRMWARE_VERSION_REQUIRED WIFI_FIRMWARE_REQUIRED +#endif + +#if defined(ARDUINO_UNOR4_WIFI) + + #define BOARD_HAS_WIFI + #define NETWORK_HARDWARE_ERROR WL_NO_SHIELD + #define NETWORK_IDLE_STATUS WL_IDLE_STATUS + #define NETWORK_CONNECTED WL_CONNECTED + #define WIFI_FIRMWARE_VERSION_REQUIRED WIFI_FIRMWARE_LATEST_VERSION +#endif + +#ifdef ARDUINO_EDGE_CONTROL + #define BOARD_HAS_CATM1_NBIOT + #define BOARD_HAS_PORTENTA_CATM1_NBIOT_SHIELD + #define NETWORK_HARDWARE_ERROR +#endif + +#if defined(ARDUINO_RASPBERRY_PI_PICO_W) + #define BOARD_HAS_WIFI + #define NETWORK_HARDWARE_ERROR WL_NO_SHIELD + #define NETWORK_IDLE_STATUS WL_IDLE_STATUS + #define NETWORK_CONNECTED WL_CONNECTED +#endif + +/****************************************************************************** + TYPEDEFS + ******************************************************************************/ + +enum class NetworkConnectionState : unsigned int { + INIT = 0, + CONNECTING = 1, + CONNECTED = 2, + DISCONNECTING = 3, + DISCONNECTED = 4, + CLOSED = 5, + ERROR = 6 +}; + +enum class NetworkConnectionEvent { + CONNECTED, + DISCONNECTED, + ERROR +}; + +enum class NetworkAdapter { + NONE, + WIFI, + ETHERNET, + NB, + GSM, + LORA, + CATM1, + CELL +}; + +union TimeoutTable { + struct { + // Note: order of the following values must be preserved + // and match against NetworkConnectionState values + uint32_t init; + uint32_t connecting; + uint32_t connected; + uint32_t disconnecting; + uint32_t disconnected; + uint32_t closed; + uint32_t error; + } timeout; + uint32_t intervals[sizeof(timeout) / sizeof(uint32_t)]; +}; + +/****************************************************************************** + CONSTANTS + ******************************************************************************/ + +constexpr TimeoutTable DefaultTimeoutTable { +#if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32) + 4000, // init +#else + 500, // init +#endif + 500, // connecting + 10000, // connected + 100, // disconnecting + 1000, // disconnected + 1000, // closed + 1000, // error +}; diff --git a/src/ConnectionHandlerInterface.cpp b/src/ConnectionHandlerInterface.cpp new file mode 100644 index 00000000..e206b850 --- /dev/null +++ b/src/ConnectionHandlerInterface.cpp @@ -0,0 +1,141 @@ +/* + This file is part of the Arduino_ConnectionHandler library. + + Copyright (c) 2024 Arduino SA + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ + +/****************************************************************************** + INCLUDE + ******************************************************************************/ + +#include "ConnectionHandlerInterface.h" + +/****************************************************************************** + CONSTRUCTOR/DESTRUCTOR + ******************************************************************************/ + +ConnectionHandler::ConnectionHandler(bool const keep_alive, NetworkAdapter interface) +: _keep_alive{keep_alive} +, _check_internet_availability{false} +, _interface{interface} +, _lastConnectionTickTime{millis()} +, _current_net_connection_state{NetworkConnectionState::INIT} +, _timeoutTable(DefaultTimeoutTable) +{ + +} + +/****************************************************************************** + PUBLIC MEMBER FUNCTIONS + ******************************************************************************/ + +NetworkConnectionState ConnectionHandler::check() +{ + unsigned long const now = millis(); + unsigned int const connectionTickTimeInterval = + _timeoutTable.intervals[static_cast(_current_net_connection_state)]; + + if((now - _lastConnectionTickTime) > connectionTickTimeInterval) + { + _lastConnectionTickTime = now; + + NetworkConnectionState old_net_connection_state = _current_net_connection_state; + NetworkConnectionState next_net_connection_state = updateConnectionState(); + + /* Here we are determining whether a state transition from one state to the next has + * occurred - and if it has, we call eventually registered callbacks. + */ + + if(old_net_connection_state != next_net_connection_state) { + updateCallback(next_net_connection_state); + + /* It may happen that the local _current_net_connection_state + * is not updated by the updateConnectionState() call. This is the case for GenericConnection handler + * where the call of updateConnectionState() is replaced by the inner ConnectionHandler call + * that updates its state, but not the outer one. For this reason it is required to perform this call twice + */ + _current_net_connection_state = next_net_connection_state; + } + } + + return _current_net_connection_state; +} + +NetworkConnectionState ConnectionHandler::updateConnectionState() { + NetworkConnectionState next_net_connection_state = _current_net_connection_state; + + /* While the state machine is implemented here, the concrete implementation of the + * states is done in the derived connection handlers. + */ + switch (_current_net_connection_state) + { + case NetworkConnectionState::INIT: next_net_connection_state = update_handleInit (); break; + case NetworkConnectionState::CONNECTING: next_net_connection_state = update_handleConnecting (); break; + case NetworkConnectionState::CONNECTED: next_net_connection_state = update_handleConnected (); break; + case NetworkConnectionState::DISCONNECTING: next_net_connection_state = update_handleDisconnecting(); break; + case NetworkConnectionState::DISCONNECTED: next_net_connection_state = update_handleDisconnected (); break; + case NetworkConnectionState::ERROR: break; + case NetworkConnectionState::CLOSED: break; + } + + /* Assign new state to the member variable holding the state */ + _current_net_connection_state = next_net_connection_state; + + return next_net_connection_state; +} + +void ConnectionHandler::updateCallback(NetworkConnectionState next_net_connection_state) { + + /* Check the next state to determine the kind of state conversion which has occurred (and call the appropriate callback) */ + if(next_net_connection_state == NetworkConnectionState::CONNECTED) + { + if(_on_connect_event_callback) _on_connect_event_callback(); + } + if(next_net_connection_state == NetworkConnectionState::DISCONNECTED) + { + if(_on_disconnect_event_callback) _on_disconnect_event_callback(); + } + if(next_net_connection_state == NetworkConnectionState::ERROR) + { + if(_on_error_event_callback) _on_error_event_callback(); + } +} + +void ConnectionHandler::connect() +{ + if (_current_net_connection_state != NetworkConnectionState::INIT && _current_net_connection_state != NetworkConnectionState::CONNECTING) + { + _keep_alive = true; + _current_net_connection_state = NetworkConnectionState::INIT; + } +} + +void ConnectionHandler::disconnect() +{ + _keep_alive = false; + _current_net_connection_state = NetworkConnectionState::DISCONNECTING; +} + +void ConnectionHandler::addCallback(NetworkConnectionEvent const event, OnNetworkEventCallback callback) +{ + switch (event) + { + case NetworkConnectionEvent::CONNECTED: _on_connect_event_callback = callback; break; + case NetworkConnectionEvent::DISCONNECTED: _on_disconnect_event_callback = callback; break; + case NetworkConnectionEvent::ERROR: _on_error_event_callback = callback; break; + } +} + +void ConnectionHandler::addConnectCallback(OnNetworkEventCallback callback) { + _on_connect_event_callback = callback; +} +void ConnectionHandler::addDisconnectCallback(OnNetworkEventCallback callback) { + _on_disconnect_event_callback = callback; +} +void ConnectionHandler::addErrorCallback(OnNetworkEventCallback callback) { + _on_error_event_callback = callback; +} diff --git a/src/ConnectionHandlerInterface.h b/src/ConnectionHandlerInterface.h new file mode 100644 index 00000000..cfdebd38 --- /dev/null +++ b/src/ConnectionHandlerInterface.h @@ -0,0 +1,138 @@ +/* + This file is part of the Arduino_ConnectionHandler library. + + Copyright (c) 2024 Arduino SA + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +/****************************************************************************** + INCLUDES + ******************************************************************************/ + +#if !defined(__AVR__) +# include +#endif + +#include +#include +#include +#include "ConnectionHandlerDefinitions.h" +#include "connectionHandlerModels/settings.h" + +#include + +/****************************************************************************** + TYPEDEFS + ******************************************************************************/ + +typedef void (*OnNetworkEventCallback)(); + +/****************************************************************************** + CLASS DECLARATION + ******************************************************************************/ + +// forward declaration FIXME +class GenericConnectionHandler; + +class ConnectionHandler { + public: + + ConnectionHandler(bool const keep_alive=true, NetworkAdapter interface=NetworkAdapter::NONE); + + virtual ~ConnectionHandler() {} + + virtual NetworkConnectionState check(); + + #if not defined(BOARD_HAS_LORA) + virtual unsigned long getTime() = 0; + #endif + + #if defined(BOARD_HAS_NOTECARD) || defined(BOARD_HAS_LORA) + virtual bool available() = 0; + virtual int read() = 0; + virtual int write(const uint8_t *buf, size_t size) = 0; + #else + virtual Client &getClient() = 0; + virtual UDP &getUDP() = 0; + #endif + + NetworkConnectionState getStatus() __attribute__((deprecated)) { + return _current_net_connection_state; + } + + NetworkAdapter getInterface() { + return _interface; + } + + virtual void connect(); + virtual void disconnect(); + void enableCheckInternetAvailability(bool enable) { + _check_internet_availability = enable; + } + + virtual void addCallback(NetworkConnectionEvent const event, OnNetworkEventCallback callback); + void addConnectCallback(OnNetworkEventCallback callback) __attribute__((deprecated)); + void addDisconnectCallback(OnNetworkEventCallback callback) __attribute__((deprecated)); + void addErrorCallback(OnNetworkEventCallback callback) __attribute__((deprecated)); + + /** + * Update the interface settings. This can be performed only when the interface is + * in INIT state. otherwise nothing is performed. The type of the interface should match + * the type of the settings provided + * + * @return true if the update is successful, false otherwise + */ + virtual bool updateSetting(const models::NetworkSetting& s) { + if(_current_net_connection_state == NetworkConnectionState::INIT && s.type == _interface) { + memcpy(&_settings, &s, sizeof(s)); + return true; + } + + return false; + } + + virtual void getSetting(models::NetworkSetting& s) { + memcpy(&s, &_settings, sizeof(s)); + return; + } + + virtual void setKeepAlive(bool keep_alive=true) { this->_keep_alive = keep_alive; } + + inline void updateTimeoutTable(const TimeoutTable& t) { _timeoutTable = t; } + inline void updateTimeoutTable(TimeoutTable&& t) { _timeoutTable = std::move(t); } + inline void updateTimeoutInterval(NetworkConnectionState state, uint32_t interval) { + _timeoutTable.intervals[static_cast(state)] = interval; + } + protected: + + virtual NetworkConnectionState updateConnectionState(); + virtual void updateCallback(NetworkConnectionState next_net_connection_state); + + bool _keep_alive; + bool _check_internet_availability; + NetworkAdapter _interface; + + virtual NetworkConnectionState update_handleInit () = 0; + virtual NetworkConnectionState update_handleConnecting () = 0; + virtual NetworkConnectionState update_handleConnected () = 0; + virtual NetworkConnectionState update_handleDisconnecting() = 0; + virtual NetworkConnectionState update_handleDisconnected () = 0; + + models::NetworkSetting _settings; + + TimeoutTable _timeoutTable; + private: + + unsigned long _lastConnectionTickTime; + NetworkConnectionState _current_net_connection_state; + OnNetworkEventCallback _on_connect_event_callback = NULL, + _on_disconnect_event_callback = NULL, + _on_error_event_callback = NULL; + + friend GenericConnectionHandler; +}; diff --git a/src/EthernetConnectionHandler.cpp b/src/EthernetConnectionHandler.cpp new file mode 100644 index 00000000..9ef06cfb --- /dev/null +++ b/src/EthernetConnectionHandler.cpp @@ -0,0 +1,160 @@ +/* + This file is part of the Arduino_ConnectionHandler library. + + Copyright (c) 2020 Arduino SA + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ + +/****************************************************************************** + INCLUDE + ******************************************************************************/ + +#include "ConnectionHandlerDefinitions.h" + +#ifdef BOARD_HAS_ETHERNET /* Only compile if the board has ethernet */ +#include "EthernetConnectionHandler.h" + +/****************************************************************************** + CTOR/DTOR + ******************************************************************************/ + +static inline void fromIPAddress(const IPAddress src, models::ip_addr& dst) { + if(src.type() == IPv4) { + dst.dword[IPADDRESS_V4_DWORD_INDEX] = (uint32_t)src; + } else if(src.type() == IPv6) { + for(uint8_t i=0; i static ip configuration + if (ip != INADDR_NONE) { + if (Ethernet.begin(nullptr, ip, + IPAddress(_settings.eth.dns.type, _settings.eth.dns.bytes), + IPAddress(_settings.eth.gateway.type, _settings.eth.gateway.bytes), + IPAddress(_settings.eth.netmask.type, _settings.eth.netmask.bytes), + _settings.eth.timeout, + _settings.eth.response_timeout) == 0) { + + DEBUG_ERROR(F("Failed to configure Ethernet, check cable connection")); + DEBUG_VERBOSE("timeout: %d, response timeout: %d", + _settings.eth.timeout, _settings.eth.response_timeout); + return NetworkConnectionState::INIT; + } + // An ip address is not provided -> dhcp configuration + } else { + if (Ethernet.begin(nullptr, _settings.eth.timeout, _settings.eth.response_timeout) == 0) { + DEBUG_ERROR(F("Waiting Ethernet configuration from DHCP server, check cable connection")); + DEBUG_VERBOSE("timeout: %d, response timeout: %d", + _settings.eth.timeout, _settings.eth.response_timeout); + + return NetworkConnectionState::INIT; + } + } + + return NetworkConnectionState::CONNECTING; +} + +NetworkConnectionState EthernetConnectionHandler::update_handleConnecting() +{ + if (Ethernet.linkStatus() == LinkOFF) { + return NetworkConnectionState::INIT; + } + + if (!_check_internet_availability) { + return NetworkConnectionState::CONNECTED; + } + + int ping_result = Ethernet.ping("time.arduino.cc"); + DEBUG_INFO(F("Ethernet.ping(): %d"), ping_result); + if (ping_result < 0) + { + DEBUG_ERROR(F("Internet check failed")); + DEBUG_INFO(F("Retrying in \"%d\" milliseconds"), _timeoutTable.timeout.connecting); + return NetworkConnectionState::CONNECTING; + } + else + { + DEBUG_INFO(F("Connected to Internet")); + return NetworkConnectionState::CONNECTED; + } + +} + +NetworkConnectionState EthernetConnectionHandler::update_handleConnected() +{ + if (Ethernet.linkStatus() == LinkOFF) { + DEBUG_ERROR(F("Ethernet link OFF, connection lost.")); + if (_keep_alive) + { + DEBUG_ERROR(F("Attempting reconnection")); + } + return NetworkConnectionState::DISCONNECTED; + } + return NetworkConnectionState::CONNECTED; +} + +NetworkConnectionState EthernetConnectionHandler::update_handleDisconnecting() +{ + Ethernet.disconnect(); + return NetworkConnectionState::DISCONNECTED; +} + +NetworkConnectionState EthernetConnectionHandler::update_handleDisconnected() +{ + if (_keep_alive) + { + return NetworkConnectionState::INIT; + } + else + { + return NetworkConnectionState::CLOSED; + } +} + +#endif /* #ifdef BOARD_HAS_ETHERNET */ diff --git a/src/EthernetConnectionHandler.h b/src/EthernetConnectionHandler.h new file mode 100644 index 00000000..82dc8933 --- /dev/null +++ b/src/EthernetConnectionHandler.h @@ -0,0 +1,76 @@ +/* + This file is part of the Arduino_ConnectionHandler library. + + Copyright (c) 2020 Arduino SA + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ + +#ifndef ARDUINO_ETHERNET_CONNECTION_HANDLER_H_ +#define ARDUINO_ETHERNET_CONNECTION_HANDLER_H_ + +/****************************************************************************** + INCLUDE + ******************************************************************************/ + +#include "ConnectionHandlerInterface.h" + +#if defined(ARDUINO_PORTENTA_H7_M7) + #include + #include +#elif defined(ARDUINO_PORTENTA_C33) + #include + #include +#elif defined(ARDUINO_OPTA) + #include + #include +#endif + +#ifndef BOARD_HAS_ETHERNET + #error "Board doesn't support ETHERNET" +#endif + +/****************************************************************************** + CLASS DECLARATION + ******************************************************************************/ + +class EthernetConnectionHandler : public ConnectionHandler +{ + public: + + EthernetConnectionHandler( + unsigned long const timeout = 15000, + unsigned long const responseTimeout = 4000, + bool const keep_alive = true); + + EthernetConnectionHandler( + const IPAddress ip, + const IPAddress dns, + const IPAddress gateway, + const IPAddress netmask, + unsigned long const timeout = 15000, + unsigned long const responseTimeout = 4000, + bool const keep_alive = true); + + virtual unsigned long getTime() override { return 0; } + virtual Client & getClient() override{ return _eth_client; } + virtual UDP & getUDP() override { return _eth_udp; } + + protected: + + virtual NetworkConnectionState update_handleInit () override; + virtual NetworkConnectionState update_handleConnecting () override; + virtual NetworkConnectionState update_handleConnected () override; + virtual NetworkConnectionState update_handleDisconnecting() override; + virtual NetworkConnectionState update_handleDisconnected () override; + + private: + + EthernetUDP _eth_udp; + EthernetClient _eth_client; + +}; + +#endif /* ARDUINO_ETHERNET_CONNECTION_HANDLER_H_ */ diff --git a/src/GSMConnectionHandler.cpp b/src/GSMConnectionHandler.cpp new file mode 100644 index 00000000..82362f88 --- /dev/null +++ b/src/GSMConnectionHandler.cpp @@ -0,0 +1,151 @@ +/* + This file is part of the Arduino_ConnectionHandler library. + + Copyright (c) 2019 Arduino SA + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ + +/****************************************************************************** + INCLUDE + ******************************************************************************/ + +#include "ConnectionHandlerDefinitions.h" + +#ifdef BOARD_HAS_GSM /* Only compile if this is a board with GSM */ +#include "GSMConnectionHandler.h" + +/****************************************************************************** + CONSTANTS + ******************************************************************************/ + +static int const GSM_TIMEOUT = 30000; +static int const GPRS_TIMEOUT = 30000; + +/****************************************************************************** + FUNCTION DEFINITION + ******************************************************************************/ + +__attribute__((weak)) void mkr_gsm_feed_watchdog() +{ + /* This function can be overwritten by a "strong" implementation + * in a higher level application, such as the ArduinoIoTCloud + * firmware stack. + */ +} + +/****************************************************************************** + CTOR/DTOR + ******************************************************************************/ +GSMConnectionHandler::GSMConnectionHandler() +: ConnectionHandler(true, NetworkAdapter::GSM) {} + +GSMConnectionHandler::GSMConnectionHandler(const char * pin, const char * apn, const char * login, const char * pass, bool const keep_alive) +: ConnectionHandler{keep_alive, NetworkAdapter::GSM} +{ + _settings.type = NetworkAdapter::GSM; + // To keep the backward compatibility, the user can call enableCheckInternetAvailability(false) for disabling the check + _check_internet_availability = true; + strncpy(_settings.gsm.pin, pin, sizeof(_settings.gsm.pin)-1); + strncpy(_settings.gsm.apn, apn, sizeof(_settings.gsm.apn)-1); + strncpy(_settings.gsm.login, login, sizeof(_settings.gsm.login)-1); + strncpy(_settings.gsm.pass, pass, sizeof(_settings.gsm.pass)-1); +} + +/****************************************************************************** + PUBLIC MEMBER FUNCTIONS + ******************************************************************************/ + +unsigned long GSMConnectionHandler::getTime() +{ + return _gsm.getTime(); +} + +/****************************************************************************** + PROTECTED MEMBER FUNCTIONS + ******************************************************************************/ + +NetworkConnectionState GSMConnectionHandler::update_handleInit() +{ + mkr_gsm_feed_watchdog(); + + if (_gsm.begin(_settings.gsm.pin) != GSM_READY) + { + DEBUG_ERROR(F("SIM not present or wrong PIN")); + return NetworkConnectionState::ERROR; + } + + mkr_gsm_feed_watchdog(); + + DEBUG_INFO(F("SIM card ok")); + _gsm.setTimeout(GSM_TIMEOUT); + _gprs.setTimeout(GPRS_TIMEOUT); + + mkr_gsm_feed_watchdog(); + + GSM3_NetworkStatus_t const network_status = _gprs.attachGPRS( + _settings.gsm.apn, _settings.gsm.login, _settings.gsm.pass, true); + DEBUG_DEBUG(F("GPRS.attachGPRS(): %d"), network_status); + if (network_status == GSM3_NetworkStatus_t::ERROR) + { + DEBUG_ERROR(F("GPRS attach failed")); + DEBUG_ERROR(F("Make sure the antenna is connected and reset your board.")); + return NetworkConnectionState::ERROR; + } + + return NetworkConnectionState::CONNECTING; +} + +NetworkConnectionState GSMConnectionHandler::update_handleConnecting() +{ + if(!_check_internet_availability){ + return NetworkConnectionState::CONNECTED; + } + + DEBUG_INFO(F("Sending PING to outer space...")); + int const ping_result = _gprs.ping("time.arduino.cc"); + DEBUG_INFO(F("GPRS.ping(): %d"), ping_result); + if (ping_result < 0) + { + DEBUG_ERROR(F("PING failed")); + DEBUG_INFO(F("Retrying in \"%d\" milliseconds"), _timeoutTable.timeout.connecting); + return NetworkConnectionState::CONNECTING; + } + else + { + DEBUG_INFO(F("Connected to GPRS Network")); + return NetworkConnectionState::CONNECTED; + } +} + +NetworkConnectionState GSMConnectionHandler::update_handleConnected() +{ + int const is_gsm_access_alive = _gsm.isAccessAlive(); + if (is_gsm_access_alive != 1) + { + return NetworkConnectionState::DISCONNECTED; + } + return NetworkConnectionState::CONNECTED; +} + +NetworkConnectionState GSMConnectionHandler::update_handleDisconnecting() +{ + _gsm.shutdown(); + return NetworkConnectionState::DISCONNECTED; +} + +NetworkConnectionState GSMConnectionHandler::update_handleDisconnected() +{ + if (_keep_alive) + { + return NetworkConnectionState::INIT; + } + else + { + return NetworkConnectionState::CLOSED; + } +} + +#endif /* #ifdef BOARD_HAS_GSM */ diff --git a/src/Arduino_GSMConnectionHandler.h b/src/GSMConnectionHandler.h similarity index 57% rename from src/Arduino_GSMConnectionHandler.h rename to src/GSMConnectionHandler.h index 714ed8c5..15e5047d 100644 --- a/src/Arduino_GSMConnectionHandler.h +++ b/src/GSMConnectionHandler.h @@ -1,40 +1,38 @@ /* - This file is part of ArduinoIoTCloud. + This file is part of the Arduino_ConnectionHandler library. - Copyright 2019 ARDUINO SA (http://www.arduino.cc/) + Copyright (c) 2019 Arduino SA - This software is released under the GNU General Public License version 3, - which covers the main part of arduino-cli. - The terms of this license can be found at: - https://www.gnu.org/licenses/gpl-3.0.en.html - - You can be released from the requirements of the above licenses by purchasing - a commercial license. Buying such a license is mandatory if you want to modify or - otherwise use the software for commercial activities involving the Arduino - software without disclosing the source code of your own applications. To purchase - a commercial license, send an email to license@arduino.cc. + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef GSM_CONNECTION_MANAGER_H_ #define GSM_CONNECTION_MANAGER_H_ /****************************************************************************** - INCLUDE + INCLUDE ******************************************************************************/ -#include "Arduino_ConnectionHandler.h" +#include "ConnectionHandlerInterface.h" +#if defined(ARDUINO_SAMD_MKRGSM1400) + #include +#endif -#ifdef BOARD_HAS_GSM /* Only compile if this is a board with GSM */ +#ifndef BOARD_HAS_GSM + #error "Board doesn't support GSM" +#endif /****************************************************************************** - CLASS DECLARATION + CLASS DECLARATION ******************************************************************************/ class GSMConnectionHandler : public ConnectionHandler { public: - + GSMConnectionHandler(); GSMConnectionHandler(const char * pin, const char * apn, const char * login, const char * pass, bool const keep_alive = true); @@ -54,17 +52,10 @@ class GSMConnectionHandler : public ConnectionHandler private: - const char * _pin; - const char * _apn; - const char * _login; - const char * _pass; - GSM _gsm; GPRS _gprs; GSMUDP _gsm_udp; GSMClient _gsm_client; }; -#endif /* #ifdef BOARD_HAS_GSM */ - #endif /* #ifndef GSM_CONNECTION_MANAGER_H_ */ diff --git a/src/GenericConnectionHandler.cpp b/src/GenericConnectionHandler.cpp new file mode 100644 index 00000000..a6076819 --- /dev/null +++ b/src/GenericConnectionHandler.cpp @@ -0,0 +1,160 @@ +/* + This file is part of the Arduino_ConnectionHandler library. + + Copyright (c) 2024 Arduino SA + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ + +/****************************************************************************** + INCLUDE + ******************************************************************************/ + +#include "GenericConnectionHandler.h" +#include "Arduino_ConnectionHandler.h" + +static inline ConnectionHandler* instantiate_handler(NetworkAdapter adapter); + +bool GenericConnectionHandler::updateSetting(const models::NetworkSetting& s) { + if(_ch != nullptr && _ch->_current_net_connection_state != NetworkConnectionState::INIT) { + // If the internal connection handler is already being used and not in INIT phase we cannot update the settings + return false; + } else if(_ch != nullptr && _ch->_current_net_connection_state == NetworkConnectionState::INIT && _interface != s.type) { + // If the internal connection handler is already being used and in INIT phase and the interface type is being changed + // -> we need to deallocate the previously allocated handler + + // if interface type is not being changed -> we just need to call updateSettings + delete _ch; + _ch = nullptr; + } + + if(_ch == nullptr) { + _ch = instantiate_handler(s.type); + } + + if(_ch != nullptr) { + _interface = s.type; + _ch->setKeepAlive(_keep_alive); + _ch->enableCheckInternetAvailability(_check_internet_availability); + return _ch->updateSetting(s); + } else { + _interface = NetworkAdapter::NONE; + + return false; + } +} + +void GenericConnectionHandler::getSetting(models::NetworkSetting& s) { + if(_ch != nullptr) { + _ch->getSetting(s); + } else { + s.type = NetworkAdapter::NONE; + } +} + +NetworkConnectionState GenericConnectionHandler::updateConnectionState() { + return _ch != nullptr ? _ch->updateConnectionState() : NetworkConnectionState::INIT; +} + +NetworkConnectionState GenericConnectionHandler::update_handleInit() { + return _ch != nullptr ? _ch->update_handleInit() : NetworkConnectionState::INIT; +} + +NetworkConnectionState GenericConnectionHandler::update_handleConnecting() { + return _ch != nullptr ? _ch->update_handleConnecting() : NetworkConnectionState::INIT; +} + +NetworkConnectionState GenericConnectionHandler::update_handleConnected() { + return _ch != nullptr ? _ch->update_handleConnected() : NetworkConnectionState::INIT; +} + +NetworkConnectionState GenericConnectionHandler::update_handleDisconnecting() { + return _ch != nullptr ? _ch->update_handleDisconnecting() : NetworkConnectionState::INIT; +} + +NetworkConnectionState GenericConnectionHandler::update_handleDisconnected() { + return _ch != nullptr ? _ch->update_handleDisconnected() : NetworkConnectionState::INIT; +} + +#if not (defined(BOARD_HAS_LORA) or defined(BOARD_HAS_NOTECARD)) +unsigned long GenericConnectionHandler::getTime() { + return _ch != nullptr ? _ch->getTime() : 0; +} + +Client & GenericConnectionHandler::getClient() { + return _ch->getClient(); // NOTE _ch may be nullptr +} + +UDP & GenericConnectionHandler::getUDP() { + return _ch->getUDP(); // NOTE _ch may be nullptr +} + +#endif // not (defined(BOARD_HAS_LORA) or defined(BOARD_HAS_NOTECARD)) + +void GenericConnectionHandler::connect() { + if(_ch!=nullptr) { + _ch->connect(); + } + ConnectionHandler::connect(); +} + +void GenericConnectionHandler::disconnect() { + if(_ch!=nullptr) { + _ch->disconnect(); + } + ConnectionHandler::disconnect(); +} + +void GenericConnectionHandler::setKeepAlive(bool keep_alive) { + _keep_alive = keep_alive; + + if(_ch!=nullptr) { + _ch->setKeepAlive(keep_alive); + } +} + +static inline ConnectionHandler* instantiate_handler(NetworkAdapter adapter) { + switch(adapter) { + #if defined(BOARD_HAS_WIFI) + case NetworkAdapter::WIFI: + return new WiFiConnectionHandler(); + break; + #endif + + #if defined(BOARD_HAS_ETHERNET) + case NetworkAdapter::ETHERNET: + return new EthernetConnectionHandler(); + break; + #endif + + #if defined(BOARD_HAS_NB) + case NetworkAdapter::NB: + return new NBConnectionHandler(); + break; + #endif + + #if defined(BOARD_HAS_GSM) + case NetworkAdapter::GSM: + return new GSMConnectionHandler(); + break; + #endif + + #if defined(BOARD_HAS_CATM1_NBIOT) + case NetworkAdapter::CATM1: + return new CatM1ConnectionHandler(); + break; + #endif + + #if defined(BOARD_HAS_CELLULAR) + case NetworkAdapter::CELL: + return new CellularConnectionHandler(); + break; + #endif + + default: + DEBUG_ERROR("Network adapter not supported by this platform: %d", adapter); + return nullptr; + } +} diff --git a/src/GenericConnectionHandler.h b/src/GenericConnectionHandler.h new file mode 100644 index 00000000..81df0f79 --- /dev/null +++ b/src/GenericConnectionHandler.h @@ -0,0 +1,74 @@ +/* + This file is part of the Arduino_ConnectionHandler library. + + Copyright (c) 2024 Arduino SA + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ + +#ifndef ARDUINO_GENERIC_CONNECTION_HANDLER_H_ +#define ARDUINO_GENERIC_CONNECTION_HANDLER_H_ + +/****************************************************************************** + INCLUDE + ******************************************************************************/ + +#include "ConnectionHandlerInterface.h" + +/****************************************************************************** + CLASS DECLARATION + ******************************************************************************/ + +/** GenericConnectionHandler class + * This class aims to wrap a connectionHandler and provide a generic way to + * instantiate a specific connectionHandler type + */ +class GenericConnectionHandler : public ConnectionHandler +{ + public: + + GenericConnectionHandler(bool const keep_alive=true): ConnectionHandler(keep_alive), _ch(nullptr) {} + + #if defined(BOARD_HAS_NOTECARD) || defined(BOARD_HAS_LORA) + virtual bool available() = 0; + virtual int read() = 0; + virtual int write(const uint8_t *buf, size_t size) = 0; + #else + unsigned long getTime() override; + + /* + * NOTE: The following functions have a huge risk of returning a reference to a non existing memory location + * It is important to make sure that the internal connection handler is already allocated before calling them + * When updateSettings is called and the internal connectionHandler is reallocated the references to TCP and UDP + * handles should be deleted. + */ + Client & getClient() override; + UDP & getUDP() override; + #endif + + bool updateSetting(const models::NetworkSetting& s) override; + void getSetting(models::NetworkSetting& s) override; + + void connect() override; + void disconnect() override; + + void setKeepAlive(bool keep_alive=true) override; + + protected: + + NetworkConnectionState updateConnectionState() override; + + NetworkConnectionState update_handleInit () override; + NetworkConnectionState update_handleConnecting () override; + NetworkConnectionState update_handleConnected () override; + NetworkConnectionState update_handleDisconnecting() override; + NetworkConnectionState update_handleDisconnected () override; + + private: + + ConnectionHandler* _ch; +}; + +#endif /* ARDUINO_GENERIC_CONNECTION_HANDLER_H_ */ diff --git a/src/LoRaConnectionHandler.cpp b/src/LoRaConnectionHandler.cpp new file mode 100644 index 00000000..19006bcd --- /dev/null +++ b/src/LoRaConnectionHandler.cpp @@ -0,0 +1,187 @@ +/* + This file is part of the Arduino_ConnectionHandler library. + + Copyright (c) 2019 Arduino SA + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ + +/****************************************************************************** + INCLUDE + ******************************************************************************/ + +#include "ConnectionHandlerDefinitions.h" + +#if defined(BOARD_HAS_LORA) /* Only compile if the board has LoRa */ +#include "LoRaConnectionHandler.h" + +/****************************************************************************** + TYPEDEF + ******************************************************************************/ + +typedef enum +{ + LORA_ERROR_ACK_NOT_RECEIVED = -1, + LORA_ERROR_GENERIC = -2, + LORA_ERROR_WRONG_PARAM = -3, + LORA_ERROR_COMMUNICATION_BUSY = -4, + LORA_ERROR_MESSAGE_OVERFLOW = -5, + LORA_ERROR_NO_NETWORK_AVAILABLE = -6, + LORA_ERROR_RX_PACKET = -7, + LORA_ERROR_REASON_UNKNOWN = -8, + LORA_ERROR_MAX_PACKET_SIZE = -20 +} LoRaCommunicationError; + +/****************************************************************************** + CTOR/DTOR + ******************************************************************************/ +LoRaConnectionHandler::LoRaConnectionHandler(char const * appeui, char const * appkey, _lora_band const band, char const * channelMask, _lora_class const device_class) +: ConnectionHandler{false, NetworkAdapter::LORA} +{ + _settings.type = NetworkAdapter::LORA; + strncpy(_settings.lora.appeui, appeui, sizeof(_settings.lora.appeui)-1); + strncpy(_settings.lora.appkey, appkey, sizeof(_settings.lora.appkey)-1); + _settings.lora.band = band; + strncpy(_settings.lora.channelMask, channelMask, sizeof(_settings.lora.channelMask)-1); + _settings.lora.deviceClass = device_class; +} + +/****************************************************************************** + PUBLIC MEMBER FUNCTIONS + ******************************************************************************/ + +int LoRaConnectionHandler::write(const uint8_t * buf, size_t size) +{ + _modem.beginPacket(); + _modem.write(buf, size); + int const err = _modem.endPacket(true); + + if (err != size) + { + switch (err) + { + case LoRaCommunicationError::LORA_ERROR_ACK_NOT_RECEIVED: + DEBUG_ERROR(F("Message ack was not received, the message could not be delivered")); + break; + case LoRaCommunicationError::LORA_ERROR_GENERIC: + DEBUG_ERROR(F("LoRa generic error (LORA_ERROR)")); + break; + case LoRaCommunicationError::LORA_ERROR_WRONG_PARAM: + DEBUG_ERROR(F("LoRa malformed param error (LORA_ERROR_PARAM")); + break; + case LoRaCommunicationError::LORA_ERROR_COMMUNICATION_BUSY: + DEBUG_ERROR(F("LoRa chip is busy (LORA_ERROR_BUSY)")); + break; + case LoRaCommunicationError::LORA_ERROR_MESSAGE_OVERFLOW: + DEBUG_ERROR(F("LoRa chip overflow error (LORA_ERROR_OVERFLOW)")); + break; + case LoRaCommunicationError::LORA_ERROR_NO_NETWORK_AVAILABLE: + DEBUG_ERROR(F("LoRa no network error (LORA_ERROR_NO_NETWORK)")); + break; + case LoRaCommunicationError::LORA_ERROR_RX_PACKET: + DEBUG_ERROR(F("LoRa rx error (LORA_ERROR_RX)")); + break; + case LoRaCommunicationError::LORA_ERROR_REASON_UNKNOWN: + DEBUG_ERROR(F("LoRa unknown error (LORA_ERROR_UNKNOWN)")); + break; + case LoRaCommunicationError::LORA_ERROR_MAX_PACKET_SIZE: + DEBUG_ERROR(F("Message length is bigger than max LoRa packet!")); + break; + } + } + else + { + DEBUG_INFO(F("Message sent correctly!")); + } + return err; +} + +int LoRaConnectionHandler::read() +{ + return _modem.read(); +} + +bool LoRaConnectionHandler::available() +{ + return _modem.available(); +} + +/****************************************************************************** + PROTECTED MEMBER FUNCTIONS + ******************************************************************************/ + +NetworkConnectionState LoRaConnectionHandler::update_handleInit() +{ + if (!_modem.begin((_lora_band)_settings.lora.band)) + { + DEBUG_ERROR(F("Something went wrong; are you indoor? Move near a window, then reset and retry.")); + return NetworkConnectionState::ERROR; + } + // Set channelmask based on configuration + if (_settings.lora.channelMask) { + _modem.sendMask(_settings.lora.channelMask); + } + //A delay is required between _modem.begin(band) and _modem.joinOTAA(appeui, appkey) in order to let the chip to be correctly initialized before the connection attempt + delay(100); + _modem.configureClass((_lora_class)_settings.lora.deviceClass); + delay(100); + DEBUG_INFO(F("Connecting to the network")); + return NetworkConnectionState::CONNECTING; +} + +NetworkConnectionState LoRaConnectionHandler::update_handleConnecting() +{ + bool const network_status = _modem.joinOTAA(_settings.lora.appeui, _settings.lora.appkey); + if (network_status != true) + { + DEBUG_ERROR(F("Connection to the network failed")); + DEBUG_INFO(F("Retrying in \"%d\" milliseconds"), _timeoutTable.timeout.connecting); + return NetworkConnectionState::INIT; + } + else + { + DEBUG_INFO(F("Connected to the network")); + return NetworkConnectionState::CONNECTED; + } +} + +NetworkConnectionState LoRaConnectionHandler::update_handleConnected() +{ + bool const network_status = _modem.connected(); + if (network_status != true) + { + DEBUG_ERROR(F("Connection to the network lost.")); + if (_keep_alive) + { + DEBUG_ERROR(F("Attempting reconnection")); + } + return NetworkConnectionState::DISCONNECTED; + } + return NetworkConnectionState::CONNECTED; +} + +NetworkConnectionState LoRaConnectionHandler::update_handleDisconnecting() +{ + DEBUG_ERROR(F("Connection to the network lost.")); + if (_keep_alive) + { + DEBUG_ERROR(F("Attempting reconnection")); + } + return NetworkConnectionState::DISCONNECTED; +} + +NetworkConnectionState LoRaConnectionHandler::update_handleDisconnected() +{ + if (_keep_alive) + { + return NetworkConnectionState::INIT; + } + else + { + return NetworkConnectionState::CLOSED; + } +} + +#endif diff --git a/src/LoRaConnectionHandler.h b/src/LoRaConnectionHandler.h new file mode 100644 index 00000000..b56505a1 --- /dev/null +++ b/src/LoRaConnectionHandler.h @@ -0,0 +1,72 @@ +/* + This file is part of the Arduino_ConnectionHandler library. + + Copyright (c) 2019 Arduino SA + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ + +#ifndef ARDUINO_LORA_CONNECTION_HANDLER_H_ +#define ARDUINO_LORA_CONNECTION_HANDLER_H_ + +/****************************************************************************** + INCLUDE + ******************************************************************************/ + +#include "ConnectionHandlerInterface.h" + +#if defined(ARDUINO_SAMD_MKRWAN1300) || defined(ARDUINO_SAMD_MKRWAN1310) + #include +#endif + +#ifndef BOARD_HAS_LORA + #error "Board doesn't support LORA" +#endif + + +/****************************************************************************** + CLASS DECLARATION + ******************************************************************************/ + +class LoRaConnectionHandler : public ConnectionHandler +{ + public: + + LoRaConnectionHandler(char const * appeui, char const * appkey, _lora_band const band = _lora_band::EU868, char const * channelMask = NULL, _lora_class const device_class = _lora_class::CLASS_A); + + virtual int write(const uint8_t *buf, size_t size) override; + virtual int read() override; + virtual bool available() override; + + inline String getVersion() { return _modem.version(); } + inline String getDeviceEUI() { return _modem.deviceEUI(); } + inline int getChannelMaskSize(_lora_band band) { return _modem.getChannelMaskSize(band); } + inline String getChannelMask() { return _modem.getChannelMask(); } + inline int isChannelEnabled(int pos) { return _modem.isChannelEnabled(pos); } + inline int getDataRate() { return _modem.getDataRate(); } + inline int getADR() { return _modem.getADR(); } + inline String getDevAddr() { return _modem.getDevAddr(); } + inline String getNwkSKey() { return _modem.getNwkSKey(); } + inline String getAppSKey() { return _modem.getAppSKey(); } + inline int getRX2DR() { return _modem.getRX2DR(); } + inline uint32_t getRX2Freq() { return _modem.getRX2Freq(); } + inline int32_t getFCU() { return _modem.getFCU(); } + inline int32_t getFCD() { return _modem.getFCD(); } + + protected: + + virtual NetworkConnectionState update_handleInit () override; + virtual NetworkConnectionState update_handleConnecting () override; + virtual NetworkConnectionState update_handleConnected () override; + virtual NetworkConnectionState update_handleDisconnecting() override; + virtual NetworkConnectionState update_handleDisconnected () override; + + + private: + + LoRaModem _modem; +}; + +#endif /* ARDUINO_LORA_CONNECTION_HANDLER_H_ */ diff --git a/src/Arduino_NBConnectionHandler.cpp b/src/NBConnectionHandler.cpp similarity index 56% rename from src/Arduino_NBConnectionHandler.cpp rename to src/NBConnectionHandler.cpp index b3c719dd..4da9fd62 100644 --- a/src/Arduino_NBConnectionHandler.cpp +++ b/src/NBConnectionHandler.cpp @@ -1,37 +1,47 @@ /* - This file is part of ArduinoIoTCloud. + This file is part of the Arduino_ConnectionHandler library. - Copyright 2019 ARDUINO SA (http://www.arduino.cc/) + Copyright (c) 2019 Arduino SA - This software is released under the GNU General Public License version 3, - which covers the main part of arduino-cli. - The terms of this license can be found at: - https://www.gnu.org/licenses/gpl-3.0.en.html - - You can be released from the requirements of the above licenses by purchasing - a commercial license. Buying such a license is mandatory if you want to modify or - otherwise use the software for commercial activities involving the Arduino - software without disclosing the source code of your own applications. To purchase - a commercial license, send an email to license@arduino.cc. + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /****************************************************************************** - INCLUDE + INCLUDE ******************************************************************************/ -#include "Arduino_NBConnectionHandler.h" +#include "ConnectionHandlerDefinitions.h" #ifdef BOARD_HAS_NB /* Only compile if this is a board with NB */ +#include "NBConnectionHandler.h" /****************************************************************************** - CONSTANTS + CONSTANTS ******************************************************************************/ static int const NB_TIMEOUT = 30000; /****************************************************************************** - CTOR/DTOR + FUNCTION DEFINITION ******************************************************************************/ + +__attribute__((weak)) void mkr_nb_feed_watchdog() +{ + /* This function can be overwritten by a "strong" implementation + * in a higher level application, such as the ArduinoIoTCloud + * firmware stack. + */ +} + +/****************************************************************************** + CTOR/DTOR + ******************************************************************************/ + +NBConnectionHandler::NBConnectionHandler() +: ConnectionHandler(true, NetworkAdapter::NB) {} + NBConnectionHandler::NBConnectionHandler(char const * pin, bool const keep_alive) : NBConnectionHandler(pin, "", keep_alive) { @@ -45,17 +55,17 @@ NBConnectionHandler::NBConnectionHandler(char const * pin, char const * apn, boo } NBConnectionHandler::NBConnectionHandler(char const * pin, char const * apn, char const * login, char const * pass, bool const keep_alive) -: ConnectionHandler{keep_alive} -, _pin(pin) -, _apn(apn) -, _login(login) -, _pass(pass) +: ConnectionHandler{keep_alive, NetworkAdapter::NB} { - + _settings.type = NetworkAdapter::NB; + strncpy(_settings.nb.pin, pin, sizeof(_settings.nb.pin)-1); + strncpy(_settings.nb.apn, apn, sizeof(_settings.nb.apn)-1); + strncpy(_settings.nb.login, login, sizeof(_settings.nb.login)-1); + strncpy(_settings.nb.pass, pass, sizeof(_settings.nb.pass)-1); } /****************************************************************************** - PUBLIC MEMBER FUNCTIONS + PUBLIC MEMBER FUNCTIONS ******************************************************************************/ unsigned long NBConnectionHandler::getTime() @@ -64,20 +74,25 @@ unsigned long NBConnectionHandler::getTime() } /****************************************************************************** - PRIVATE MEMBER FUNCTIONS + PRIVATE MEMBER FUNCTIONS ******************************************************************************/ NetworkConnectionState NBConnectionHandler::update_handleInit() { - if (_nb.begin(_pin, _apn, _login, _pass) == NB_READY) + mkr_nb_feed_watchdog(); + + if (_nb.begin(_settings.nb.pin, + _settings.nb.apn, + _settings.nb.login, + _settings.nb.pass) == NB_READY) { - Debug.print(DBG_INFO, "SIM card ok"); + DEBUG_INFO(F("SIM card ok")); _nb.setTimeout(NB_TIMEOUT); return NetworkConnectionState::CONNECTING; } else { - Debug.print(DBG_ERROR, "SIM not present or wrong PIN"); + DEBUG_ERROR(F("SIM not present or wrong PIN")); return NetworkConnectionState::ERROR; } } @@ -85,15 +100,15 @@ NetworkConnectionState NBConnectionHandler::update_handleInit() NetworkConnectionState NBConnectionHandler::update_handleConnecting() { NB_NetworkStatus_t const network_status = _nb_gprs.attachGPRS(true); - Debug.print(DBG_DEBUG, "GPRS.attachGPRS(): %d", network_status); - if (network_status == NB_NetworkStatus_t::ERROR) + DEBUG_DEBUG(F("GPRS.attachGPRS(): %d"), network_status); + if (network_status == NB_NetworkStatus_t::NB_ERROR) { - Debug.print(DBG_ERROR, "GPRS.attachGPRS() failed"); + DEBUG_ERROR(F("GPRS.attachGPRS() failed")); return NetworkConnectionState::ERROR; } else { - Debug.print(DBG_INFO, "Connected to GPRS Network"); + DEBUG_INFO(F("Connected to GPRS Network")); return NetworkConnectionState::CONNECTED; } } @@ -101,22 +116,22 @@ NetworkConnectionState NBConnectionHandler::update_handleConnecting() NetworkConnectionState NBConnectionHandler::update_handleConnected() { int const nb_is_access_alive = _nb.isAccessAlive(); - Debug.print(DBG_VERBOSE, "GPRS.isAccessAlive(): %d", nb_is_access_alive); + DEBUG_VERBOSE(F("GPRS.isAccessAlive(): %d"), nb_is_access_alive); if (nb_is_access_alive != 1) { - Debug.print(DBG_INFO, "Disconnected from cellular network"); + DEBUG_INFO(F("Disconnected from cellular network")); return NetworkConnectionState::DISCONNECTED; } else { - Debug.print(DBG_VERBOSE, "Connected to Cellular Network"); + DEBUG_VERBOSE(F("Connected to Cellular Network")); return NetworkConnectionState::CONNECTED; } } NetworkConnectionState NBConnectionHandler::update_handleDisconnecting() { - Debug.print(DBG_VERBOSE, "Disconnecting from Cellular Network"); + DEBUG_VERBOSE(F("Disconnecting from Cellular Network")); _nb.shutdown(); return NetworkConnectionState::DISCONNECTED; } diff --git a/src/Arduino_NBConnectionHandler.h b/src/NBConnectionHandler.h similarity index 61% rename from src/Arduino_NBConnectionHandler.h rename to src/NBConnectionHandler.h index 53d2174e..a271199a 100644 --- a/src/Arduino_NBConnectionHandler.h +++ b/src/NBConnectionHandler.h @@ -1,39 +1,38 @@ /* - This file is part of ArduinoIoTCloud. + This file is part of the Arduino_ConnectionHandler library. - Copyright 2019 ARDUINO SA (http://www.arduino.cc/) + Copyright (c) 2019 Arduino SA - This software is released under the GNU General Public License version 3, - which covers the main part of arduino-cli. - The terms of this license can be found at: - https://www.gnu.org/licenses/gpl-3.0.en.html - - You can be released from the requirements of the above licenses by purchasing - a commercial license. Buying such a license is mandatory if you want to modify or - otherwise use the software for commercial activities involving the Arduino - software without disclosing the source code of your own applications. To purchase - a commercial license, send an email to license@arduino.cc. + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef NB_CONNECTION_MANAGER_H_ #define NB_CONNECTION_MANAGER_H_ /****************************************************************************** - INCLUDE + INCLUDE ******************************************************************************/ -#include "Arduino_ConnectionHandler.h" +#include "ConnectionHandlerInterface.h" + +#ifdef ARDUINO_SAMD_MKRNB1500 + #include +#endif -#ifdef BOARD_HAS_NB /* Only compile if this is a board with NB */ +#ifndef BOARD_HAS_NB + #error "Board doesn't support NB" +#endif /****************************************************************************** - CLASS DECLARATION + CLASS DECLARATION ******************************************************************************/ class NBConnectionHandler : public ConnectionHandler { public: - + NBConnectionHandler(); NBConnectionHandler(char const * pin, bool const keep_alive = true); NBConnectionHandler(char const * pin, char const * apn, bool const keep_alive = true); NBConnectionHandler(char const * pin, char const * apn, char const * login, char const * pass, bool const keep_alive = true); @@ -57,17 +56,10 @@ class NBConnectionHandler : public ConnectionHandler void changeConnectionState(NetworkConnectionState _newState); - char const * _pin; - char const * _apn; - char const * _login; - char const * _pass; - NB _nb; GPRS _nb_gprs; NBUDP _nb_udp; NBClient _nb_client; }; -#endif /* #ifdef BOARD_HAS_NB */ - #endif /* #ifndef NB_CONNECTION_MANAGER_H_ */ diff --git a/src/WiFiConnectionHandler.cpp b/src/WiFiConnectionHandler.cpp new file mode 100644 index 00000000..54dd61b5 --- /dev/null +++ b/src/WiFiConnectionHandler.cpp @@ -0,0 +1,192 @@ +/* + This file is part of the Arduino_ConnectionHandler library. + + Copyright (c) 2019 Arduino SA + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ + +/****************************************************************************** + INCLUDE + ******************************************************************************/ + +#include "ConnectionHandlerDefinitions.h" + +#ifdef BOARD_HAS_WIFI /* Only compile if the board has WiFi */ +#include "WiFiConnectionHandler.h" + +/****************************************************************************** + CONSTANTS + ******************************************************************************/ +#if defined(ARDUINO_ARCH_ESP8266) +static int const ESP_WIFI_CONNECTION_TIMEOUT = 3000; +#endif + +/****************************************************************************** + CTOR/DTOR + ******************************************************************************/ + +WiFiConnectionHandler::WiFiConnectionHandler() +: ConnectionHandler(true, NetworkAdapter::WIFI) { +} + +WiFiConnectionHandler::WiFiConnectionHandler(char const * ssid, char const * pass, bool const keep_alive) +: ConnectionHandler{keep_alive, NetworkAdapter::WIFI} +{ + _settings.type = NetworkAdapter::WIFI; + strncpy(_settings.wifi.ssid, ssid, sizeof(_settings.wifi.ssid)-1); + strncpy(_settings.wifi.pwd, pass, sizeof(_settings.wifi.pwd)-1); +} + +/****************************************************************************** + PUBLIC MEMBER FUNCTIONS + ******************************************************************************/ + +unsigned long WiFiConnectionHandler::getTime() +{ +#if !defined(ARDUINO_ARCH_ESP8266) && !defined(ARDUINO_ARCH_ESP32) + return WiFi.getTime(); +#else + return 0; +#endif +} + +/****************************************************************************** + PROTECTED MEMBER FUNCTIONS + ******************************************************************************/ + +NetworkConnectionState WiFiConnectionHandler::update_handleInit() +{ +#if !defined(__AVR__) + DEBUG_INFO(F("WiFi.status(): %d"), WiFi.status()); +#endif + +#if !defined(ARDUINO_ARCH_ESP8266) && !defined(ARDUINO_ARCH_ESP32) + if (WiFi.status() == NETWORK_HARDWARE_ERROR) + { +#if !defined(__AVR__) + DEBUG_ERROR(F("WiFi Hardware failure.\nMake sure you are using a WiFi enabled board/shield.")); + DEBUG_ERROR(F("Then reset and retry.")); +#endif + return NetworkConnectionState::ERROR; + } +#if !defined(__AVR__) + DEBUG_INFO(F("Current WiFi Firmware: %s"), WiFi.firmwareVersion()); +#endif + +#if defined(WIFI_FIRMWARE_VERSION_REQUIRED) + if (String(WiFi.firmwareVersion()) < String(WIFI_FIRMWARE_VERSION_REQUIRED)) + { +#if !defined(__AVR__) + DEBUG_ERROR(F("Latest WiFi Firmware: %s"), WIFI_FIRMWARE_VERSION_REQUIRED); + DEBUG_ERROR(F("Please update to the latest version for best performance.")); +#endif + delay(5000); + } +#endif +#else + WiFi.mode(WIFI_STA); +#endif /* #if !defined(ARDUINO_ARCH_ESP8266) && !defined(ARDUINO_ARCH_ESP32) */ + + if (WiFi.status() != WL_CONNECTED) + { + WiFi.begin(_settings.wifi.ssid, _settings.wifi.pwd); +#if defined(ARDUINO_ARCH_ESP8266) + /* Wait connection otherwise board won't connect */ + unsigned long start = millis(); + while((WiFi.status() != WL_CONNECTED) && (millis() - start) < ESP_WIFI_CONNECTION_TIMEOUT) { + delay(100); + } +#endif + + } + + if (WiFi.status() != NETWORK_CONNECTED) + { +#if !defined(__AVR__) + DEBUG_ERROR(F("Connection to \"%s\" failed"), _settings.wifi.ssid); + DEBUG_INFO(F("Retrying in \"%d\" milliseconds"), _timeoutTable.timeout.init); +#endif + return NetworkConnectionState::INIT; + } + else + { +#if !defined(__AVR__) + DEBUG_INFO(F("Connected to \"%s\""), _settings.wifi.ssid); +#endif +#if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32) + configTime(0, 0, "time.arduino.cc", "pool.ntp.org", "time.nist.gov"); +#endif + return NetworkConnectionState::CONNECTING; + } +} + +NetworkConnectionState WiFiConnectionHandler::update_handleConnecting() +{ + if (WiFi.status() != WL_CONNECTED){ + return NetworkConnectionState::INIT; + } + + if(!_check_internet_availability){ + return NetworkConnectionState::CONNECTED; + } + + #if !defined(ARDUINO_ARCH_ESP8266) && !defined(ARDUINO_ARCH_ESP32) + int ping_result = WiFi.ping("time.arduino.cc"); + DEBUG_INFO(F("WiFi.ping(): %d"), ping_result); + if (ping_result < 0) + { + DEBUG_ERROR(F("Internet check failed")); + DEBUG_INFO(F("Retrying in \"%d\" milliseconds"), _timeoutTable.timeout.connecting); + return NetworkConnectionState::CONNECTING; + } + #endif + DEBUG_INFO(F("Connected to Internet")); + return NetworkConnectionState::CONNECTED; + +} + +NetworkConnectionState WiFiConnectionHandler::update_handleConnected() +{ + if (WiFi.status() != WL_CONNECTED) + { +#if !defined(__AVR__) + DEBUG_VERBOSE(F("WiFi.status(): %d"), WiFi.status()); + DEBUG_ERROR(F("Connection to \"%s\" lost."), _settings.wifi.ssid); +#endif + if (_keep_alive) + { +#if !defined(__AVR__) + DEBUG_INFO(F("Attempting reconnection")); +#endif + } + + return NetworkConnectionState::DISCONNECTED; + } + return NetworkConnectionState::CONNECTED; +} + +NetworkConnectionState WiFiConnectionHandler::update_handleDisconnecting() +{ + WiFi.disconnect(); + return NetworkConnectionState::DISCONNECTED; +} + +NetworkConnectionState WiFiConnectionHandler::update_handleDisconnected() +{ +#if !defined(ARDUINO_ARCH_ESP8266) && !defined(ARDUINO_ARCH_ESP32) + WiFi.end(); +#endif /* #if !defined(ARDUINO_ARCH_ESP8266) && !defined(ARDUINO_ARCH_ESP32) */ + if (_keep_alive) + { + return NetworkConnectionState::INIT; + } + else + { + return NetworkConnectionState::CLOSED; + } +} + +#endif /* #ifdef BOARD_HAS_WIFI */ diff --git a/src/WiFiConnectionHandler.h b/src/WiFiConnectionHandler.h new file mode 100644 index 00000000..1c12c998 --- /dev/null +++ b/src/WiFiConnectionHandler.h @@ -0,0 +1,80 @@ +/* + This file is part of the Arduino_ConnectionHandler library. + + Copyright (c) 2019 Arduino SA + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ + +#ifndef ARDUINO_WIFI_CONNECTION_HANDLER_H_ +#define ARDUINO_WIFI_CONNECTION_HANDLER_H_ + +/****************************************************************************** + INCLUDE + ******************************************************************************/ + +#include "ConnectionHandlerInterface.h" + +#ifdef ARDUINO_SAMD_MKR1000 + #include + #include +#elif defined(ARDUINO_SAMD_MKRWIFI1010) || defined(ARDUINO_SAMD_NANO_33_IOT) || \ + defined(ARDUINO_AVR_UNO_WIFI_REV2) || defined (ARDUINO_NANO_RP2040_CONNECT) + #include + #include +#elif defined(ARDUINO_PORTENTA_H7_M7) || defined(ARDUINO_PORTENTA_H7_M7) || \ + defined(ARDUINO_NICLA_VISION) || defined(ARDUINO_OPTA) || defined(ARDUINO_GIGA) + #include + #include +#elif defined(ARDUINO_PORTENTA_C33) + #include + #include +#elif defined(ARDUINO_ARCH_ESP8266) + #include + #include +#elif defined(ARDUINO_ARCH_ESP32) + #include + #include +#elif defined(ARDUINO_UNOR4_WIFI) + #include +#elif defined(ARDUINO_RASPBERRY_PI_PICO_W) + #include + #include +#endif + +#ifndef BOARD_HAS_WIFI + #error "Board doesn't support WIFI" +#endif + +/****************************************************************************** + CLASS DECLARATION + ******************************************************************************/ + +class WiFiConnectionHandler : public ConnectionHandler +{ + public: + WiFiConnectionHandler(); + WiFiConnectionHandler(char const * ssid, char const * pass, bool const keep_alive = true); + + + virtual unsigned long getTime() override; + virtual Client & getClient() override { return _wifi_client; } + virtual UDP & getUDP() override { return _wifi_udp; } + + + protected: + + virtual NetworkConnectionState update_handleInit () override; + virtual NetworkConnectionState update_handleConnecting () override; + virtual NetworkConnectionState update_handleConnected () override; + virtual NetworkConnectionState update_handleDisconnecting() override; + virtual NetworkConnectionState update_handleDisconnected () override; + + private: + WiFiUDP _wifi_udp; + WiFiClient _wifi_client; +}; + +#endif /* ARDUINO_WIFI_CONNECTION_HANDLER_H_ */ diff --git a/src/connectionHandlerModels/settings.h b/src/connectionHandlerModels/settings.h new file mode 100644 index 00000000..40319d66 --- /dev/null +++ b/src/connectionHandlerModels/settings.h @@ -0,0 +1,130 @@ +/* + This file is part of the Arduino_ConnectionHandler library. + + Copyright (c) 2024 Arduino SA + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ + +#pragma once + +#include "ConnectionHandlerDefinitions.h" +#include +#include + +namespace models { + constexpr size_t WifiSsidLength = 33; // Max length of wifi ssid is 32 + \0 + constexpr size_t WifiPwdLength = 64; // Max length of wifi password is 63 + \0 + + constexpr size_t CellularPinLength = 9; + constexpr size_t CellularApnLength = 101; // Max length of apn is 100 + \0 + constexpr size_t CellularLoginLength = 65; + constexpr size_t CellularPassLength = 65; + + constexpr size_t LoraAppeuiLength = 17; // appeui is 8 octets * 2 (hex format) + \0 + constexpr size_t LoraAppkeyLength = 33; // appeui is 16 octets * 2 (hex format) + \0 + constexpr size_t LoraChannelMaskLength = 13; + + #if defined(BOARD_HAS_WIFI) + struct WiFiSetting { + char ssid[WifiSsidLength]; + char pwd[WifiPwdLength]; + }; + #endif //defined(BOARD_HAS_WIFI) + + #if defined(BOARD_HAS_ETHERNET) + // this struct represents an ip address in its simplest form. + // FIXME this should be available from ArduinoCore-api IPAddress + struct ip_addr { + IPType type; + union { + uint8_t bytes[16]; + uint32_t dword[4]; + }; + }; + + struct EthernetSetting { + ip_addr ip; + ip_addr dns; + ip_addr gateway; + ip_addr netmask; + unsigned long timeout; + unsigned long response_timeout; + }; + #endif // BOARD_HAS_ETHERNET + + #if defined(BOARD_HAS_NB) || defined(BOARD_HAS_GSM) ||defined(BOARD_HAS_CELLULAR) + struct CellularSetting { + char pin[CellularPinLength]; + char apn[CellularApnLength]; + char login[CellularLoginLength]; + char pass[CellularPassLength]; + }; + #endif // defined(BOARD_HAS_NB) || defined(BOARD_HAS_GSM) || defined(BOARD_HAS_CATM1_NBIOT) || defined(BOARD_HAS_CELLULAR) + + #if defined(BOARD_HAS_GSM) + typedef CellularSetting GSMSetting; + #endif //defined(BOARD_HAS_GSM) + + #if defined(BOARD_HAS_NB) + typedef CellularSetting NBSetting; + #endif //defined(BOARD_HAS_NB) + + #if defined(BOARD_HAS_CATM1_NBIOT) + struct CATM1Setting { + char pin[CellularPinLength]; + char apn[CellularApnLength]; + char login[CellularLoginLength]; + char pass[CellularPassLength]; + uint32_t band; + uint8_t rat; + }; + #endif //defined(BOARD_HAS_CATM1_NBIOT) + +#if defined(BOARD_HAS_LORA) + struct LoraSetting { + char appeui[LoraAppeuiLength]; + char appkey[LoraAppkeyLength]; + uint8_t band; + char channelMask[LoraChannelMaskLength]; + uint8_t deviceClass; + }; +#endif + + struct NetworkSetting { + NetworkAdapter type; + union { + #if defined(BOARD_HAS_WIFI) + WiFiSetting wifi; + #endif + + #if defined(BOARD_HAS_ETHERNET) + EthernetSetting eth; + #endif + + #if defined(BOARD_HAS_NB) + NBSetting nb; + #endif + + #if defined(BOARD_HAS_GSM) + GSMSetting gsm; + #endif + + #if defined(BOARD_HAS_CATM1_NBIOT) + CATM1Setting catm1; + #endif + + #if defined(BOARD_HAS_CELLULAR) + CellularSetting cell; + #endif + + #if defined(BOARD_HAS_LORA) + LoraSetting lora; + #endif + }; + }; +} + +#include "settings_default.h" diff --git a/src/connectionHandlerModels/settings_default.h b/src/connectionHandlerModels/settings_default.h new file mode 100644 index 00000000..186cebff --- /dev/null +++ b/src/connectionHandlerModels/settings_default.h @@ -0,0 +1,72 @@ +/* + This file is part of the Arduino_ConnectionHandler library. + + Copyright (c) 2024 Arduino SA + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at http://mozilla.org/MPL/2.0/. +*/ + +#pragma once +#include "settings.h" + +namespace models { + + /* + * if the cpp version is older than cpp14 then a constexpr function cannot include + * other than a simple return statement, thsu we can define it only as inline + */ + #if __cplusplus > 201103L + constexpr NetworkSetting settingsDefault(NetworkAdapter type) { + #else + inline NetworkSetting settingsDefault(NetworkAdapter type) { + #endif + + NetworkSetting res = {type, {}}; + + switch(type) { + #if defined(BOARD_HAS_ETHERNET) + case NetworkAdapter::ETHERNET: + res.eth.timeout = 15000; + res.eth.response_timeout = 4000; + break; + #endif //defined(BOARD_HAS_ETHERNET) + + #if defined(BOARD_HAS_CATM1_NBIOT) + case NetworkAdapter::CATM1: + res.catm1.rat = 7; // CATM1 + res.catm1.band = 0x04 | 0x80000 | 0x40000; // BAND_3 | BAND_20 | BAND_19 + break; + #endif //defined(BOARD_HAS_CATM1_NBIOT) + + #if defined(BOARD_HAS_LORA) + case NetworkAdapter::LORA: + res.lora.band = 5; // _lora_band::EU868 + res.lora.channelMask[0] = '\0'; + res.lora.deviceClass = 'A'; // _lora_class::CLASS_A + break; + #endif //defined(BOARD_HAS_LORA) + + #if defined(BOARD_HAS_WIFI) + case NetworkAdapter::WIFI: // nothing todo, default optional values are fine with 0 + #endif //defined(BOARD_HAS_WIFI) + + #if defined(BOARD_HAS_NB) + case NetworkAdapter::NB: // nothing todo, default optional values are fine with 0 + #endif //defined(BOARD_HAS_NB) + + #if defined(BOARD_HAS_GSM) + case NetworkAdapter::GSM: // nothing todo, default optional values are fine with 0 + #endif //defined(BOARD_HAS_GSM) + + #if defined(BOARD_HAS_CELLULAR) + case NetworkAdapter::CELL: // nothing todo, default optional values are fine with 0 + #endif //defined(BOARD_HAS_CELLULAR) + default: + (void) 0; + } + + return res; + } +}