├── .github ├── dependabot.yml └── workflows │ ├── compile-examples.yml │ ├── report-size-deltas.yml │ ├── spell-check.yml │ └── sync-labels.yml ├── .gitignore ├── CHANGELOG ├── LICENSE.txt ├── README.adoc ├── docs ├── api.md └── readme.md ├── examples ├── GPRSUdpNtpClient │ ├── GPRSUdpNtpClient.ino │ └── arduino_secrets.h ├── NBSSLWebClient │ ├── NBSSLWebClient.ino │ └── arduino_secrets.h ├── NBWebClient │ ├── NBWebClient.ino │ └── arduino_secrets.h ├── ReceiveSMS │ ├── ReceiveSMS.ino │ └── arduino_secrets.h ├── SendSMS │ ├── SendSMS.ino │ └── arduino_secrets.h └── Tools │ ├── ChooseRadioAccessTechnology │ └── ChooseRadioAccessTechnology.ino │ ├── NBScanNetworks │ ├── NBScanNetworks.ino │ └── arduino_secrets.h │ ├── PinManagement │ └── PinManagement.ino │ ├── SerialSARAPassthrough │ └── SerialSARAPassthrough.ino │ ├── TestGPRS │ ├── TestGPRS.ino │ └── arduino_secrets.h │ └── TestModem │ └── TestModem.ino ├── extras └── codespell-ignore-words-list.txt ├── keywords.txt ├── library.properties └── src ├── GPRS.cpp ├── GPRS.h ├── MKRNB.h ├── Modem.cpp ├── Modem.h ├── NB.cpp ├── NB.h ├── NBClient.cpp ├── NBClient.h ├── NBFileUtils.cpp ├── NBFileUtils.h ├── NBModem.cpp ├── NBModem.h ├── NBPIN.cpp ├── NBPIN.h ├── NBSSLClient.cpp ├── NBSSLClient.h ├── NBScanner.cpp ├── NBScanner.h ├── NBUdp.cpp ├── NBUdp.h ├── NB_SMS.cpp ├── NB_SMS.h └── utility ├── NBRootCerts.h ├── NBSocketBuffer.cpp └── NBSocketBuffer.h /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # See: https://docs.github.com/en/code-security/supply-chain-security/configuration-options-for-dependency-updates#about-the-dependabotyml-file 2 | version: 2 3 | 4 | updates: 5 | # Configure check for outdated GitHub Actions actions in workflows. 6 | # Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/assets/dependabot/README.md 7 | # See: https://docs.github.com/en/code-security/supply-chain-security/keeping-your-actions-up-to-date-with-dependabot 8 | - package-ecosystem: github-actions 9 | directory: / # Check the repository's workflows under /.github/workflows/ 10 | schedule: 11 | interval: daily 12 | labels: 13 | - "topic: infrastructure" 14 | -------------------------------------------------------------------------------- /.github/workflows/compile-examples.yml: -------------------------------------------------------------------------------- 1 | name: Compile Examples 2 | 3 | on: 4 | pull_request: 5 | paths: 6 | - ".github/workflows/compile-examples.yml" 7 | - "examples/**" 8 | - "src/**" 9 | push: 10 | paths: 11 | - ".github/workflows/compile-examples.yml" 12 | - "examples/**" 13 | - "src/**" 14 | 15 | jobs: 16 | build: 17 | runs-on: ubuntu-latest 18 | 19 | env: 20 | SKETCHES_REPORTS_PATH: sketches-reports 21 | 22 | strategy: 23 | fail-fast: false 24 | 25 | matrix: 26 | board: 27 | - fqbn: arduino:samd:mkrnb1500 28 | platforms: | 29 | - name: arduino:samd 30 | artifact-name-suffix: arduino-samd-mkrnb1500 31 | 32 | steps: 33 | - name: Checkout 34 | uses: actions/checkout@v4 35 | 36 | - name: Compile examples 37 | uses: arduino/compile-sketches@main 38 | with: 39 | github-token: ${{ secrets.GITHUB_TOKEN }} 40 | fqbn: ${{ matrix.board.fqbn }} 41 | platforms: ${{ matrix.board.platforms }} 42 | libraries: | 43 | # Install the MKRNB library from the local path 44 | - source-path: ./ 45 | sketch-paths: | 46 | examples 47 | enable-deltas-report: true 48 | sketches-report-path: ${{ env.SKETCHES_REPORTS_PATH }} 49 | 50 | - name: Save memory usage change report as artifact 51 | uses: actions/upload-artifact@v4 52 | with: 53 | if-no-files-found: error 54 | path: ${{ env.SKETCHES_REPORTS_PATH }} 55 | name: sketches-report-${{ matrix.board.artifact-name-suffix }} 56 | -------------------------------------------------------------------------------- /.github/workflows/report-size-deltas.yml: -------------------------------------------------------------------------------- 1 | on: 2 | schedule: 3 | - cron: '*/5 * * * *' 4 | 5 | jobs: 6 | report: 7 | runs-on: ubuntu-latest 8 | 9 | steps: 10 | - name: Comment size deltas reports to PRs 11 | uses: arduino/report-size-deltas@main 12 | with: 13 | # Regex matching the names of the workflow artifacts created by the "Compile Examples" workflow 14 | sketches-reports-source: ^sketches-report-.+ 15 | -------------------------------------------------------------------------------- /.github/workflows/spell-check.yml: -------------------------------------------------------------------------------- 1 | name: Spell Check 2 | 3 | on: 4 | pull_request: 5 | push: 6 | schedule: 7 | # run every Tuesday at 3 AM UTC 8 | - cron: "0 3 * * 2" 9 | 10 | jobs: 11 | spellcheck: 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - name: Checkout 16 | uses: actions/checkout@v4 17 | 18 | # See: https://github.com/codespell-project/actions-codespell/blob/master/README.md 19 | - name: Spell check 20 | uses: codespell-project/actions-codespell@master 21 | with: 22 | check_filenames: true 23 | check_hidden: true 24 | # In the event of a false positive, add the word in all lower case to this file: 25 | ignore_words_file: extras/codespell-ignore-words-list.txt 26 | skip: ./.git 27 | -------------------------------------------------------------------------------- /.github/workflows/sync-labels.yml: -------------------------------------------------------------------------------- 1 | # Source: https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/sync-labels.md 2 | name: Sync Labels 3 | 4 | # See: https://docs.github.com/en/actions/reference/events-that-trigger-workflows 5 | on: 6 | push: 7 | paths: 8 | - ".github/workflows/sync-labels.ya?ml" 9 | - ".github/label-configuration-files/*.ya?ml" 10 | pull_request: 11 | paths: 12 | - ".github/workflows/sync-labels.ya?ml" 13 | - ".github/label-configuration-files/*.ya?ml" 14 | schedule: 15 | # Run daily at 8 AM UTC to sync with changes to shared label configurations. 16 | - cron: "0 8 * * *" 17 | workflow_dispatch: 18 | repository_dispatch: 19 | 20 | env: 21 | CONFIGURATIONS_FOLDER: .github/label-configuration-files 22 | CONFIGURATIONS_ARTIFACT: label-configuration-files 23 | 24 | jobs: 25 | check: 26 | runs-on: ubuntu-latest 27 | 28 | steps: 29 | - name: Checkout repository 30 | uses: actions/checkout@v4 31 | 32 | - name: Download JSON schema for labels configuration file 33 | id: download-schema 34 | uses: carlosperate/download-file-action@v2 35 | with: 36 | file-url: https://raw.githubusercontent.com/arduino/tooling-project-assets/main/workflow-templates/assets/sync-labels/arduino-tooling-gh-label-configuration-schema.json 37 | location: ${{ runner.temp }}/label-configuration-schema 38 | 39 | - name: Install JSON schema validator 40 | run: | 41 | sudo npm install \ 42 | --global \ 43 | ajv-cli \ 44 | ajv-formats 45 | 46 | - name: Validate local labels configuration 47 | run: | 48 | # See: https://github.com/ajv-validator/ajv-cli#readme 49 | ajv validate \ 50 | --all-errors \ 51 | -c ajv-formats \ 52 | -s "${{ steps.download-schema.outputs.file-path }}" \ 53 | -d "${{ env.CONFIGURATIONS_FOLDER }}/*.{yml,yaml}" 54 | 55 | download: 56 | needs: check 57 | runs-on: ubuntu-latest 58 | 59 | strategy: 60 | matrix: 61 | filename: 62 | # Filenames of the shared configurations to apply to the repository in addition to the local configuration. 63 | # https://github.com/arduino/tooling-project-assets/blob/main/workflow-templates/assets/sync-labels 64 | - universal.yml 65 | 66 | steps: 67 | - name: Download 68 | uses: carlosperate/download-file-action@v2 69 | with: 70 | file-url: https://raw.githubusercontent.com/arduino/tooling-project-assets/main/workflow-templates/assets/sync-labels/${{ matrix.filename }} 71 | 72 | - name: Pass configuration files to next job via workflow artifact 73 | uses: actions/upload-artifact@v4 74 | with: 75 | path: | 76 | *.yaml 77 | *.yml 78 | if-no-files-found: error 79 | name: ${{ env.CONFIGURATIONS_ARTIFACT }} 80 | 81 | sync: 82 | needs: download 83 | runs-on: ubuntu-latest 84 | 85 | steps: 86 | - name: Set environment variables 87 | run: | 88 | # See: https://docs.github.com/en/actions/reference/workflow-commands-for-github-actions#setting-an-environment-variable 89 | echo "MERGED_CONFIGURATION_PATH=${{ runner.temp }}/labels.yml" >> "$GITHUB_ENV" 90 | 91 | - name: Determine whether to dry run 92 | id: dry-run 93 | if: > 94 | github.event_name == 'pull_request' || 95 | ( 96 | ( 97 | github.event_name == 'push' || 98 | github.event_name == 'workflow_dispatch' 99 | ) && 100 | github.ref != format('refs/heads/{0}', github.event.repository.default_branch) 101 | ) 102 | run: | 103 | # Use of this flag in the github-label-sync command will cause it to only check the validity of the 104 | # configuration. 105 | echo "::set-output name=flag::--dry-run" 106 | 107 | - name: Checkout repository 108 | uses: actions/checkout@v4 109 | 110 | - name: Download configuration files artifact 111 | uses: actions/download-artifact@v4 112 | with: 113 | name: ${{ env.CONFIGURATIONS_ARTIFACT }} 114 | path: ${{ env.CONFIGURATIONS_FOLDER }} 115 | 116 | - name: Remove unneeded artifact 117 | uses: geekyeggo/delete-artifact@v5 118 | with: 119 | name: ${{ env.CONFIGURATIONS_ARTIFACT }} 120 | 121 | - name: Merge label configuration files 122 | run: | 123 | # Merge all configuration files 124 | shopt -s extglob 125 | cat "${{ env.CONFIGURATIONS_FOLDER }}"/*.@(yml|yaml) > "${{ env.MERGED_CONFIGURATION_PATH }}" 126 | 127 | - name: Install github-label-sync 128 | run: sudo npm install --global github-label-sync 129 | 130 | - name: Sync labels 131 | env: 132 | GITHUB_ACCESS_TOKEN: ${{ secrets.GITHUB_TOKEN }} 133 | run: | 134 | # See: https://github.com/Financial-Times/github-label-sync 135 | github-label-sync \ 136 | --labels "${{ env.MERGED_CONFIGURATION_PATH }}" \ 137 | ${{ steps.dry-run.outputs.flag }} \ 138 | ${{ github.repository }} 139 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | -------------------------------------------------------------------------------- /CHANGELOG: -------------------------------------------------------------------------------- 1 | MKRNB 0.0.0 - ????.??.?? 2 | 3 | MKRNB 1.3.1 - 2019.05.17 4 | 5 | * Fixed issues with NB::begin(...) failing for SIMs that required a PIN 6 | 7 | MKRNB 1.3.0 - 2019.05.15 8 | 9 | * Added optional parameters to NB::begin(...) to set the APN to username/password for registration 10 | * Replaced bundled "Amazon Root CA 1" root certificate with "Starfield Services Root Certificate Authority - G2 root CA" 11 | 12 | MKRNB 1.2.0 - 2019.03.26 13 | 14 | * SerialSARAPassthrough example: Enabled the POW_ON pin in setup() 15 | * Fixed result of NB::getTime() 16 | * Added optional parameter to NB::begin(...) to set the APN to use for registration 17 | * Added MODEM.setBaudRate(...) and MODEM.debug(print) and API's 18 | * Added Amazon Root CA 1 19 | 20 | MKRNB 1.1.0 - 2019.03.04 21 | 22 | * Removed NB::lowPowerMode() and NB::noLowPowerMode() API's 23 | * Changed begin() and end() to use the power pin to control the module power 24 | * Added SMS send and receive support 25 | * Added NBModem::getICCID() API 26 | 27 | MKRNB 1.0.1 - 2019.01.23 28 | 29 | * Fixed warning and incorrect enum comparison in NB::shutdown() 30 | * Choose Radio Access Technology sketch: Corrected 5G to 4G 31 | * Fixed NBClient::write for write lengths of > 256 32 | * NBUDP: Changed to use URC for received packets 33 | 34 | MKRNB 1.0.0 - 2018.11.28 35 | 36 | * Initial release 37 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | [This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.] 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | 474 | Copyright (C) 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 489 | USA 490 | 491 | Also add information on how to contact you by electronic and paper mail. 492 | 493 | You should also get your employer (if you work as a programmer) or your 494 | school, if any, to sign a "copyright disclaimer" for the library, if 495 | necessary. Here is a sample; alter the names: 496 | 497 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 498 | library `Frob' (a library for tweaking knobs) written by James Random 499 | Hacker. 500 | 501 | , 1 April 1990 502 | Ty Coon, President of Vice 503 | 504 | That's all there is to it! 505 | -------------------------------------------------------------------------------- /README.adoc: -------------------------------------------------------------------------------- 1 | // Define the repository information in these attributes 2 | :repository-owner: arduino-libraries 3 | :repository-name: MKRNB 4 | 5 | = {repository-name} Library for Arduino = 6 | 7 | image:https://github.com/{repository-owner}/{repository-name}/workflows/Compile%20Examples/badge.svg["Compile Examples Status", link="https://github.com/{repository-owner}/{repository-name}/actions?workflow=Compile+Examples"] 8 | image:https://github.com/{repository-owner}/{repository-name}/workflows/Spell%20Check/badge.svg["Spell Check Status", link="https://github.com/{repository-owner}/{repository-name}/actions?workflow=Spell+Check"] 9 | 10 | This library enables an Arduino MKR NB 1500 board to connect to the internet over a NarrowBand IoT or LTE Cat M1 network. 11 | 12 | For more information about this library please visit us at 13 | https://www.arduino.cc/en/Reference/{repository-name} 14 | 15 | == License == 16 | 17 | Copyright (c) 2018 Arduino SA. All rights reserved. 18 | 19 | This library is free software; you can redistribute it and/or 20 | modify it under the terms of the GNU Lesser General Public 21 | License as published by the Free Software Foundation; either 22 | version 2.1 of the License, or (at your option) any later version. 23 | 24 | This library is distributed in the hope that it will be useful, 25 | but WITHOUT ANY WARRANTY; without even the implied warranty of 26 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 27 | Lesser General Public License for more details. 28 | 29 | You should have received a copy of the GNU Lesser General Public 30 | License along with this library; if not, write to the Free Software 31 | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA 32 | -------------------------------------------------------------------------------- /docs/readme.md: -------------------------------------------------------------------------------- 1 | # MKRNB library 2 | 3 | With the [Arduino MKR NB 1500](https://store.arduino.cc/products/arduino-mkr-nb-1500) and this library you can connect to the internet over a GSM network. The on board module operates in 4G, using LTE Cat M1 or NB1. 4 | 5 | Arduino MKR NB 1500 has a modem that transfers data from a serial port to the GSM network. The modem executes operations via a series of AT commands. The library abstracts low level communications between the modem and SIM card. It relies on the Serial library for communication between the modem and Arduino. 6 | 7 | Typically, each individual command is part of a larger series necessary to execute a particular function. The library can also receive information and return it to you when necessary. 8 | 9 | To use this library 10 | 11 | ``` 12 | #include 13 | ``` 14 | 15 | ## Library structure 16 | 17 | As the library enables multiple types of functionality, there are a number of different classes. 18 | 19 | - The `NB` class takes care of commands to the radio modem. This handles the connectivity aspects of the module and registers your system in the 4G infrastructure. All of your GSM/GPRS programs will need to include an object of this class to handle the necessary low level communication. 20 | - Send/receive SMS messages, managed by the `NB_SMS` class. 21 | - The `GPRSClass` is for connecting to the internet. 22 | - `NBClient` includes implementations for a client, similar to the Ethernet and WiFi libraries. 23 | - A number of utility classes such as `NBScanner` and `NBModem` 24 | 25 | ## Library compatibility 26 | 27 | The library tries to be as compatible as possible with the current Ethernet and WiFi101 library. Porting a program from an Arduino Ethernet or WiFi101 library to an Arduino with the MKR NB 1500 should be fairly easy. While it is not possible to simply run Ethernet or WiFi101 compatible code on the MKR NB 1500 as-is, some minor, library specific, modifications will be necessary, like including the GSM and GPRS specific libraries and getting network configuration settings from your cellular network provider. 28 | 29 | 30 | ## Examples 31 | 32 | You can visit the [MKR NB 1500 documentation portal](https://docs.arduino.cc/hardware/mkr-nb-1500) for tutorials, technical specifications and more. You can also browse through a set of examples at the [Examples from Libraries page](https://docs.arduino.cc/library-examples/#wifi-library). -------------------------------------------------------------------------------- /examples/GPRSUdpNtpClient/GPRSUdpNtpClient.ino: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Udp NTP Client 4 | 5 | Get the time from a Network Time Protocol (NTP) time server 6 | Demonstrates use of UDP write and parsePacket 7 | For more on NTP time servers and the messages needed to communicate with them, 8 | see http://en.wikipedia.org/wiki/Network_Time_Protocol 9 | 10 | created 4 Sep 2010 11 | by Michael Margolis 12 | modified 9 Apr 2012 13 | by Tom Igoe 14 | 15 | modified 6 Dec 2017 ported from WiFi101 to MKRGSM 16 | by Arturo Guadalupi 17 | 18 | This code is in the public domain. 19 | 20 | */ 21 | 22 | #include 23 | 24 | #include "arduino_secrets.h" 25 | // Please enter your sensitive data in the Secret tab or arduino_secrets.h 26 | // PIN Number 27 | const char PINNUMBER[] = SECRET_PINNUMBER; 28 | 29 | unsigned int localPort = 2390; // local port to listen for UDP packets 30 | 31 | IPAddress timeServer(129, 6, 15, 28); // time.nist.gov NTP server 32 | 33 | const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message 34 | 35 | byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets 36 | 37 | // initialize the library instance 38 | GPRS gprs; 39 | NB nbAccess; 40 | 41 | // A UDP instance to let us send and receive packets over UDP 42 | NBUDP Udp; 43 | 44 | void setup() 45 | { 46 | // Open serial communications and wait for port to open: 47 | Serial.begin(9600); 48 | while (!Serial) { 49 | ; // wait for serial port to connect. Needed for native USB port only 50 | } 51 | 52 | Serial.println("Starting Arduino GPRS NTP client."); 53 | // connection state 54 | boolean connected = false; 55 | 56 | // After starting the modem with NB.begin() 57 | // attach the shield to the GPRS network with the APN, login and password 58 | while (!connected) { 59 | if ((nbAccess.begin(PINNUMBER) == NB_READY) && 60 | (gprs.attachGPRS() == GPRS_READY)) { 61 | connected = true; 62 | } else { 63 | Serial.println("Not connected"); 64 | delay(1000); 65 | } 66 | } 67 | 68 | Serial.println("\nStarting connection to server..."); 69 | Udp.begin(localPort); 70 | } 71 | 72 | void loop() 73 | { 74 | sendNTPpacket(timeServer); // send an NTP packet to a time server 75 | // wait to see if a reply is available 76 | delay(1000); 77 | if ( Udp.parsePacket() ) { 78 | Serial.println("packet received"); 79 | // We've received a packet, read the data from it 80 | Udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer 81 | 82 | //the timestamp starts at byte 40 of the received packet and is four bytes, 83 | // or two words, long. First, extract the two words: 84 | 85 | unsigned long highWord = word(packetBuffer[40], packetBuffer[41]); 86 | unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]); 87 | // combine the four bytes (two words) into a long integer 88 | // this is NTP time (seconds since Jan 1 1900): 89 | unsigned long secsSince1900 = highWord << 16 | lowWord; 90 | Serial.print("Seconds since Jan 1 1900 = " ); 91 | Serial.println(secsSince1900); 92 | 93 | // now convert NTP time into everyday time: 94 | Serial.print("Unix time = "); 95 | // Unix time starts on Jan 1 1970. In seconds, that's 2208988800: 96 | const unsigned long seventyYears = 2208988800UL; 97 | // subtract seventy years: 98 | unsigned long epoch = secsSince1900 - seventyYears; 99 | // print Unix time: 100 | Serial.println(epoch); 101 | 102 | 103 | // print the hour, minute and second: 104 | Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT) 105 | Serial.print((epoch % 86400L) / 3600); // print the hour (86400 equals secs per day) 106 | Serial.print(':'); 107 | if ( ((epoch % 3600) / 60) < 10 ) { 108 | // In the first 10 minutes of each hour, we'll want a leading '0' 109 | Serial.print('0'); 110 | } 111 | Serial.print((epoch % 3600) / 60); // print the minute (3600 equals secs per minute) 112 | Serial.print(':'); 113 | if ( (epoch % 60) < 10 ) { 114 | // In the first 10 seconds of each minute, we'll want a leading '0' 115 | Serial.print('0'); 116 | } 117 | Serial.println(epoch % 60); // print the second 118 | } 119 | // wait ten seconds before asking for the time again 120 | delay(10000); 121 | } 122 | 123 | // send an NTP request to the time server at the given address 124 | unsigned long sendNTPpacket(IPAddress& address) 125 | { 126 | //Serial.println("1"); 127 | // set all bytes in the buffer to 0 128 | memset(packetBuffer, 0, NTP_PACKET_SIZE); 129 | // Initialize values needed to form NTP request 130 | // (see URL above for details on the packets) 131 | //Serial.println("2"); 132 | packetBuffer[0] = 0b11100011; // LI, Version, Mode 133 | packetBuffer[1] = 0; // Stratum, or type of clock 134 | packetBuffer[2] = 6; // Polling Interval 135 | packetBuffer[3] = 0xEC; // Peer Clock Precision 136 | // 8 bytes of zero for Root Delay & Root Dispersion 137 | packetBuffer[12] = 49; 138 | packetBuffer[13] = 0x4E; 139 | packetBuffer[14] = 49; 140 | packetBuffer[15] = 52; 141 | 142 | //Serial.println("3"); 143 | 144 | // all NTP fields have been given values, now 145 | // you can send a packet requesting a timestamp: 146 | Udp.beginPacket(address, 123); //NTP requests are to port 123 147 | //Serial.println("4"); 148 | Udp.write(packetBuffer, NTP_PACKET_SIZE); 149 | //Serial.println("5"); 150 | Udp.endPacket(); 151 | //Serial.println("6"); 152 | } 153 | -------------------------------------------------------------------------------- /examples/GPRSUdpNtpClient/arduino_secrets.h: -------------------------------------------------------------------------------- 1 | #define SECRET_PINNUMBER "" 2 | -------------------------------------------------------------------------------- /examples/NBSSLWebClient/NBSSLWebClient.ino: -------------------------------------------------------------------------------- 1 | /* 2 | SSL Web client 3 | 4 | This sketch connects to a website using SSL through a MKR NB 1500 board. Specifically, 5 | this example downloads the URL "https://www.arduino.cc/asciilogo.txt" and 6 | prints it to the Serial monitor. 7 | 8 | Circuit: 9 | * MKR NB 1500 board 10 | * Antenna 11 | * SIM card with a data plan 12 | 13 | created 8 Mar 2012 14 | by Tom Igoe 15 | */ 16 | 17 | // libraries 18 | #include 19 | 20 | #include "arduino_secrets.h" 21 | // Please enter your sensitive data in the Secret tab or arduino_secrets.h 22 | // PIN Number 23 | const char PINNUMBER[] = SECRET_PINNUMBER; 24 | 25 | // initialize the library instance 26 | NBSSLClient client; 27 | GPRS gprs; 28 | NB nbAccess; 29 | 30 | // URL, path and port (for example: arduino.cc) 31 | char server[] = "arduino.cc"; 32 | char path[] = "/asciilogo.txt"; 33 | int port = 443; // port 443 is the default for HTTPS 34 | 35 | void setup() { 36 | // initialize serial communications and wait for port to open: 37 | Serial.begin(9600); 38 | while (!Serial) { 39 | ; // wait for serial port to connect. Needed for native USB port only 40 | } 41 | 42 | Serial.println("Starting Arduino web client."); 43 | // connection state 44 | boolean connected = false; 45 | 46 | // After starting the modem with NB.begin() 47 | // attach to the GPRS network with the APN, login and password 48 | while (!connected) { 49 | if ((nbAccess.begin(PINNUMBER) == NB_READY) && 50 | (gprs.attachGPRS() == GPRS_READY)) { 51 | connected = true; 52 | } else { 53 | Serial.println("Not connected"); 54 | delay(1000); 55 | } 56 | } 57 | 58 | Serial.println("connecting..."); 59 | 60 | // if you get a connection, report back via serial: 61 | if (client.connect(server, port)) { 62 | Serial.println("connected"); 63 | // Make a HTTP request: 64 | client.print("GET "); 65 | client.print(path); 66 | client.println(" HTTP/1.1"); 67 | client.print("Host: "); 68 | client.println(server); 69 | client.println("Connection: close"); 70 | client.println(); 71 | } else { 72 | // if you didn't get a connection to the server: 73 | Serial.println("connection failed"); 74 | } 75 | } 76 | 77 | void loop() { 78 | // if there are incoming bytes available 79 | // from the server, read them and print them: 80 | if (client.available()) { 81 | char c = client.read(); 82 | Serial.print(c); 83 | } 84 | 85 | // if the server's disconnected, stop the client: 86 | if (!client.available() && !client.connected()) { 87 | Serial.println(); 88 | Serial.println("disconnecting."); 89 | client.stop(); 90 | 91 | // do nothing forevermore: 92 | for (;;) 93 | ; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /examples/NBSSLWebClient/arduino_secrets.h: -------------------------------------------------------------------------------- 1 | #define SECRET_PINNUMBER "" 2 | -------------------------------------------------------------------------------- /examples/NBWebClient/NBWebClient.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Web client 3 | 4 | This sketch connects to a website through a MKR NB 1500 board. Specifically, 5 | this example downloads the URL "http://example.org/" and 6 | prints it to the Serial monitor. 7 | 8 | Circuit: 9 | - MKR NB 1500 board 10 | - Antenna 11 | - SIM card with a data plan 12 | 13 | created 8 Mar 2012 14 | by Tom Igoe 15 | */ 16 | 17 | // libraries 18 | #include 19 | 20 | #include "arduino_secrets.h" 21 | // Please enter your sensitive data in the Secret tab or arduino_secrets.h 22 | // PIN Number 23 | const char PINNUMBER[] = SECRET_PINNUMBER; 24 | 25 | // initialize the library instance 26 | NBClient client; 27 | GPRS gprs; 28 | NB nbAccess; 29 | 30 | // URL, path and port (for example: example.org) 31 | char server[] = "example.org"; 32 | char path[] = "/"; 33 | int port = 80; // port 80 is the default for HTTP 34 | 35 | void setup() { 36 | // initialize serial communications and wait for port to open: 37 | Serial.begin(9600); 38 | while (!Serial) { 39 | ; // wait for serial port to connect. Needed for native USB port only 40 | } 41 | 42 | Serial.println("Starting Arduino web client."); 43 | // connection state 44 | boolean connected = false; 45 | 46 | // After starting the modem with NB.begin() 47 | // attach to the GPRS network with the APN, login and password 48 | while (!connected) { 49 | if ((nbAccess.begin(PINNUMBER) == NB_READY) && 50 | (gprs.attachGPRS() == GPRS_READY)) { 51 | connected = true; 52 | } else { 53 | Serial.println("Not connected"); 54 | delay(1000); 55 | } 56 | } 57 | 58 | Serial.println("connecting..."); 59 | 60 | // if you get a connection, report back via serial: 61 | if (client.connect(server, port)) { 62 | Serial.println("connected"); 63 | // Make a HTTP request: 64 | client.print("GET "); 65 | client.print(path); 66 | client.println(" HTTP/1.1"); 67 | client.print("Host: "); 68 | client.println(server); 69 | client.println("Connection: close"); 70 | client.println(); 71 | } else { 72 | // if you didn't get a connection to the server: 73 | Serial.println("connection failed"); 74 | } 75 | } 76 | 77 | void loop() { 78 | // if there are incoming bytes available 79 | // from the server, read them and print them: 80 | if (client.available()) { 81 | Serial.print((char)client.read()); 82 | } 83 | 84 | // if the server's disconnected, stop the client: 85 | if (!client.available() && !client.connected()) { 86 | Serial.println(); 87 | Serial.println("disconnecting."); 88 | client.stop(); 89 | 90 | // do nothing forevermore: 91 | for (;;) 92 | ; 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /examples/NBWebClient/arduino_secrets.h: -------------------------------------------------------------------------------- 1 | #define SECRET_PINNUMBER "" 2 | -------------------------------------------------------------------------------- /examples/ReceiveSMS/ReceiveSMS.ino: -------------------------------------------------------------------------------- 1 | /* 2 | SMS receiver 3 | 4 | This sketch, for the MKR NB 1500 board, waits for a SMS message 5 | and displays it through the Serial port. 6 | 7 | Circuit: 8 | * MKR NB 1500 board 9 | * Antenna 10 | * SIM card that can receive SMS messages 11 | 12 | created 25 Feb 2012 13 | by Javier Zorzano / TD 14 | */ 15 | 16 | // include the NB library 17 | #include 18 | 19 | #include "arduino_secrets.h" 20 | // Please enter your sensitive data in the Secret tab or arduino_secrets.h 21 | // PIN Number 22 | const char PINNUMBER[] = SECRET_PINNUMBER; 23 | 24 | // initialize the library instances 25 | NB nbAccess; 26 | NB_SMS sms; 27 | 28 | // Array to hold the number an SMS is retrieved from 29 | char senderNumber[20]; 30 | 31 | void setup() { 32 | // initialize serial communications and wait for port to open: 33 | Serial.begin(9600); 34 | while (!Serial) { 35 | ; // wait for serial port to connect. Needed for native USB port only 36 | } 37 | 38 | Serial.println("SMS Messages Receiver"); 39 | 40 | // connection state 41 | bool connected = false; 42 | 43 | // Start GSM connection 44 | while (!connected) { 45 | if (nbAccess.begin(PINNUMBER) == NB_READY) { 46 | connected = true; 47 | } else { 48 | Serial.println("Not connected"); 49 | delay(1000); 50 | } 51 | } 52 | 53 | Serial.println("NB initialized"); 54 | Serial.println("Waiting for messages"); 55 | } 56 | 57 | void loop() { 58 | int c; 59 | 60 | // If there are any SMSs available() 61 | if (sms.available()) { 62 | Serial.println("Message received from:"); 63 | 64 | // Get remote number 65 | sms.remoteNumber(senderNumber, 20); 66 | Serial.println(senderNumber); 67 | 68 | // An example of message disposal 69 | // Any messages starting with # should be discarded 70 | if (sms.peek() == '#') { 71 | Serial.println("Discarded SMS"); 72 | sms.flush(); 73 | } 74 | 75 | // Read message bytes and print them 76 | while ((c = sms.read()) != -1) { 77 | Serial.print((char)c); 78 | } 79 | 80 | Serial.println("\nEND OF MESSAGE"); 81 | 82 | // Delete message from modem memory 83 | sms.flush(); 84 | Serial.println("MESSAGE DELETED"); 85 | } 86 | 87 | delay(1000); 88 | 89 | } 90 | -------------------------------------------------------------------------------- /examples/ReceiveSMS/arduino_secrets.h: -------------------------------------------------------------------------------- 1 | #define SECRET_PINNUMBER "" 2 | -------------------------------------------------------------------------------- /examples/SendSMS/SendSMS.ino: -------------------------------------------------------------------------------- 1 | /* 2 | SMS sender 3 | 4 | This sketch, for the MKR NB 1500 board, sends an SMS message 5 | you enter in the serial monitor. Connect your Arduino with the 6 | SIM card, open the serial monitor, and wait for 7 | the "READY" message to appear in the monitor. Next, type a 8 | message to send and press "return". Make sure the serial 9 | monitor is set to send a newline when you press return. 10 | 11 | Circuit: 12 | * MKR NB 1500 board 13 | * Antenna 14 | * SIM card that can send SMS 15 | 16 | created 25 Feb 2012 17 | by Tom Igoe 18 | */ 19 | 20 | // Include the NB library 21 | #include 22 | 23 | #include "arduino_secrets.h" 24 | // Please enter your sensitive data in the Secret tab or arduino_secrets.h 25 | // PIN Number 26 | const char PINNUMBER[] = SECRET_PINNUMBER; 27 | 28 | // initialize the library instance 29 | NB nbAccess; 30 | NB_SMS sms; 31 | 32 | void setup() { 33 | // initialize serial communications and wait for port to open: 34 | Serial.begin(9600); 35 | while (!Serial) { 36 | ; // wait for serial port to connect. Needed for native USB port only 37 | } 38 | 39 | Serial.println("SMS Messages Sender"); 40 | 41 | // connection state 42 | bool connected = false; 43 | 44 | // Start NB module 45 | // If your SIM has PIN, pass it as a parameter of begin() in quotes 46 | while (!connected) { 47 | if (nbAccess.begin(PINNUMBER) == NB_READY) { 48 | connected = true; 49 | } else { 50 | Serial.println("Not connected"); 51 | delay(1000); 52 | } 53 | } 54 | 55 | Serial.println("NB initialized"); 56 | } 57 | 58 | void loop() { 59 | 60 | Serial.print("Enter a mobile number: "); 61 | char remoteNum[20]; // telephone number to send SMS 62 | readSerial(remoteNum); 63 | Serial.println(remoteNum); 64 | 65 | // SMS text 66 | Serial.print("Now, enter SMS content: "); 67 | char txtMsg[200]; 68 | readSerial(txtMsg); 69 | Serial.println("SENDING"); 70 | Serial.println(); 71 | Serial.println("Message:"); 72 | Serial.println(txtMsg); 73 | 74 | // send the message 75 | sms.beginSMS(remoteNum); 76 | sms.print(txtMsg); 77 | sms.endSMS(); 78 | Serial.println("\nCOMPLETE!\n"); 79 | } 80 | 81 | /* 82 | Read input serial 83 | */ 84 | int readSerial(char result[]) { 85 | int i = 0; 86 | while (1) { 87 | while (Serial.available() > 0) { 88 | char inChar = Serial.read(); 89 | if (inChar == '\n') { 90 | result[i] = '\0'; 91 | Serial.flush(); 92 | return 0; 93 | } 94 | if (inChar != '\r') { 95 | result[i] = inChar; 96 | i++; 97 | } 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /examples/SendSMS/arduino_secrets.h: -------------------------------------------------------------------------------- 1 | #define SECRET_PINNUMBER "" 2 | -------------------------------------------------------------------------------- /examples/Tools/ChooseRadioAccessTechnology/ChooseRadioAccessTechnology.ino: -------------------------------------------------------------------------------- 1 | /* 2 | Radio Access Technology selection for Arduino MKR NB 1500 3 | 4 | This sketch allows you to select your preferred 4G 5 | Narrowband Radio Access Technology (RAT). 6 | 7 | You can choose among CAT-M1, NB-IoT or a combination of both. 8 | 9 | Selecting JUST ONE technology will speed up the modem's network 10 | registration A LOT! 11 | 12 | The chosen configuration will be saved to modem's internal memory 13 | and will be preserved through MKR NB 1500 sketch uploads. 14 | 15 | In order to change the RAT, you will need to run this sketch again. 16 | 17 | Circuit: 18 | - MKR NB 1500 board 19 | - Antenna 20 | - SIM card 21 | 22 | Created 26 November 2018 23 | by Giampaolo Mancini 24 | 25 | */ 26 | 27 | #include 28 | 29 | void setup() { 30 | Serial.begin(115200); 31 | while (!Serial); 32 | 33 | MODEM.begin(); 34 | while (!MODEM.noop()); 35 | 36 | for (int i = 0; i < 80; i++) Serial.print("*"); 37 | Serial.println(); 38 | Serial.println("This sketch allows you to select your preferred"); 39 | Serial.println("4G Narrowband Radio Access Technology (RAT)."); 40 | Serial.println(); 41 | Serial.println("You can choose among CAT-M1, NB-IoT or a combination of both."); 42 | Serial.println(); 43 | Serial.println("Selecting JUST ONE technology will speed up the modem's network registration A LOT!"); 44 | Serial.println(); 45 | Serial.println("The chosen configuration will be saved to modem's internal memory"); 46 | Serial.println("and will be preserved through MKR NB 1500 sketch uploads."); 47 | Serial.println(); 48 | Serial.println("In order to change the RAT, you will need to run this sketch again."); 49 | for (int i = 0; i < 80; i++) Serial.print("*"); 50 | 51 | Serial.println(); 52 | Serial.println(); 53 | Serial.println("Please choose your Radio Access Technology:"); 54 | Serial.println(); 55 | Serial.println(" 0 - CAT M1 only"); 56 | Serial.println(" 1 - NB IoT only"); 57 | Serial.println(" 2 - CAT M1 preferred, NB IoT as failover (default)"); 58 | Serial.println(" 3 - NB IoT preferred, CAT M1 as failover"); 59 | Serial.println(); 60 | } 61 | 62 | void loop() { 63 | String uratChoice; 64 | 65 | Serial.print("> "); 66 | 67 | Serial.setTimeout(-1); 68 | while (Serial.available() == 0); 69 | String uratInput = Serial.readStringUntil('\n'); 70 | uratInput.trim(); 71 | int urat = uratInput.toInt(); 72 | Serial.println(urat); 73 | 74 | switch (urat) { 75 | case 0: 76 | uratChoice = "7"; 77 | break; 78 | case 1: 79 | uratChoice = "8"; 80 | break; 81 | case 2: 82 | uratChoice = "7,8"; 83 | break; 84 | case 3: 85 | uratChoice = "8,7"; 86 | break; 87 | default: 88 | Serial.println("Invalid input. Please, retry."); 89 | return; 90 | } 91 | 92 | setRAT(uratChoice); 93 | apply(); 94 | 95 | Serial.println(); 96 | Serial.println("Radio Access Technology selected."); 97 | Serial.println("Now you can upload your 4G application sketch."); 98 | while (true); 99 | } 100 | 101 | bool setRAT(String choice) 102 | { 103 | String response; 104 | 105 | Serial.print("Disconnecting from network: "); 106 | MODEM.sendf("AT+COPS=2"); 107 | MODEM.waitForResponse(2000); 108 | Serial.println("done."); 109 | 110 | Serial.print("Setting Radio Access Technology: "); 111 | MODEM.sendf("AT+URAT=%s", choice.c_str()); 112 | MODEM.waitForResponse(2000, &response); 113 | Serial.println("done."); 114 | 115 | return true; 116 | } 117 | 118 | bool apply() 119 | { 120 | Serial.print("Applying changes and saving configuration: "); 121 | MODEM.send("AT+CFUN=15"); 122 | MODEM.waitForResponse(5000); 123 | delay(5000); 124 | 125 | do { 126 | delay(1000); 127 | MODEM.noop(); 128 | } while (MODEM.waitForResponse(1000) != 1); 129 | 130 | Serial.println("done."); 131 | 132 | return true; 133 | } 134 | -------------------------------------------------------------------------------- /examples/Tools/NBScanNetworks/NBScanNetworks.ino: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | NB Scan Networks 4 | 5 | This example prints out the IMEI number of the modem, 6 | then checks to see if it's connected to a carrier. 7 | Then it scans for nearby networks and prints out their signal strengths. 8 | 9 | Circuit: 10 | * MKR NB 1500 board 11 | * Antenna 12 | * SIM card 13 | 14 | Created 8 Mar 2012 15 | by Tom Igoe, implemented by Javier Carazo 16 | Modified 4 Feb 2013 17 | by Scott Fitzgerald 18 | */ 19 | 20 | // libraries 21 | #include 22 | 23 | #include "arduino_secrets.h" 24 | // Please enter your sensitive data in the Secret tab or arduino_secrets.h 25 | // PIN Number 26 | const char PINNUMBER[] = SECRET_PINNUMBER; 27 | 28 | // initialize the library instance 29 | NB nbAccess; // include a 'true' parameter to enable debugging 30 | NBScanner scannerNetworks; 31 | NBModem modemTest; 32 | 33 | // Save data variables 34 | String IMEI = ""; 35 | 36 | // serial monitor result messages 37 | String errortext = "ERROR"; 38 | 39 | void setup() { 40 | // initialize serial communications and wait for port to open: 41 | Serial.begin(9600); 42 | while (!Serial) { 43 | ; // wait for serial port to connect. Needed for Leonardo only 44 | } 45 | 46 | Serial.println("NB IoT/LTE Cat M1 networks scanner"); 47 | scannerNetworks.begin(); 48 | 49 | // connection state 50 | boolean connected = false; 51 | 52 | // Start module 53 | // If your SIM has PIN, pass it as a parameter of begin() in quotes 54 | while (!connected) { 55 | if (nbAccess.begin(PINNUMBER) == NB_READY) { 56 | connected = true; 57 | } else { 58 | Serial.println("Not connected"); 59 | delay(1000); 60 | } 61 | } 62 | 63 | // get modem parameters 64 | // IMEI, modem unique identifier 65 | Serial.print("Modem IMEI: "); 66 | IMEI = modemTest.getIMEI(); 67 | IMEI.replace("\n", ""); 68 | if (IMEI != NULL) { 69 | Serial.println(IMEI); 70 | } 71 | } 72 | 73 | void loop() { 74 | // currently connected carrier 75 | Serial.print("Current carrier: "); 76 | Serial.println(scannerNetworks.getCurrentCarrier()); 77 | 78 | // returns strength and BER 79 | // signal strength in 0-31 scale. 31 means power > 51dBm 80 | // BER is the Bit Error Rate. 0-7 scale. 99=not detectable 81 | Serial.print("Signal Strength: "); 82 | Serial.print(scannerNetworks.getSignalStrength()); 83 | Serial.println(" [0-31]"); 84 | 85 | // scan for existing networks, displays a list of networks 86 | Serial.println("Scanning available networks. May take some seconds."); 87 | Serial.println(scannerNetworks.readNetworks()); 88 | // wait ten seconds before scanning again 89 | delay(10000); 90 | } 91 | -------------------------------------------------------------------------------- /examples/Tools/NBScanNetworks/arduino_secrets.h: -------------------------------------------------------------------------------- 1 | #define SECRET_PINNUMBER "" 2 | -------------------------------------------------------------------------------- /examples/Tools/PinManagement/PinManagement.ino: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | This example enables you to change or remove the PIN number of 4 | a SIM card inserted into a MKR NB 1500 board. 5 | 6 | Circuit: 7 | * MKR NB 1500 board 8 | * Antenna 9 | * SIM card 10 | 11 | Created 12 Jun 2012 12 | by David del Peral 13 | */ 14 | 15 | // libraries 16 | #include 17 | 18 | // pin manager object 19 | NBPIN PINManager; 20 | 21 | // save input in serial by user 22 | String user_input = ""; 23 | 24 | // authenticated with PIN code 25 | boolean auth = false; 26 | 27 | // serial monitor result messages 28 | String oktext = "OK"; 29 | String errortext = "ERROR"; 30 | 31 | void setup() { 32 | // initialize serial communications and wait for port to open: 33 | Serial.begin(9600); 34 | while (!Serial) { 35 | ; // wait for serial port to connect. Needed for Leonardo only 36 | } 37 | 38 | Serial.println("Change PIN example\n"); 39 | PINManager.begin(); 40 | 41 | // check if the SIM have pin lock 42 | while (!auth) { 43 | int pin_query = PINManager.isPIN(); 44 | if (pin_query == 1) { 45 | // if SIM is locked, enter PIN code 46 | Serial.print("Enter PIN code: "); 47 | user_input = readSerial(); 48 | // check PIN code 49 | if (PINManager.checkPIN(user_input) == 0) { 50 | auth = true; 51 | PINManager.setPINUsed(true); 52 | Serial.println(oktext); 53 | } else { 54 | // if PIN code was incorrected 55 | Serial.println("Incorrect PIN. Remember that you have 3 opportunities."); 56 | } 57 | } else if (pin_query == -1) { 58 | // PIN code is locked, user must enter PUK code 59 | Serial.println("PIN locked. Enter PUK code: "); 60 | String puk = readSerial(); 61 | Serial.print("Now, enter a new PIN code: "); 62 | user_input = readSerial(); 63 | // check PUK code 64 | if (PINManager.checkPUK(puk, user_input) == 0) { 65 | auth = true; 66 | PINManager.setPINUsed(true); 67 | Serial.println(oktext); 68 | } else { 69 | // if PUK o the new PIN are incorrect 70 | Serial.println("Incorrect PUK or invalid new PIN. Try again!."); 71 | } 72 | } else if (pin_query == -2) { 73 | // the worst case, PIN and PUK are locked 74 | Serial.println("PIN and PUK locked. Use PIN2/PUK2 in a mobile phone."); 75 | while (true); 76 | } else { 77 | // SIM does not requires authentication 78 | Serial.println("No pin necessary."); 79 | auth = true; 80 | } 81 | } 82 | 83 | // start module 84 | Serial.print("Checking register in NB IoT / LTE Cat M1 network..."); 85 | if (PINManager.checkReg() == 0) { 86 | Serial.println(oktext); 87 | } 88 | // if you are connect by roaming 89 | else if (PINManager.checkReg() == 1) { 90 | Serial.println("ROAMING " + oktext); 91 | } else { 92 | // error connection 93 | Serial.println(errortext); 94 | while (true); 95 | } 96 | } 97 | 98 | void loop() { 99 | // Function loop implements pin management user menu 100 | // You can only change PIN code if your SIM uses pin lock 101 | 102 | Serial.println("Choose an option:\n1 - On/Off PIN."); 103 | if (PINManager.getPINUsed()) { 104 | Serial.println("2 - Change PIN."); 105 | } 106 | // save user input to user_op variable 107 | String user_op = readSerial(); 108 | if (user_op == "1") { 109 | Serial.println("Enter your PIN code:"); 110 | user_input = readSerial(); 111 | // activate/deactivate PIN lock 112 | PINManager.switchPIN(user_input); 113 | } else if (user_op == "2" && PINManager.getPINUsed()) { 114 | Serial.println("Enter your actual PIN code:"); 115 | String oldPIN = readSerial(); 116 | Serial.println("Now, enter your new PIN code:"); 117 | String newPIN = readSerial(); 118 | // change PIN 119 | PINManager.changePIN(oldPIN, newPIN); 120 | } else { 121 | Serial.println("Incorrect option. Try again!."); 122 | } 123 | delay(1000); 124 | } 125 | 126 | /* 127 | Read serial input 128 | */ 129 | String readSerial() { 130 | String text = ""; 131 | while (1) { 132 | while (Serial.available() > 0) { 133 | char inChar = Serial.read(); 134 | if (inChar == '\n') { 135 | return text; 136 | } 137 | if (inChar != '\r') { 138 | text += inChar; 139 | } 140 | } 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /examples/Tools/SerialSARAPassthrough/SerialSARAPassthrough.ino: -------------------------------------------------------------------------------- 1 | /* 2 | SerialSARAPassthrough sketch 3 | 4 | This sketch allows you to send AT commands from the USB CDC serial port 5 | of the MKR NB 1500 board to the onboard ublox SARA-R410 cellular module. 6 | 7 | For a list of supported AT commands see: 8 | https://www.u-blox.com/sites/default/files/u-blox-CEL_ATCommands_%28UBX-13002752%29.pdf 9 | 10 | Circuit: 11 | - MKR NB 1500 board 12 | - Antenna 13 | - SIM card 14 | 15 | Make sure the Serial Monitor's line ending is set to "Both NL and CR" or "Carriage Return" 16 | 17 | created 11 December 2017 18 | Sandeep Mistry 19 | */ 20 | 21 | // baud rate used for both Serial ports 22 | unsigned long baud = 115200; 23 | 24 | void setup() { 25 | // NEVER EVER use RESET_N 26 | pinMode(SARA_RESETN, OUTPUT); 27 | digitalWrite(SARA_RESETN, LOW); 28 | 29 | // Send Poweron pulse 30 | pinMode(SARA_PWR_ON, OUTPUT); 31 | digitalWrite(SARA_PWR_ON, HIGH); 32 | delay(150); 33 | digitalWrite(SARA_PWR_ON, LOW); 34 | 35 | Serial.begin(baud); 36 | SerialSARA.begin(baud); 37 | } 38 | 39 | void loop() { 40 | if (Serial.available()) { 41 | SerialSARA.write(Serial.read()); 42 | } 43 | 44 | if (SerialSARA.available()) { 45 | Serial.write(SerialSARA.read()); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /examples/Tools/TestGPRS/TestGPRS.ino: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | This sketch tests the MKR NB 1500 board's ability to connect to a 4 | GPRS network. It asks for APN information through the 5 | serial monitor and tries to connect to example.org. 6 | 7 | Circuit: 8 | * MKR NB 1500 board 9 | * Antenna 10 | * SIM card with data plan 11 | 12 | Created 18 Jun 2012 13 | by David del Peral 14 | */ 15 | 16 | // libraries 17 | #include 18 | 19 | #include "arduino_secrets.h" 20 | // Please enter your sensitive data in the Secret tab or arduino_secrets.h 21 | // PIN Number 22 | const char PINNUMBER[] = SECRET_PINNUMBER; 23 | 24 | // initialize the library instance 25 | NB nbAccess; // NB access: include a 'true' parameter for debug enabled 26 | GPRS gprsAccess; // GPRS access 27 | NBClient client; // Client service for TCP connection 28 | 29 | // messages for serial monitor response 30 | String oktext = "OK"; 31 | String errortext = "ERROR"; 32 | 33 | // URL and path (for example: example.org) 34 | char url[] = "example.org"; 35 | char urlproxy[] = "http://example.org"; 36 | char path[] = "/"; 37 | 38 | // variable to save obtained response 39 | String response = ""; 40 | 41 | // use a proxy 42 | boolean use_proxy = false; 43 | 44 | void setup() { 45 | // initialize serial communications and wait for port to open: 46 | Serial.begin(9600); 47 | while (!Serial) { 48 | ; // wait for serial port to connect. Needed for Leonardo only 49 | } 50 | } 51 | 52 | void loop() { 53 | use_proxy = false; 54 | 55 | // start module 56 | // if your SIM has PIN, pass it as a parameter of begin() in quotes 57 | Serial.print("Connecting NB IoT / LTE Cat M1 network..."); 58 | if (nbAccess.begin(PINNUMBER) != NB_READY) { 59 | Serial.println(errortext); 60 | while (true); 61 | } 62 | Serial.println(oktext); 63 | 64 | // attach GPRS 65 | Serial.println("Attaching to GPRS..."); 66 | if (gprsAccess.attachGPRS() != GPRS_READY) { 67 | Serial.println(errortext); 68 | } else { 69 | 70 | Serial.println(oktext); 71 | 72 | // read proxy introduced by user 73 | char proxy[100]; 74 | Serial.print("If your carrier uses a proxy, enter it, if not press enter: "); 75 | readSerial(proxy); 76 | Serial.println(proxy); 77 | 78 | // if user introduced a proxy, asks them for proxy port 79 | int pport; 80 | if (proxy[0] != '\0') { 81 | // read proxy port introduced by user 82 | char proxyport[10]; 83 | Serial.print("Enter the proxy port: "); 84 | readSerial(proxyport); 85 | // cast proxy port introduced to integer 86 | pport = (int) proxyport; 87 | use_proxy = true; 88 | Serial.println(proxyport); 89 | } 90 | 91 | // connection with example.org and realize HTTP request 92 | Serial.print("Connecting and sending GET request to example.org..."); 93 | int res_connect; 94 | 95 | // if use a proxy, connect with it 96 | if (use_proxy) { 97 | res_connect = client.connect(proxy, pport); 98 | } else { 99 | res_connect = client.connect(url, 80); 100 | } 101 | 102 | if (res_connect) { 103 | // make a HTTP 1.0 GET request (client sends the request) 104 | client.print("GET "); 105 | 106 | // if using a proxy, the path is example.org URL 107 | if (use_proxy) { 108 | client.print(urlproxy); 109 | } else { 110 | client.print(path); 111 | } 112 | 113 | client.println(" HTTP/1.1"); 114 | client.print("Host: "); 115 | client.println(url); 116 | client.println("Connection: close"); 117 | client.println(); 118 | Serial.println(oktext); 119 | } else { 120 | // if you didn't get a connection to the server 121 | Serial.println(errortext); 122 | } 123 | Serial.print("Receiving response..."); 124 | 125 | boolean test = true; 126 | while (test) { 127 | // if there are incoming bytes available 128 | // from the server, read and check them 129 | if (client.available()) { 130 | char c = client.read(); 131 | response += c; 132 | 133 | // cast response obtained from string to char array 134 | char responsechar[response.length() + 1]; 135 | response.toCharArray(responsechar, response.length() + 1); 136 | 137 | // if response includes a "200 OK" substring 138 | if (strstr(responsechar, "200 OK") != NULL) { 139 | Serial.println(oktext); 140 | Serial.println("TEST COMPLETE!"); 141 | test = false; 142 | } 143 | } 144 | 145 | // if the server's disconnected, stop the client: 146 | if (!client.connected()) { 147 | Serial.println(); 148 | Serial.println("disconnecting."); 149 | client.stop(); 150 | test = false; 151 | } 152 | } 153 | } 154 | } 155 | 156 | /* 157 | Read input serial 158 | */ 159 | int readSerial(char result[]) { 160 | int i = 0; 161 | while (1) { 162 | while (Serial.available() > 0) { 163 | char inChar = Serial.read(); 164 | if (inChar == '\n') { 165 | result[i] = '\0'; 166 | return 0; 167 | } 168 | if (inChar != '\r') { 169 | result[i] = inChar; 170 | i++; 171 | } 172 | } 173 | } 174 | } 175 | -------------------------------------------------------------------------------- /examples/Tools/TestGPRS/arduino_secrets.h: -------------------------------------------------------------------------------- 1 | #define SECRET_PINNUMBER "" 2 | -------------------------------------------------------------------------------- /examples/Tools/TestModem/TestModem.ino: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | This example tests to see if the modem of the 4 | MKR NB 1500 board is working correctly. You do not need 5 | a SIM card for this example. 6 | 7 | Circuit: 8 | * MKR NB 1500 board 9 | * Antenna 10 | 11 | Created 12 Jun 2012 12 | by David del Peral 13 | modified 21 Nov 2012 14 | by Tom Igoe 15 | */ 16 | 17 | // libraries 18 | #include 19 | 20 | // modem verification object 21 | NBModem modem; 22 | 23 | // IMEI variable 24 | String IMEI = ""; 25 | 26 | void setup() { 27 | // initialize serial communications and wait for port to open: 28 | Serial.begin(9600); 29 | while (!Serial) { 30 | ; // wait for serial port to connect. Needed for Leonardo only 31 | } 32 | 33 | // start modem test (reset and check response) 34 | Serial.print("Starting modem test..."); 35 | if (modem.begin()) { 36 | Serial.println("modem.begin() succeeded"); 37 | } else { 38 | Serial.println("ERROR, no modem answer."); 39 | } 40 | } 41 | 42 | void loop() { 43 | // get modem IMEI 44 | Serial.print("Checking IMEI..."); 45 | IMEI = modem.getIMEI(); 46 | 47 | // check IMEI response 48 | if (IMEI != NULL) { 49 | // show IMEI in serial monitor 50 | Serial.println("Modem's IMEI: " + IMEI); 51 | // reset modem to check booting: 52 | Serial.print("Resetting modem..."); 53 | modem.begin(); 54 | // get and check IMEI one more time 55 | if (modem.getIMEI() != NULL) { 56 | Serial.println("Modem is functioning properly"); 57 | } else { 58 | Serial.println("Error: getIMEI() failed after modem.begin()"); 59 | } 60 | } else { 61 | Serial.println("Error: Could not get IMEI"); 62 | } 63 | // do nothing: 64 | while (true); 65 | } 66 | -------------------------------------------------------------------------------- /extras/codespell-ignore-words-list.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/arduino-libraries/MKRNB/ac81663ba57647eb3da44e17f8b07da62b0c2444/extras/codespell-ignore-words-list.txt -------------------------------------------------------------------------------- /keywords.txt: -------------------------------------------------------------------------------- 1 | ####################################### 2 | # Syntax Coloring Map For MKNB 3 | ####################################### 4 | # Class 5 | ####################################### 6 | 7 | MKRNB KEYWORD1 8 | NB KEYWORD1 9 | NB_SMS KEYWORD1 10 | GPRS KEYWORD1 11 | NBClient KEYWORD1 12 | NBModem KEYWORD1 13 | NBScanner KEYWORD1 14 | NBPIN KEYWORD1 15 | NBSSLClient KEYWORD1 16 | NBUdp KEYWORD1 17 | 18 | ####################################### 19 | # Methods and Functions 20 | ####################################### 21 | 22 | begin KEYWORD2 23 | shutdown KEYWORD2 24 | ready KEYWORD2 25 | setTimeout KEYWORD2 26 | beginSMS KEYWORD2 27 | endSMS KEYWORD2 28 | remoteNumber KEYWORD2 29 | attachGPRS KEYWORD2 30 | beginWrite KEYWORD2 31 | endWrite KEYWORD2 32 | getIMEI KEYWORD2 33 | getICCID KEYWORD2 34 | getCurrentCarrier KEYWORD2 35 | getSignalStrength KEYWORD2 36 | readNetworks KEYWORD2 37 | isPIN KEYWORD2 38 | checkPIN KEYWORD2 39 | checkPUK KEYWORD2 40 | changePIN KEYWORD2 41 | switchPIN KEYWORD2 42 | checkReg KEYWORD2 43 | getPINUsed KEYWORD2 44 | setPINUsed KEYWORD2 45 | hostByName KEYWORD2 46 | getTime KEYWORD2 47 | setTime KEYWORD2 48 | getLocalTime KEYWORD2 49 | 50 | ####################################### 51 | # Constants 52 | ####################################### 53 | 54 | ERROR LITERAL1 55 | IDLE LITERAL1 56 | CONNECTING LITERAL1 57 | NB_READY LITERAL1 58 | GPRS_READY LITERAL1 59 | TRANSPARENT_CONNECTED LITERAL1 60 | -------------------------------------------------------------------------------- /library.properties: -------------------------------------------------------------------------------- 1 | name=MKRNB 2 | version=1.6.0 3 | author=Arduino 4 | maintainer=Arduino 5 | sentence=Enables NB/GRPS network connection using the Arduino MKR NB 1500 board. 6 | paragraph=This library also allows you to connect to internet through NarrowBand IoT or LTE Cat M1 networks.
7 | category=Communication 8 | url=http://www.arduino.cc/en/Reference/MKRNB 9 | architectures=samd 10 | includes=MKRNB.h 11 | -------------------------------------------------------------------------------- /src/GPRS.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB library. 3 | Copyright (c) 2018 Arduino SA. All rights reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #include "GPRS.h" 21 | 22 | enum { 23 | GPRS_STATE_IDLE, 24 | 25 | GPRS_STATE_ATTACH, 26 | GPRS_STATE_WAIT_ATTACH_RESPONSE, 27 | GPRS_STATE_CHECK_ATTACHED, 28 | GPRS_STATE_WAIT_CHECK_ATTACHED_RESPONSE, 29 | 30 | GPRS_STATE_DEATTACH, 31 | GPRS_STATE_WAIT_DEATTACH_RESPONSE 32 | }; 33 | 34 | GPRS::GPRS() : 35 | _status(IDLE), 36 | _timeout(0) 37 | { 38 | } 39 | 40 | GPRS::~GPRS() 41 | { 42 | } 43 | 44 | NB_NetworkStatus_t GPRS::attachGPRS(bool synchronous) 45 | { 46 | _state = GPRS_STATE_ATTACH; 47 | _status = CONNECTING; 48 | 49 | if (synchronous) { 50 | unsigned long start = millis(); 51 | 52 | while (ready() == 0) { 53 | if (_timeout && !((millis() - start) < _timeout)) { 54 | _state = NB_ERROR; 55 | break; 56 | } 57 | delay(500); 58 | } 59 | } else { 60 | ready(); 61 | } 62 | 63 | return _status; 64 | } 65 | 66 | NB_NetworkStatus_t GPRS::detachGPRS(bool synchronous) 67 | { 68 | _state = GPRS_STATE_DEATTACH; 69 | 70 | if (synchronous) { 71 | while (ready() == 0) { 72 | delay(100); 73 | } 74 | } else { 75 | ready(); 76 | } 77 | 78 | return _status; 79 | } 80 | 81 | int GPRS::ready() 82 | { 83 | int ready = MODEM.ready(); 84 | 85 | if (ready == 0) { 86 | return 0; 87 | } 88 | 89 | MODEM.poll(); 90 | 91 | ready = 0; 92 | 93 | switch (_state) { 94 | case GPRS_STATE_IDLE: 95 | default: { 96 | break; 97 | } 98 | 99 | case GPRS_STATE_ATTACH: { 100 | MODEM.send("AT+CGATT=1"); 101 | _state = GPRS_STATE_WAIT_ATTACH_RESPONSE; 102 | ready = 0; 103 | break; 104 | } 105 | 106 | case GPRS_STATE_WAIT_ATTACH_RESPONSE: { 107 | if (ready > 1) { 108 | _state = GPRS_STATE_IDLE; 109 | _status = NB_ERROR; 110 | } else { 111 | _state = GPRS_STATE_CHECK_ATTACHED; 112 | ready = 0; 113 | } 114 | break; 115 | } 116 | 117 | case GPRS_STATE_CHECK_ATTACHED: { 118 | MODEM.setResponseDataStorage(&_response); 119 | MODEM.send("AT+CGACT?"); 120 | _state = GPRS_STATE_WAIT_CHECK_ATTACHED_RESPONSE; 121 | ready = 0; 122 | break; 123 | } 124 | 125 | case GPRS_STATE_WAIT_CHECK_ATTACHED_RESPONSE: { 126 | if (ready > 1) { 127 | _state = GPRS_STATE_IDLE; 128 | _status = NB_ERROR; 129 | } else { 130 | if (_response.indexOf("1,1") >= 0) { 131 | _state = GPRS_STATE_IDLE; 132 | _status = GPRS_READY; 133 | ready = 1; 134 | } else { 135 | _state = GPRS_STATE_WAIT_ATTACH_RESPONSE; 136 | ready = 0; 137 | } 138 | } 139 | break; 140 | } 141 | 142 | case GPRS_STATE_DEATTACH: { 143 | MODEM.send("AT+CGATT=0"); 144 | _state = GPRS_STATE_WAIT_DEATTACH_RESPONSE; 145 | ready = 0; 146 | break; 147 | } 148 | 149 | case GPRS_STATE_WAIT_DEATTACH_RESPONSE: { 150 | if (ready > 1) { 151 | _state = GPRS_STATE_IDLE; 152 | _status = NB_ERROR; 153 | } else { 154 | _state = GPRS_STATE_IDLE; 155 | _status = IDLE; 156 | ready = 1; 157 | } 158 | break; 159 | } 160 | } 161 | 162 | return ready; 163 | } 164 | 165 | IPAddress GPRS::getIPAddress() 166 | { 167 | String response; 168 | 169 | MODEM.send("AT+CGPADDR=1"); 170 | if (MODEM.waitForResponse(100, &response) == 1) { 171 | if (response.startsWith("+CGPADDR: 1,")) { 172 | response.remove(0, 12); 173 | response.remove(response.length()); 174 | 175 | IPAddress ip; 176 | 177 | if (ip.fromString(response)) { 178 | return ip; 179 | } 180 | } 181 | } 182 | 183 | return IPAddress(0, 0, 0, 0); 184 | } 185 | 186 | void GPRS::setTimeout(unsigned long timeout) 187 | { 188 | _timeout = timeout; 189 | } 190 | 191 | NB_NetworkStatus_t GPRS::status() 192 | { 193 | MODEM.poll(); 194 | return _status; 195 | } 196 | -------------------------------------------------------------------------------- /src/GPRS.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB library. 3 | Copyright (c) 2018 Arduino SA. All rights reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #ifndef _GPRS_H_INCLUDED 21 | #define _GPRS_H_INCLUDED 22 | 23 | #include 24 | #include "NB.h" 25 | 26 | #include "Modem.h" 27 | 28 | class GPRS { 29 | 30 | public: 31 | 32 | GPRS(); 33 | virtual ~GPRS(); 34 | 35 | /** Attach to GPRS/NB network 36 | @return connection status 37 | */ 38 | NB_NetworkStatus_t networkAttach() 39 | { 40 | return attachGPRS(); 41 | }; 42 | 43 | /** Detach GPRS/NB network 44 | @return connection status 45 | */ 46 | NB_NetworkStatus_t networkDetach(){ return detachGPRS(); }; 47 | 48 | 49 | /** Returns 0 if last command is still executing 50 | @return 1 if success, >1 if error 51 | */ 52 | int ready(); 53 | 54 | /** Attach to GPRS service 55 | @param synchronous Sync mode 56 | @return connection status 57 | */ 58 | NB_NetworkStatus_t attachGPRS(bool synchronous = true); 59 | 60 | /** Detach GPRS service 61 | @param synchronous Sync mode 62 | @return connection status 63 | */ 64 | NB_NetworkStatus_t detachGPRS(bool synchronous = true); 65 | 66 | /** Get actual assigned IP address in IPAddress format 67 | @return IP address in IPAddress format 68 | */ 69 | IPAddress getIPAddress(); 70 | void setTimeout(unsigned long timeout); 71 | NB_NetworkStatus_t status(); 72 | 73 | private: 74 | int _state; 75 | NB_NetworkStatus_t _status; 76 | String _response; 77 | int _pingResult; 78 | unsigned long _timeout; 79 | }; 80 | 81 | #endif 82 | -------------------------------------------------------------------------------- /src/MKRNB.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB library. 3 | Copyright (c) 2018 Arduino SA. All rights reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #ifndef _MKRNB_H_INCLUDED 21 | #define _MKRNB_H_INCLUDED 22 | 23 | #include "NB.h" 24 | #include "NB_SMS.h" 25 | #include "GPRS.h" 26 | #include "NBClient.h" 27 | #include "NBModem.h" 28 | #include "NBScanner.h" 29 | #include "NBPIN.h" 30 | 31 | #include "NBSSLClient.h" 32 | #include "NBUdp.h" 33 | 34 | #include "NBFileUtils.h" 35 | 36 | #endif 37 | -------------------------------------------------------------------------------- /src/Modem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB library. 3 | Copyright (c) 2018 Arduino SA. All rights reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #include "Modem.h" 21 | 22 | #define MODEM_MIN_RESPONSE_OR_URC_WAIT_TIME_MS 20 23 | 24 | ModemUrcHandler* ModemClass::_urcHandlers[MAX_URC_HANDLERS] = { NULL }; 25 | Print* ModemClass::_debugPrint = NULL; 26 | 27 | ModemClass::ModemClass(Uart& uart, unsigned long baud, int resetPin, int powerOnPin, int vIntPin) : 28 | _uart(&uart), 29 | _baud(baud), 30 | _resetPin(resetPin), 31 | _powerOnPin(powerOnPin), 32 | _vIntPin(vIntPin), 33 | _lastResponseOrUrcMillis(0), 34 | _atCommandState(AT_COMMAND_IDLE), 35 | _ready(1), 36 | _responseDataStorage(NULL) 37 | { 38 | _buffer.reserve(64); 39 | } 40 | 41 | void ModemClass::setVIntPin(int vIntPin) 42 | { 43 | // Allow setting only if unset, used to track state 44 | if (_vIntPin==SARA_VINT_OFF || _vIntPin==SARA_VINT_ON) { 45 | _vIntPin=vIntPin; 46 | } 47 | } 48 | 49 | int ModemClass::isPowerOn() 50 | { 51 | if (_vIntPin==SARA_VINT_OFF) { 52 | return 0; 53 | } else if (_vIntPin==SARA_VINT_ON) { 54 | return 1; 55 | } 56 | return digitalRead(_vIntPin); 57 | } 58 | 59 | #ifdef ARDUINO_PORTENTA_H7_M7 60 | #include 61 | #include 62 | mbed::DigitalInOut pwr(PD_4); 63 | mbed::DigitalInOut rst(PE_3); 64 | #endif 65 | 66 | int ModemClass::begin(bool restart) 67 | { 68 | #ifdef ARDUINO_PORTENTA_H7_M7 69 | pwr.input(); 70 | rst.input(); 71 | PMIC.begin(); 72 | PMIC.disableWatchdog(); 73 | // Set the input current limit to 2 A and the overload input voltage to 3.88 V 74 | PMIC.setInputCurrentLimit(3.0); 75 | PMIC.setInputVoltageLimit(3.88); 76 | // set the minimum voltage used to feeding the module embed on Board 77 | PMIC.setMinimumSystemVoltage(3.8); 78 | // Set the desired charge voltage to 4.11 V 79 | PMIC.setChargeVoltage(4.2); 80 | // Set the charge current to 375 mA 81 | // the charge current should be defined as maximum at (C for hour)/2h 82 | // to avoid battery explosion (for example for a 750 mAh battery set to 0.375 A) 83 | PMIC.setChargeCurrent(0.375); 84 | PMIC.enableBoostMode(); 85 | PMIC.setInputCurrentLimit(3.0); 86 | 87 | pwr.output(); 88 | pwr = 0; 89 | delay(150); 90 | pwr = 1; 91 | delay(150); 92 | pwr.input(); 93 | rst.output(); 94 | rst = 0; 95 | delay(150); 96 | rst = 1; 97 | delay(150); 98 | rst.input(); 99 | #endif 100 | 101 | #ifndef ARDUINO_PORTENTA_H7_M7 102 | // datasheet warns not to use _resetPin, this may lead to an unrecoverable state 103 | pinMode(_powerOnPin, OUTPUT); 104 | pinMode(_resetPin, OUTPUT); 105 | digitalWrite(_resetPin, LOW); 106 | if (restart) { 107 | shutdown(); 108 | end(); 109 | } 110 | #endif 111 | 112 | _uart->begin(_baud > 115200 ? 115200 : _baud); 113 | 114 | // power on module 115 | #ifndef ARDUINO_PORTENTA_H7_M7 116 | if (!isPowerOn()) { 117 | digitalWrite(_powerOnPin, HIGH); 118 | delay(150); // Datasheet says power-on pulse should be >=150ms, <=3200ms 119 | digitalWrite(_powerOnPin, LOW); 120 | setVIntPin(SARA_VINT_ON); 121 | } else { 122 | if (!autosense()) { 123 | return 0; 124 | } 125 | } 126 | #endif 127 | 128 | if (!autosense()) { 129 | return 0; 130 | } 131 | 132 | if (_baud > 115200) { 133 | sendf("AT+IPR=%ld", _baud); 134 | if (waitForResponse() != 1) { 135 | return 0; 136 | } 137 | 138 | _uart->end(); 139 | delay(100); 140 | _uart->begin(_baud); 141 | 142 | if (!autosense()) { 143 | return 0; 144 | } 145 | } 146 | 147 | return 1; 148 | } 149 | 150 | int ModemClass::shutdown() 151 | { 152 | // AT command shutdown 153 | #ifdef ARDUINO_PORTENTA_H7_M7 154 | if (autosense(200)) { 155 | #else 156 | if (isPowerOn()) { 157 | #endif 158 | send("AT+CPWROFF"); 159 | if (waitForResponse(40000) != 1) { 160 | return 0; 161 | } 162 | setVIntPin(SARA_VINT_OFF); 163 | } 164 | return 1; 165 | } 166 | 167 | void ModemClass::end() 168 | { 169 | _uart->end(); 170 | // Hardware pin power off 171 | #ifdef ARDUINO_PORTENTA_H7_M7 172 | if (1) { 173 | #else 174 | if (isPowerOn()) { 175 | #endif 176 | digitalWrite(_powerOnPin, HIGH); 177 | delay(1500); // Datasheet says power-off pulse should be >=1500ms 178 | digitalWrite(_powerOnPin, LOW); 179 | setVIntPin(SARA_VINT_OFF); 180 | } 181 | } 182 | 183 | void ModemClass::hardReset() 184 | { 185 | // Hardware pin reset, only use in EMERGENCY 186 | digitalWrite(_resetPin, HIGH); 187 | delay(10000); // Datasheet says 10s minimum low pulse on reset pin. 188 | digitalWrite(_resetPin, LOW); 189 | setVIntPin(SARA_VINT_OFF); 190 | } 191 | 192 | void ModemClass::debug() 193 | { 194 | debug(Serial); 195 | } 196 | 197 | void ModemClass::debug(Print& p) 198 | { 199 | _debugPrint = &p; 200 | } 201 | 202 | void ModemClass::noDebug() 203 | { 204 | _debugPrint = NULL; 205 | } 206 | 207 | int ModemClass::autosense(unsigned long timeout) 208 | { 209 | for (unsigned long start = millis(); (millis() - start) < timeout;) { 210 | if (noop() == 1) { 211 | return 1; 212 | } 213 | 214 | delay(100); 215 | } 216 | 217 | return 0; 218 | } 219 | 220 | int ModemClass::noop() 221 | { 222 | send("AT"); 223 | 224 | return (waitForResponse() == 1); 225 | } 226 | 227 | int ModemClass::reset() 228 | { 229 | send("AT+CFUN=15"); 230 | 231 | return (waitForResponse(1000) == 1); 232 | } 233 | 234 | size_t ModemClass::write(uint8_t c) 235 | { 236 | return _uart->write(c); 237 | } 238 | 239 | size_t ModemClass::write(const uint8_t* buf, size_t size) 240 | { 241 | size_t result = _uart->write(buf, size); 242 | 243 | // the R410m echoes the binary data - we don't want it to do so 244 | size_t ignoreCount = 0; 245 | 246 | while (ignoreCount < result) { 247 | if (_uart->available()) { 248 | _uart->read(); 249 | 250 | ignoreCount++; 251 | } 252 | } 253 | 254 | return result; 255 | } 256 | 257 | void ModemClass::send(const char* command) 258 | { 259 | // compare the time of the last response or URC and ensure 260 | // at least 20ms have passed before sending a new command 261 | unsigned long delta = millis() - _lastResponseOrUrcMillis; 262 | if(delta < MODEM_MIN_RESPONSE_OR_URC_WAIT_TIME_MS) { 263 | delay(MODEM_MIN_RESPONSE_OR_URC_WAIT_TIME_MS - delta); 264 | } 265 | 266 | _uart->println(command); 267 | _uart->flush(); 268 | _atCommandState = AT_COMMAND_IDLE; 269 | _ready = 0; 270 | } 271 | 272 | void ModemClass::sendf(const char *fmt, ...) 273 | { 274 | char buf[BUFSIZ]; 275 | 276 | va_list ap; 277 | va_start((ap), (fmt)); 278 | vsnprintf(buf, sizeof(buf) - 1, fmt, ap); 279 | va_end(ap); 280 | 281 | send(buf); 282 | } 283 | 284 | int ModemClass::waitForPrompt(unsigned long timeout) 285 | { 286 | for (unsigned long start = millis(); (millis() - start) < timeout;) { 287 | while (_uart->available()) { 288 | char c = _uart->read(); 289 | if (_debugPrint) { 290 | _debugPrint->print(c); 291 | } 292 | 293 | _buffer += c; 294 | 295 | if (_buffer.endsWith(">")) { 296 | return 1; 297 | } 298 | } 299 | } 300 | return -1; 301 | } 302 | 303 | int ModemClass::waitForResponse(unsigned long timeout, String* responseDataStorage) 304 | { 305 | _responseDataStorage = responseDataStorage; 306 | for (unsigned long start = millis(); (millis() - start) < timeout;) { 307 | int r = ready(); 308 | 309 | if (r != 0) { 310 | _responseDataStorage = NULL; 311 | return r; 312 | } 313 | } 314 | 315 | _responseDataStorage = NULL; 316 | _buffer = ""; 317 | return -1; 318 | } 319 | 320 | int ModemClass::ready() 321 | { 322 | poll(); 323 | 324 | return _ready; 325 | } 326 | 327 | void ModemClass::poll() 328 | { 329 | while (_uart->available()) { 330 | char c = _uart->read(); 331 | 332 | if (_debugPrint) { 333 | _debugPrint->write(c); 334 | } 335 | 336 | _buffer += c; 337 | 338 | switch (_atCommandState) { 339 | case AT_COMMAND_IDLE: 340 | default: { 341 | 342 | if (_buffer.startsWith("AT") && _buffer.endsWith("\r\n")) { 343 | _atCommandState = AT_RECEIVING_RESPONSE; 344 | _buffer = ""; 345 | } else if (_buffer.endsWith("\r\n")) { 346 | _buffer.trim(); 347 | 348 | if (_buffer.length()) { 349 | _lastResponseOrUrcMillis = millis(); 350 | 351 | for (int i = 0; i < MAX_URC_HANDLERS; i++) { 352 | if (_urcHandlers[i] != NULL) { 353 | _urcHandlers[i]->handleUrc(_buffer); 354 | } 355 | } 356 | } 357 | 358 | _buffer = ""; 359 | } 360 | 361 | break; 362 | } 363 | 364 | case AT_RECEIVING_RESPONSE: { 365 | if (c == '\n') { 366 | _lastResponseOrUrcMillis = millis(); 367 | int responseResultIndex; 368 | 369 | responseResultIndex = _buffer.lastIndexOf("OK\r\n"); 370 | 371 | if (responseResultIndex != -1) { 372 | _ready = 1; 373 | } else { 374 | responseResultIndex = _buffer.lastIndexOf("ERROR\r\n"); 375 | if (responseResultIndex != -1) { 376 | _ready = 2; 377 | } else { 378 | responseResultIndex = _buffer.lastIndexOf("NO CARRIER\r\n"); 379 | if (responseResultIndex != -1) { 380 | _ready = 3; 381 | } else { 382 | responseResultIndex = _buffer.lastIndexOf("CME ERROR"); 383 | if (responseResultIndex != -1) { 384 | _ready = 4; 385 | } 386 | } 387 | } 388 | } 389 | 390 | if (_ready != 0) { 391 | if (_responseDataStorage != NULL) { 392 | if (_ready > 1) { 393 | _buffer.substring(responseResultIndex); 394 | } else { 395 | _buffer.remove(responseResultIndex); 396 | } 397 | _buffer.trim(); 398 | 399 | *_responseDataStorage = _buffer; 400 | 401 | _responseDataStorage = NULL; 402 | } 403 | 404 | _atCommandState = AT_COMMAND_IDLE; 405 | _buffer = ""; 406 | return; 407 | } 408 | } 409 | break; 410 | } 411 | } 412 | } 413 | } 414 | 415 | void ModemClass::setResponseDataStorage(String* responseDataStorage) 416 | { 417 | _responseDataStorage = responseDataStorage; 418 | } 419 | 420 | void ModemClass::addUrcHandler(ModemUrcHandler* handler) 421 | { 422 | for (int i = 0; i < MAX_URC_HANDLERS; i++) { 423 | if (_urcHandlers[i] == NULL) { 424 | _urcHandlers[i] = handler; 425 | break; 426 | } 427 | } 428 | } 429 | 430 | void ModemClass::removeUrcHandler(ModemUrcHandler* handler) 431 | { 432 | for (int i = 0; i < MAX_URC_HANDLERS; i++) { 433 | if (_urcHandlers[i] == handler) { 434 | _urcHandlers[i] = NULL; 435 | break; 436 | } 437 | } 438 | } 439 | 440 | void ModemClass::setBaudRate(unsigned long baud) 441 | { 442 | _baud = baud; 443 | } 444 | 445 | #ifdef ARDUINO_PORTENTA_H7_M7 446 | #include 447 | UART SerialSARA(PA_9, PA_10, NC, NC); 448 | mbed::DigitalOut rts(PI_14, 0); 449 | #define SARA_PWR_ON PD_4 450 | #define SARA_RESETN PE_3 451 | #endif 452 | 453 | ModemClass MODEM(SerialSARA, 115200, SARA_RESETN, SARA_PWR_ON, SARA_VINT); 454 | -------------------------------------------------------------------------------- /src/Modem.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB library. 3 | Copyright (c) 2018 Arduino SA. All rights reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #ifndef _MODEM_INCLUDED_H 21 | #define _MODEM_INCLUDED_H 22 | 23 | #include 24 | #include 25 | 26 | #include 27 | 28 | /* The NB 1500 does not connect the SARA V_INT pin so that it can be monitored. 29 | The below constants and associated code enables connecting SARA_VINT to a digital input 30 | using a level shifter (1.8V to 5V) or simply a MOS transistor, say a 2N7000. 31 | The code does rudimentary tracking of the on/off state if this is not available. 32 | */ 33 | #define SARA_VINT_OFF (-1) 34 | #define SARA_VINT_ON (-2) 35 | 36 | #ifndef SARA_VINT 37 | #define SARA_VINT SARA_VINT_OFF 38 | #endif 39 | 40 | class ModemUrcHandler { 41 | public: 42 | virtual void handleUrc(const String& urc) = 0; 43 | }; 44 | 45 | #ifdef ARDUINO_PORTENTA_H7_M7 46 | typedef UART Uart; 47 | #endif 48 | 49 | class ModemClass { 50 | public: 51 | ModemClass(Uart& uart, unsigned long baud, int resetPin, int powerOnPin, int vIntPin=SARA_VINT); 52 | 53 | int begin(bool restart = false); 54 | void end(); 55 | 56 | void debug(); 57 | void debug(Print& p); 58 | void noDebug(); 59 | 60 | int autosense(unsigned long timeout = 10000); 61 | 62 | int noop(); 63 | int reset(); 64 | int shutdown(); 65 | void hardReset(); // Hardware pin reset, only use in EMERGENCY 66 | int isPowerOn(); 67 | void setVIntPin(int vIntPin); 68 | 69 | size_t write(uint8_t c); 70 | size_t write(const uint8_t*, size_t); 71 | 72 | void send(const char* command); 73 | void send(const String& command) { send(command.c_str()); } 74 | void sendf(const char *fmt, ...); 75 | 76 | int waitForPrompt(unsigned long timeout = 500); 77 | int waitForResponse(unsigned long timeout = 200, String* responseDataStorage = NULL); 78 | int ready(); 79 | void poll(); 80 | void setResponseDataStorage(String* responseDataStorage); 81 | 82 | void addUrcHandler(ModemUrcHandler* handler); 83 | void removeUrcHandler(ModemUrcHandler* handler); 84 | 85 | void setBaudRate(unsigned long baud); 86 | 87 | private: 88 | Uart* _uart; 89 | unsigned long _baud; 90 | int _resetPin; 91 | int _powerOnPin; 92 | int _vIntPin; 93 | unsigned long _lastResponseOrUrcMillis; 94 | 95 | enum { 96 | AT_COMMAND_IDLE, 97 | AT_RECEIVING_RESPONSE 98 | } _atCommandState; 99 | int _ready; 100 | String _buffer; 101 | String* _responseDataStorage; 102 | 103 | #define MAX_URC_HANDLERS 8 // 7 sockets + GPRS 104 | static ModemUrcHandler* _urcHandlers[MAX_URC_HANDLERS]; 105 | static Print* _debugPrint; 106 | }; 107 | 108 | extern ModemClass MODEM; 109 | 110 | #endif 111 | -------------------------------------------------------------------------------- /src/NB.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB library. 3 | Copyright (c) 2018 Arduino SA. All rights reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | #define _XOPEN_SOURCE 20 | #include 21 | 22 | #include "Modem.h" 23 | 24 | #include "NB.h" 25 | 26 | __attribute__((weak)) void mkr_nb_feed_watchdog() 27 | { 28 | /* This function can be overwritten by a "strong" implementation 29 | * in a higher level application, such as the ArduinoIoTCloud 30 | * firmware stack. 31 | */ 32 | } 33 | 34 | enum { 35 | READY_STATE_SET_ERROR_DISABLED, 36 | READY_STATE_WAIT_SET_ERROR_DISABLED, 37 | READY_STATE_SET_MINIMUM_FUNCTIONALITY_MODE, 38 | READY_STATE_WAIT_SET_MINIMUM_FUNCTIONALITY_MODE, 39 | READY_STATE_CHECK_SIM, 40 | READY_STATE_WAIT_CHECK_SIM_RESPONSE, 41 | READY_STATE_UNLOCK_SIM, 42 | READY_STATE_WAIT_UNLOCK_SIM_RESPONSE, 43 | READY_STATE_DETACH_DATA, 44 | READY_STATE_WAIT_DETACH_DATA, 45 | READY_STATE_SET_PREFERRED_MESSAGE_FORMAT, 46 | READY_STATE_WAIT_SET_PREFERRED_MESSAGE_FORMAT_RESPONSE, 47 | READY_STATE_SET_HEX_MODE, 48 | READY_STATE_WAIT_SET_HEX_MODE_RESPONSE, 49 | READY_STATE_SET_AUTOMATIC_TIME_ZONE, 50 | READY_STATE_WAIT_SET_AUTOMATIC_TIME_ZONE_RESPONSE, 51 | READY_STATE_SET_APN, 52 | READY_STATE_WAIT_SET_APN, 53 | READY_STATE_SET_APN_AUTH, 54 | READY_STATE_WAIT_SET_APN_AUTH, 55 | READY_STATE_SET_FULL_FUNCTIONALITY_MODE, 56 | READY_STATE_WAIT_SET_FULL_FUNCTIONALITY_MODE, 57 | READY_STATE_CHECK_REGISTRATION, 58 | READY_STATE_WAIT_CHECK_REGISTRATION_RESPONSE, 59 | READY_STATE_DONE 60 | }; 61 | 62 | NB::NB(bool debug) : 63 | _state(NB_ERROR), 64 | _readyState(0), 65 | _pin(NULL), 66 | _apn(""), 67 | _username(""), 68 | _password(""), 69 | _timeout(0) 70 | { 71 | if (debug) { 72 | MODEM.debug(); 73 | } 74 | } 75 | 76 | NB_NetworkStatus_t NB::begin(const char* pin, bool restart, bool synchronous) 77 | { 78 | return begin(pin, "", restart, synchronous); 79 | } 80 | 81 | NB_NetworkStatus_t NB::begin(const char* pin, const char* apn, bool restart, bool synchronous) 82 | { 83 | return begin(pin, apn, "", "", restart, synchronous); 84 | } 85 | 86 | NB_NetworkStatus_t NB::begin(const char* pin, const char* apn, const char* username, const char* password, bool restart, bool synchronous) 87 | { 88 | if (!MODEM.begin(restart)) { 89 | _state = NB_ERROR; 90 | } else { 91 | _pin = pin; 92 | _apn = apn; 93 | _username = username, 94 | _password = password; 95 | _state = IDLE; 96 | _readyState = READY_STATE_SET_ERROR_DISABLED; 97 | 98 | if (synchronous) { 99 | unsigned long start = millis(); 100 | 101 | while (ready() == 0) { 102 | if (_timeout && !((millis() - start) < _timeout)) { 103 | _state = NB_ERROR; 104 | break; 105 | } 106 | 107 | mkr_nb_feed_watchdog(); 108 | 109 | delay(100); 110 | } 111 | } else { 112 | return (NB_NetworkStatus_t)0; 113 | } 114 | } 115 | 116 | return _state; 117 | } 118 | 119 | int NB::isAccessAlive() 120 | { 121 | String response; 122 | 123 | MODEM.send("AT+CEREG?"); 124 | if (MODEM.waitForResponse(100, &response) == 1) { 125 | int status = response.charAt(response.length() - 1) - '0'; 126 | 127 | if (status == 1 || status == 5 || status == 8) { 128 | return 1; 129 | } 130 | } 131 | 132 | return 0; 133 | } 134 | 135 | bool NB::shutdown() 136 | { 137 | // Attempt AT command shutdown 138 | if (_state == NB_READY && MODEM.shutdown()) { 139 | _state = NB_OFF; 140 | return true; 141 | } 142 | return false; 143 | } 144 | 145 | bool NB::secureShutdown() 146 | { 147 | // Hardware power off 148 | MODEM.end(); 149 | _state = NB_OFF; 150 | return true; 151 | } 152 | 153 | int NB::ready() 154 | { 155 | if (_state == NB_ERROR) { 156 | return 2; 157 | } 158 | 159 | int ready = MODEM.ready(); 160 | 161 | if (ready == 0) { 162 | return 0; 163 | } 164 | 165 | switch (_readyState) { 166 | case READY_STATE_SET_ERROR_DISABLED: { 167 | MODEM.send("AT+CMEE=0"); 168 | _readyState = READY_STATE_WAIT_SET_ERROR_DISABLED; 169 | ready = 0; 170 | break; 171 | } 172 | 173 | case READY_STATE_WAIT_SET_ERROR_DISABLED: { 174 | if (ready > 1) { 175 | _state = NB_ERROR; 176 | ready = 2; 177 | } else { 178 | _readyState = READY_STATE_SET_MINIMUM_FUNCTIONALITY_MODE; 179 | ready = 0; 180 | } 181 | 182 | break; 183 | } 184 | 185 | case READY_STATE_SET_MINIMUM_FUNCTIONALITY_MODE: { 186 | MODEM.send("AT+CFUN=0"); 187 | _readyState = READY_STATE_WAIT_SET_MINIMUM_FUNCTIONALITY_MODE; 188 | ready = 0; 189 | break; 190 | } 191 | 192 | case READY_STATE_WAIT_SET_MINIMUM_FUNCTIONALITY_MODE:{ 193 | if (ready > 1) { 194 | _state = NB_ERROR; 195 | ready = 2; 196 | } else { 197 | _readyState = READY_STATE_CHECK_SIM; 198 | ready = 0; 199 | } 200 | 201 | break; 202 | } 203 | 204 | case READY_STATE_CHECK_SIM: { 205 | MODEM.setResponseDataStorage(&_response); 206 | MODEM.send("AT+CPIN?"); 207 | _readyState = READY_STATE_WAIT_CHECK_SIM_RESPONSE; 208 | ready = 0; 209 | break; 210 | } 211 | 212 | case READY_STATE_WAIT_CHECK_SIM_RESPONSE: { 213 | if (ready > 1) { 214 | // error => retry 215 | _readyState = READY_STATE_CHECK_SIM; 216 | ready = 0; 217 | } else { 218 | if (_response.endsWith("READY")) { 219 | _readyState = READY_STATE_SET_PREFERRED_MESSAGE_FORMAT; 220 | ready = 0; 221 | } else if (_response.endsWith("SIM PIN")) { 222 | _readyState = READY_STATE_UNLOCK_SIM; 223 | ready = 0; 224 | } else { 225 | _state = NB_ERROR; 226 | ready = 2; 227 | } 228 | } 229 | 230 | break; 231 | } 232 | 233 | case READY_STATE_UNLOCK_SIM: { 234 | if (_pin != NULL) { 235 | MODEM.setResponseDataStorage(&_response); 236 | MODEM.sendf("AT+CPIN=\"%s\"", _pin); 237 | 238 | _readyState = READY_STATE_WAIT_UNLOCK_SIM_RESPONSE; 239 | ready = 0; 240 | } else { 241 | _state = NB_ERROR; 242 | ready = 2; 243 | } 244 | break; 245 | } 246 | 247 | case READY_STATE_WAIT_UNLOCK_SIM_RESPONSE: { 248 | if (ready > 1) { 249 | _state = NB_ERROR; 250 | ready = 2; 251 | } else { 252 | _readyState = READY_STATE_DETACH_DATA; 253 | ready = 0; 254 | } 255 | 256 | break; 257 | } 258 | 259 | case READY_STATE_DETACH_DATA: { 260 | MODEM.send("AT+CGATT=0"); 261 | _readyState = READY_STATE_WAIT_DETACH_DATA; 262 | ready = 0; 263 | break; 264 | } 265 | 266 | case READY_STATE_WAIT_DETACH_DATA:{ 267 | if (ready > 1) { 268 | _state = NB_ERROR; 269 | ready = 2; 270 | } else { 271 | _readyState = READY_STATE_SET_PREFERRED_MESSAGE_FORMAT; 272 | ready = 0; 273 | } 274 | 275 | break; 276 | } 277 | 278 | case READY_STATE_SET_PREFERRED_MESSAGE_FORMAT: { 279 | MODEM.send("AT+CMGF=1"); 280 | _readyState = READY_STATE_WAIT_SET_PREFERRED_MESSAGE_FORMAT_RESPONSE; 281 | ready = 0; 282 | break; 283 | } 284 | 285 | case READY_STATE_WAIT_SET_PREFERRED_MESSAGE_FORMAT_RESPONSE: { 286 | if (ready > 1) { 287 | _state = NB_ERROR; 288 | ready = 2; 289 | } else { 290 | _readyState = READY_STATE_SET_HEX_MODE; 291 | ready = 0; 292 | } 293 | 294 | break; 295 | } 296 | 297 | case READY_STATE_SET_HEX_MODE: { 298 | MODEM.send("AT+UDCONF=1,1"); 299 | _readyState = READY_STATE_WAIT_SET_HEX_MODE_RESPONSE; 300 | ready = 0; 301 | break; 302 | } 303 | 304 | case READY_STATE_WAIT_SET_HEX_MODE_RESPONSE: { 305 | if (ready > 1) { 306 | _state = NB_ERROR; 307 | ready = 2; 308 | } else { 309 | _readyState = READY_STATE_SET_AUTOMATIC_TIME_ZONE; 310 | ready = 0; 311 | } 312 | 313 | break; 314 | } 315 | 316 | case READY_STATE_SET_AUTOMATIC_TIME_ZONE: { 317 | MODEM.send("AT+CTZU=1"); 318 | _readyState = READY_STATE_WAIT_SET_AUTOMATIC_TIME_ZONE_RESPONSE; 319 | ready = 0; 320 | break; 321 | } 322 | 323 | case READY_STATE_WAIT_SET_AUTOMATIC_TIME_ZONE_RESPONSE: { 324 | if (ready > 1) { 325 | _state = NB_ERROR; 326 | ready = 2; 327 | } else { 328 | _readyState = READY_STATE_SET_APN; 329 | ready = 0; 330 | } 331 | break; 332 | } 333 | 334 | case READY_STATE_SET_APN: { 335 | MODEM.sendf("AT+CGDCONT=1,\"IP\",\"%s\"", _apn); 336 | _readyState = READY_STATE_WAIT_SET_APN; 337 | ready = 0; 338 | break; 339 | } 340 | 341 | case READY_STATE_WAIT_SET_APN: { 342 | if (ready > 1) { 343 | _state = NB_ERROR; 344 | ready = 2; 345 | } else { 346 | _readyState = READY_STATE_SET_APN_AUTH; 347 | ready = 0; 348 | } 349 | break; 350 | } 351 | 352 | case READY_STATE_SET_APN_AUTH: { 353 | if (strlen(_username) > 0 || strlen(_password) > 0) { 354 | // CHAP 355 | MODEM.sendf("AT+UAUTHREQ=1,2,\"%s\",\"%s\"", _password, _username); 356 | } else { 357 | // no auth 358 | MODEM.sendf("AT+UAUTHREQ=1,%d", 0); 359 | } 360 | 361 | _readyState = READY_STATE_WAIT_SET_APN_AUTH; 362 | ready = 0; 363 | break; 364 | } 365 | 366 | case READY_STATE_WAIT_SET_APN_AUTH: { 367 | if (ready > 1) { 368 | _state = NB_ERROR; 369 | ready = 2; 370 | } else { 371 | _readyState = READY_STATE_SET_FULL_FUNCTIONALITY_MODE; 372 | ready = 0; 373 | } 374 | break; 375 | } 376 | 377 | case READY_STATE_SET_FULL_FUNCTIONALITY_MODE: { 378 | MODEM.send("AT+CFUN=1"); 379 | _readyState = READY_STATE_WAIT_SET_FULL_FUNCTIONALITY_MODE; 380 | ready = 0; 381 | break; 382 | } 383 | 384 | case READY_STATE_WAIT_SET_FULL_FUNCTIONALITY_MODE:{ 385 | if (ready > 1) { 386 | _state = NB_ERROR; 387 | ready = 2; 388 | } else { 389 | _readyState = READY_STATE_CHECK_REGISTRATION; 390 | ready = 0; 391 | } 392 | 393 | break; 394 | } 395 | 396 | case READY_STATE_CHECK_REGISTRATION: { 397 | MODEM.setResponseDataStorage(&_response); 398 | MODEM.send("AT+CEREG?"); 399 | _readyState = READY_STATE_WAIT_CHECK_REGISTRATION_RESPONSE; 400 | ready = 0; 401 | break; 402 | } 403 | 404 | case READY_STATE_WAIT_CHECK_REGISTRATION_RESPONSE: { 405 | if (ready > 1) { 406 | _state = NB_ERROR; 407 | ready = 2; 408 | } else { 409 | int status = _response.charAt(_response.length() - 1) - '0'; 410 | 411 | if (status == 0 || status == 4) { 412 | _readyState = READY_STATE_CHECK_REGISTRATION; 413 | ready = 0; 414 | } else if (status == 1 || status == 5 || status == 8) { 415 | _readyState = READY_STATE_DONE; 416 | _state = NB_READY; 417 | ready = 1; 418 | } else if (status == 2) { 419 | _readyState = READY_STATE_CHECK_REGISTRATION; 420 | _state = CONNECTING; 421 | ready = 0; 422 | } else if (status == 3) { 423 | _state = NB_ERROR; 424 | ready = 2; 425 | } 426 | } 427 | 428 | break; 429 | } 430 | 431 | case READY_STATE_DONE: 432 | break; 433 | } 434 | 435 | return ready; 436 | } 437 | 438 | void NB::setTimeout(unsigned long timeout) 439 | { 440 | _timeout = timeout; 441 | } 442 | 443 | unsigned long NB::getTime() 444 | { 445 | String response; 446 | 447 | MODEM.send("AT+CCLK?"); 448 | if (MODEM.waitForResponse(100, &response) != 1) { 449 | return 0; 450 | } 451 | 452 | struct tm now; 453 | 454 | int dashIndex = response.lastIndexOf('-'); 455 | if (dashIndex != -1) { 456 | response.remove(dashIndex); 457 | } 458 | 459 | if (strptime(response.c_str(), "+CCLK: \"%y/%m/%d,%H:%M:%S", &now) != NULL) { 460 | // adjust for timezone offset which is +/- in 15 minute increments 461 | 462 | time_t result = mktime(&now); 463 | time_t delta = ((response.charAt(26) - '0') * 10 + (response.charAt(27) - '0')) * (15 * 60); 464 | 465 | if (response.charAt(25) == '-') { 466 | result += delta; 467 | } else if (response.charAt(25) == '+') { 468 | result -= delta; 469 | } 470 | 471 | return result; 472 | } 473 | 474 | return 0; 475 | } 476 | 477 | unsigned long NB::getLocalTime() 478 | { 479 | String response; 480 | 481 | MODEM.send("AT+CCLK?"); 482 | if (MODEM.waitForResponse(100, &response) != 1) { 483 | return 0; 484 | } 485 | 486 | struct tm now; 487 | 488 | if (strptime(response.c_str(), "+CCLK: \"%y/%m/%d,%H:%M:%S", &now) != NULL) { 489 | 490 | time_t result = mktime(&now); 491 | return result; 492 | } 493 | 494 | return 0; 495 | } 496 | 497 | bool NB::setTime(unsigned long const epoch, int const timezone) 498 | { 499 | String hours, date; 500 | const uint8_t daysInMonth [] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30 }; 501 | unsigned long unix_time = epoch - 946684800UL; /* Subtract seconds from 1970 to 2000 */ 502 | 503 | if (((unix_time % 86400L) / 3600) < 10 ) { 504 | hours = "0"; 505 | } 506 | 507 | hours += String((unix_time % 86400L) / 3600) + ":"; 508 | if ( ((unix_time % 3600) / 60) < 10 ) { 509 | hours = "0"; 510 | } 511 | 512 | hours += String((unix_time % 3600) / 60) + ":"; 513 | if ((unix_time % 60) < 10 ) { 514 | hours += "0"; 515 | } 516 | 517 | hours += String(unix_time % 60)+ "+"; 518 | if (timezone < 10) { 519 | hours += "0"; 520 | } 521 | 522 | hours += String(timezone); 523 | /* Convert unix_time from seconds to days */ 524 | int days = unix_time / (24 * 3600); 525 | int leap; 526 | int year = 0; 527 | while (1) { 528 | leap = year % 4 == 0; 529 | if (days < 365 + leap) { 530 | if (year < 10) { 531 | date += "0"; 532 | } 533 | break; 534 | } 535 | days -= 365 + leap; 536 | year++; 537 | } 538 | 539 | date += String(year) + "/"; 540 | int month; 541 | for (month = 1; month < 12; month++) { 542 | uint8_t daysPerMonth = daysInMonth[month - 1]; 543 | if (leap && month == 2) 544 | daysPerMonth++; 545 | if (days < daysPerMonth) { 546 | if (month < 10) { 547 | date += "0"; 548 | } 549 | break; 550 | } 551 | days -= daysPerMonth; 552 | } 553 | date += String(month) + "/"; 554 | 555 | if ((days + 1) < 10) { 556 | date += "0"; 557 | } 558 | date += String(days + 1) + ","; 559 | 560 | MODEM.send("AT+CCLK=\"" + date + hours + "\""); 561 | if (MODEM.waitForResponse(100) != 1) { 562 | return false; 563 | } 564 | return true; 565 | } 566 | 567 | NB_NetworkStatus_t NB::status() 568 | { 569 | return _state; 570 | } 571 | -------------------------------------------------------------------------------- /src/NB.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB library. 3 | Copyright (c) 2018 Arduino SA. All rights reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #ifndef _NB_H_INCLUDED 21 | #define _NB_H_INCLUDED 22 | 23 | #include 24 | 25 | enum NB_NetworkStatus_t { NB_ERROR, IDLE, CONNECTING, NB_READY, GPRS_READY, TRANSPARENT_CONNECTED, NB_OFF}; 26 | 27 | class NB { 28 | 29 | public: 30 | /** Constructor 31 | @param debug Determines debug mode 32 | */ 33 | NB(bool debug = false); 34 | 35 | /** Start the NB IoT modem, attaching to the NB IoT or LTE Cat M1 network 36 | @param pin SIM PIN number (4 digits in a string, example: "1234"). If 37 | NULL the SIM has no configured PIN. 38 | @param apn (optional) APN to use 39 | @param restart Restart the modem. Default is TRUE. The modem receives 40 | a signal through the Ctrl/D7 pin. If it is shut down, it will 41 | start-up. If it is running, it will restart. Takes up to 10 42 | seconds 43 | @param synchronous If TRUE the call only returns after the Start is complete 44 | or fails. If FALSE the call will return immediately. You have 45 | to call repeatedly ready() until you get a result. Default is TRUE. 46 | @return If synchronous, NB_NetworkStatus_t. If asynchronous, returns 0. 47 | */ 48 | NB_NetworkStatus_t begin(const char* pin = 0, bool restart = true, bool synchronous = true); 49 | NB_NetworkStatus_t begin(const char* pin, const char* apn, bool restart = true, bool synchronous = true); 50 | NB_NetworkStatus_t begin(const char* pin, const char* apn, const char* username, const char* password, bool restart = true, bool synchronous = true); 51 | 52 | /** Check network access status 53 | @return 1 if Alive, 0 if down 54 | */ 55 | int isAccessAlive(); 56 | 57 | /** Shutdown the modem (power off really) 58 | @return true if successful 59 | */ 60 | bool shutdown(); 61 | 62 | /** Secure shutdown the modem (power off really) 63 | @return always true 64 | */ 65 | bool secureShutdown(); 66 | 67 | /** Get last command status 68 | @return returns 0 if last command is still executing, 1 success, >1 error 69 | */ 70 | int ready(); 71 | 72 | void setTimeout(unsigned long timeout); 73 | 74 | unsigned long getTime(); 75 | unsigned long getLocalTime(); 76 | bool setTime(unsigned long const epoch, int const timezone = 0); 77 | 78 | NB_NetworkStatus_t status(); 79 | 80 | private: 81 | NB_NetworkStatus_t _state; 82 | int _readyState; 83 | const char* _pin; 84 | const char* _apn; 85 | const char* _username; 86 | const char* _password; 87 | String _response; 88 | unsigned long _timeout; 89 | }; 90 | 91 | #endif 92 | -------------------------------------------------------------------------------- /src/NBClient.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB library. 3 | Copyright (c) 2018 Arduino SA. All rights reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #include "Modem.h" 21 | 22 | #include "utility/NBSocketBuffer.h" 23 | 24 | #include "NBClient.h" 25 | 26 | enum { 27 | CLIENT_STATE_IDLE, 28 | CLIENT_STATE_CREATE_SOCKET, 29 | CLIENT_STATE_WAIT_CREATE_SOCKET_RESPONSE, 30 | CLIENT_STATE_ENABLE_SSL, 31 | CLIENT_STATE_WAIT_ENABLE_SSL_RESPONSE, 32 | CLIENT_STATE_MANAGE_SSL_PROFILE, 33 | CLIENT_STATE_WAIT_MANAGE_SSL_PROFILE_RESPONSE, 34 | CLIENT_STATE_CONNECT, 35 | CLIENT_STATE_WAIT_CONNECT_RESPONSE, 36 | CLIENT_STATE_CLOSE_SOCKET, 37 | CLIENT_STATE_WAIT_CLOSE_SOCKET, 38 | CLIENT_STATE_RETRIEVE_ERROR 39 | }; 40 | 41 | NBClient::NBClient(bool synch) : 42 | NBClient(-1, synch) 43 | { 44 | } 45 | 46 | NBClient::NBClient(int socket, bool synch) : 47 | _synch(synch), 48 | _socket(socket), 49 | _connected(false), 50 | _state(CLIENT_STATE_IDLE), 51 | _ip((uint32_t)0), 52 | _host(NULL), 53 | _port(0), 54 | _ssl(false), 55 | _writeSync(true) 56 | { 57 | MODEM.addUrcHandler(this); 58 | } 59 | 60 | NBClient::~NBClient() 61 | { 62 | MODEM.removeUrcHandler(this); 63 | } 64 | 65 | int NBClient::ready() 66 | { 67 | int ready = MODEM.ready(); 68 | 69 | if (ready == 0) { 70 | return 0; 71 | } 72 | 73 | switch (_state) { 74 | case CLIENT_STATE_IDLE: 75 | default: { 76 | break; 77 | } 78 | 79 | case CLIENT_STATE_CREATE_SOCKET: { 80 | MODEM.setResponseDataStorage(&_response); 81 | MODEM.send("AT+USOCR=6"); 82 | 83 | _state = CLIENT_STATE_WAIT_CREATE_SOCKET_RESPONSE; 84 | ready = 0; 85 | break; 86 | } 87 | 88 | case CLIENT_STATE_WAIT_CREATE_SOCKET_RESPONSE: { 89 | if (ready > 1 || !_response.startsWith("+USOCR: ")) { 90 | _state = CLIENT_STATE_IDLE; 91 | } else { 92 | _socket = _response.charAt(_response.length() - 1) - '0'; 93 | 94 | if (_ssl) { 95 | _state = CLIENT_STATE_ENABLE_SSL; 96 | } else { 97 | _state = CLIENT_STATE_CONNECT; 98 | } 99 | 100 | ready = 0; 101 | } 102 | break; 103 | } 104 | 105 | case CLIENT_STATE_ENABLE_SSL: { 106 | MODEM.sendf("AT+USOSEC=%d,1,0", _socket); 107 | 108 | _state = CLIENT_STATE_WAIT_ENABLE_SSL_RESPONSE; 109 | ready = 0; 110 | break; 111 | } 112 | 113 | case CLIENT_STATE_WAIT_ENABLE_SSL_RESPONSE: { 114 | if (ready > 1) { 115 | _state = CLIENT_STATE_CLOSE_SOCKET; 116 | } else { 117 | _state = CLIENT_STATE_MANAGE_SSL_PROFILE; 118 | } 119 | 120 | ready = 0; 121 | break; 122 | } 123 | 124 | case CLIENT_STATE_MANAGE_SSL_PROFILE: { 125 | MODEM.send("AT+USECPRF=0,0,1"); 126 | 127 | _state = CLIENT_STATE_WAIT_MANAGE_SSL_PROFILE_RESPONSE; 128 | ready = 0; 129 | break; 130 | } 131 | 132 | case CLIENT_STATE_WAIT_MANAGE_SSL_PROFILE_RESPONSE: { 133 | if (ready > 1) { 134 | _state = CLIENT_STATE_CLOSE_SOCKET; 135 | } else { 136 | _state = CLIENT_STATE_CONNECT; 137 | } 138 | ready = 0; 139 | break; 140 | } 141 | 142 | case CLIENT_STATE_CONNECT: { 143 | if (_host != NULL) { 144 | MODEM.sendf("AT+USOCO=%d,\"%s\",%d", _socket, _host, _port); 145 | } else { 146 | MODEM.sendf("AT+USOCO=%d,\"%d.%d.%d.%d\",%d", _socket, _ip[0], _ip[1], _ip[2], _ip[3], _port); 147 | } 148 | 149 | _state = CLIENT_STATE_WAIT_CONNECT_RESPONSE; 150 | ready = 0; 151 | break; 152 | } 153 | 154 | case CLIENT_STATE_WAIT_CONNECT_RESPONSE: { 155 | if (ready > 1) { 156 | _state = CLIENT_STATE_CLOSE_SOCKET; 157 | 158 | ready = 0; 159 | } else { 160 | _connected = true; 161 | _state = CLIENT_STATE_IDLE; 162 | } 163 | break; 164 | } 165 | 166 | case CLIENT_STATE_CLOSE_SOCKET: { 167 | 168 | MODEM.sendf("AT+USOCL=%d", _socket); 169 | 170 | _state = CLIENT_STATE_WAIT_CLOSE_SOCKET; 171 | ready = 0; 172 | break; 173 | } 174 | 175 | case CLIENT_STATE_WAIT_CLOSE_SOCKET: { 176 | _state = CLIENT_STATE_RETRIEVE_ERROR; 177 | _socket = -1; 178 | break; 179 | } 180 | 181 | case CLIENT_STATE_RETRIEVE_ERROR: { 182 | MODEM.send("AT+USOER"); 183 | _state = CLIENT_STATE_IDLE; 184 | break; 185 | } 186 | } 187 | 188 | return ready; 189 | } 190 | 191 | int NBClient::connect(IPAddress ip, uint16_t port) 192 | { 193 | _ip = ip; 194 | _host = NULL; 195 | _port = port; 196 | _ssl = false; 197 | 198 | return connect(); 199 | } 200 | 201 | int NBClient::connectSSL(IPAddress ip, uint16_t port) 202 | { 203 | _ip = ip; 204 | _host = NULL; 205 | _port = port; 206 | _ssl = true; 207 | 208 | return connect(); 209 | } 210 | 211 | int NBClient::connect(const char *host, uint16_t port) 212 | { 213 | _ip = (uint32_t)0; 214 | _host = host; 215 | _port = port; 216 | _ssl = false; 217 | 218 | return connect(); 219 | } 220 | 221 | int NBClient::connectSSL(const char *host, uint16_t port) 222 | { 223 | _ip = (uint32_t)0; 224 | _host = host; 225 | _port = port; 226 | _ssl = true; 227 | 228 | return connect(); 229 | } 230 | 231 | int NBClient::connect() 232 | { 233 | if (_socket != -1) { 234 | stop(); 235 | } 236 | 237 | if (_synch) { 238 | while (ready() == 0); 239 | } else if (ready() == 0) { 240 | return 0; 241 | } 242 | 243 | _state = CLIENT_STATE_CREATE_SOCKET; 244 | 245 | if (_synch) { 246 | while (ready() == 0) { 247 | delay(100); 248 | } 249 | 250 | if (_socket == -1) { 251 | return 0; 252 | } 253 | } 254 | 255 | return 1; 256 | } 257 | 258 | void NBClient::beginWrite(bool sync) 259 | { 260 | _writeSync = sync; 261 | } 262 | 263 | size_t NBClient::write(uint8_t c) 264 | { 265 | return write(&c, 1); 266 | } 267 | 268 | size_t NBClient::write(const uint8_t *buf) 269 | { 270 | return write(buf, strlen((const char*)buf)); 271 | } 272 | 273 | size_t NBClient::write(const uint8_t* buf, size_t size) 274 | { 275 | if (_writeSync) { 276 | while (ready() == 0); 277 | } else if (ready() == 0) { 278 | return 0; 279 | } 280 | 281 | if (_socket == -1) { 282 | return 0; 283 | } 284 | 285 | size_t written = 0; 286 | String command; 287 | 288 | command.reserve(19 + (size > 256 ? 256 : size) * 2); 289 | 290 | while (size) { 291 | size_t chunkSize = size; 292 | 293 | if (chunkSize > 256) { 294 | chunkSize = 256; 295 | } 296 | 297 | command.reserve(19 + chunkSize * 2); 298 | 299 | command = "AT+USOWR="; 300 | command += _socket; 301 | command += ","; 302 | command += chunkSize; 303 | command += ",\""; 304 | 305 | for (size_t i = 0; i < chunkSize; i++) { 306 | byte b = buf[i + written]; 307 | 308 | byte n1 = (b >> 4) & 0x0f; 309 | byte n2 = (b & 0x0f); 310 | 311 | command += (char)(n1 > 9 ? 'A' + n1 - 10 : '0' + n1); 312 | command += (char)(n2 > 9 ? 'A' + n2 - 10 : '0' + n2); 313 | } 314 | 315 | command += "\""; 316 | 317 | MODEM.send(command); 318 | if (_writeSync) { 319 | String response; 320 | int status = MODEM.waitForResponse(10000, &response); 321 | if ( status != 1) { 322 | if (status == 4 && response.indexOf("Operation not allowed") != -1 ) { 323 | stop(); 324 | break; 325 | } else { 326 | break; 327 | } 328 | } 329 | } 330 | 331 | written += chunkSize; 332 | size -= chunkSize; 333 | } 334 | 335 | return written; 336 | } 337 | 338 | void NBClient::endWrite(bool /*sync*/) 339 | { 340 | _writeSync = true; 341 | } 342 | 343 | uint8_t NBClient::connected() 344 | { 345 | MODEM.poll(); 346 | 347 | if (_socket == -1) { 348 | return 0; 349 | } 350 | 351 | // call available to update socket state 352 | if (NBSocketBuffer.available(_socket) < 0 || (_ssl && !_connected)) { 353 | stop(); 354 | 355 | return 0; 356 | } 357 | 358 | return 1; 359 | } 360 | 361 | NBClient::operator bool() 362 | { 363 | return (_socket != -1); 364 | } 365 | 366 | int NBClient::read(uint8_t *buf, size_t size) 367 | { 368 | if (_socket == -1) { 369 | return 0; 370 | } 371 | 372 | if (size == 0) { 373 | return 0; 374 | } 375 | 376 | int avail = available(); 377 | 378 | if (avail == 0) { 379 | return 0; 380 | } 381 | 382 | return NBSocketBuffer.read(_socket, buf, size); 383 | } 384 | 385 | int NBClient::read() 386 | { 387 | byte b; 388 | 389 | if (read(&b, 1) == 1) { 390 | return b; 391 | } 392 | 393 | return -1; 394 | } 395 | 396 | int NBClient::available() 397 | { 398 | if (_synch) { 399 | while (ready() == 0); 400 | } else if (ready() == 0) { 401 | return 0; 402 | } 403 | 404 | if (_socket == -1) { 405 | return 0; 406 | } 407 | 408 | int avail = NBSocketBuffer.available(_socket); 409 | 410 | if (avail < 0) { 411 | stop(); 412 | 413 | return 0; 414 | } 415 | 416 | return avail; 417 | } 418 | 419 | int NBClient::peek() 420 | { 421 | if (available() > 0) { 422 | return NBSocketBuffer.peek(_socket); 423 | } 424 | 425 | return -1; 426 | } 427 | 428 | void NBClient::flush() 429 | { 430 | } 431 | 432 | void NBClient::stop() 433 | { 434 | _state = CLIENT_STATE_IDLE; 435 | if (_socket < 0) { 436 | return; 437 | } 438 | 439 | MODEM.sendf("AT+USOCL=%d", _socket); 440 | MODEM.waitForResponse(10000); 441 | 442 | NBSocketBuffer.close(_socket); 443 | 444 | _socket = -1; 445 | _connected = false; 446 | } 447 | 448 | void NBClient::handleUrc(const String& urc) 449 | { 450 | if (urc.startsWith("+UUSORD: ")) { 451 | int socket = urc.charAt(9) - '0'; 452 | if (socket == _socket) { 453 | if (urc.endsWith(",4294967295")) { 454 | _connected = false; 455 | } 456 | } 457 | } 458 | } -------------------------------------------------------------------------------- /src/NBClient.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB library. 3 | Copyright (c) 2018 Arduino SA. All rights reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #ifndef _NB_CLIENT_H_INCLUDED 21 | #define _NB_CLIENT_H_INCLUDED 22 | 23 | #include "Modem.h" 24 | 25 | #include 26 | 27 | class NBClient : public Client, public ModemUrcHandler { 28 | 29 | public: 30 | 31 | /** Constructor 32 | @param synch Sync mode 33 | */ 34 | NBClient(bool synch = true); 35 | 36 | /** Constructor 37 | @param socket Socket 38 | @param synch Sync mode 39 | */ 40 | NBClient(int socket, bool synch); 41 | 42 | virtual ~NBClient(); 43 | 44 | /** Get last command status 45 | @return returns 0 if last command is still executing, 1 success, >1 error 46 | */ 47 | virtual int ready(); 48 | 49 | /** Connect to server by IP address 50 | @param (IPAddress) 51 | @param (uint16_t) 52 | @return returns 0 if last command is still executing, 1 success, 2 if there are no resources 53 | */ 54 | int connect(IPAddress, uint16_t); 55 | int connectSSL(IPAddress, uint16_t); 56 | 57 | /** Connect to server by hostname 58 | @param host Hostname 59 | @param port Port 60 | @return returns 0 if last command is still executing, 1 success, 2 if there are no resources 61 | */ 62 | int connect(const char *host, uint16_t port); 63 | int connectSSL(const char *host, uint16_t port); 64 | 65 | /** Initialize write in request 66 | @param sync Sync mode 67 | */ 68 | void beginWrite(bool sync = false); 69 | 70 | /** Write a character in request 71 | @param c Character 72 | @return size 73 | */ 74 | size_t write(uint8_t c); 75 | 76 | /** Write a characters buffer in request 77 | @param buf Buffer 78 | @return buffer size 79 | */ 80 | size_t write(const uint8_t *buf); 81 | 82 | /** Write a characters buffer with size in request 83 | @param (uint8_t*) Buffer 84 | @param (size_t) Buffer size 85 | @return buffer size 86 | */ 87 | size_t write(const uint8_t*, size_t); 88 | 89 | /** Finish write request 90 | @param sync Sync mode 91 | */ 92 | void endWrite(bool sync = false); 93 | 94 | /** Check if connected to server 95 | @return 1 if connected 96 | */ 97 | uint8_t connected(); 98 | 99 | operator bool(); 100 | 101 | /** Read from response buffer and copy size specified to buffer 102 | @param buf Buffer 103 | @param size Buffer size 104 | @return bytes read 105 | */ 106 | int read(uint8_t *buf, size_t size); 107 | 108 | /** Read a character from response buffer 109 | @return character 110 | */ 111 | int read(); 112 | 113 | /** Check if exists a response available 114 | @return 1 if exists, 0 if not exists 115 | */ 116 | int available(); 117 | 118 | /** Read a character from response buffer but does not move the pointer. 119 | @return character 120 | */ 121 | int peek(); 122 | 123 | /** Flush response buffer 124 | */ 125 | void flush(); 126 | 127 | /** Stop client 128 | */ 129 | void stop(); 130 | 131 | virtual void handleUrc(const String& urc); 132 | 133 | private: 134 | int connect(); 135 | 136 | bool _synch; 137 | int _socket; 138 | int _connected; 139 | 140 | int _state; 141 | IPAddress _ip; 142 | const char* _host; 143 | uint16_t _port; 144 | bool _ssl; 145 | 146 | bool _writeSync; 147 | String _response; 148 | }; 149 | 150 | #endif 151 | -------------------------------------------------------------------------------- /src/NBFileUtils.cpp: -------------------------------------------------------------------------------- 1 | #include "Modem.h" 2 | #include "NBFileUtils.h" 3 | 4 | NBFileUtils::NBFileUtils(bool debug) 5 | : _count(0) 6 | , _files("") 7 | , _debug(debug) 8 | { 9 | } 10 | 11 | bool NBFileUtils::begin(const bool restart) 12 | { 13 | int status; 14 | 15 | MODEM.begin(restart); 16 | 17 | if (_debug) { 18 | MODEM.debug(); 19 | MODEM.send("AT+CMEE=2"); 20 | MODEM.waitForResponse(); 21 | } 22 | 23 | for (unsigned long start = millis(); (millis() - start) < 10000;) { 24 | status = _getFileList(); 25 | if (status == 1) { 26 | _countFiles(); 27 | return true; 28 | } 29 | MODEM.poll(); 30 | } 31 | return false; 32 | } 33 | 34 | int NBFileUtils::_getFileList() 35 | { 36 | String response; 37 | int status = 0; 38 | 39 | while (!status) { 40 | MODEM.send("AT+ULSTFILE=0"); 41 | status = MODEM.waitForResponse(5000, &response); 42 | 43 | if (status) { 44 | String list = response.substring(11); 45 | list.trim(); 46 | _files = list; 47 | } 48 | } 49 | return status; 50 | } 51 | 52 | int NBFileUtils::existFile(const String filename) 53 | { 54 | _getFileList(); 55 | _countFiles(); 56 | 57 | String files[_count]; 58 | 59 | int num = listFiles(files); 60 | 61 | for (int i = 0; i 0) { 75 | for (int index = list.indexOf(','); index != -1; index = list.indexOf(',')) { 76 | list.remove(0, index + 1); 77 | ++len; 78 | } 79 | ++len; 80 | } 81 | _count = len; 82 | } 83 | 84 | size_t NBFileUtils::listFiles(String files[]) const 85 | { 86 | String list = _files; 87 | int index; 88 | 89 | if (_count == 0) 90 | return 0; 91 | 92 | size_t n = 0; 93 | 94 | for (index = list.indexOf(','); index != -1; index = list.indexOf(',')) { 95 | String file = list.substring(1, index - 1); 96 | files[n++] = file; 97 | list.remove(0, index + 1); 98 | } 99 | files[n++] = list.substring(1, list.lastIndexOf("\"")); 100 | 101 | return n; 102 | } 103 | 104 | uint32_t NBFileUtils::downloadFile(const String filename, const char buf[], uint32_t size, const bool append) 105 | { 106 | if (!append) 107 | deleteFile(filename); 108 | 109 | int status = 0; 110 | 111 | while (!status) { 112 | MODEM.sendf("AT+UDWNFILE=\"%s\",%d", filename.c_str(), size * 2); 113 | MODEM.waitForPrompt(20000); 114 | 115 | char hex[size * 2] { 0 }; 116 | 117 | for (auto i = 0; i < size; i++) { 118 | byte b = buf[i]; 119 | 120 | byte n1 = (b >> 4) & 0x0f; 121 | byte n2 = (b & 0x0f); 122 | 123 | hex[i * 2] = (char)(n1 > 9 ? 'A' + n1 - 10 : '0' + n1); 124 | hex[i * 2 + 1] = (char)(n2 > 9 ? 'A' + n2 - 10 : '0' + n2); 125 | } 126 | for (auto h : hex) 127 | MODEM.write(h); 128 | 129 | status = MODEM.waitForResponse(1000); 130 | } 131 | 132 | auto fileExists = _files.indexOf(filename) > 0; 133 | if (!fileExists) { 134 | _getFileList(); 135 | _countFiles(); 136 | } 137 | 138 | return size; 139 | } 140 | 141 | uint32_t NBFileUtils::createFile(const String filename, const char buf[], uint32_t size) 142 | { 143 | uint32_t sizeFile; 144 | sizeFile = listFile(filename); 145 | if (sizeFile) { 146 | return sizeFile; 147 | } 148 | return downloadFile(filename, buf, size, true); 149 | } 150 | 151 | uint32_t NBFileUtils::readFile(const String filename, String* content) 152 | { 153 | String response; 154 | 155 | if (!listFile(filename)) { 156 | return 0; 157 | } 158 | 159 | MODEM.sendf("AT+URDFILE=\"%s\"", filename.c_str()); 160 | MODEM.waitForResponse(1000, &response); 161 | 162 | size_t skip = 10; 163 | String _content = response.substring(skip); 164 | 165 | int commaIndex = _content.indexOf(','); 166 | skip += commaIndex; 167 | 168 | _content = _content.substring(commaIndex + 1); 169 | commaIndex = _content.indexOf(','); 170 | skip += commaIndex; 171 | 172 | String sizePart = _content.substring(0, commaIndex); 173 | uint32_t size = sizePart.toInt() / 2; 174 | skip += 3; 175 | 176 | String* _data = content; 177 | (*_data).reserve(size); 178 | 179 | for (auto i = 0; i < size; i++) { 180 | byte n1 = response[skip + i * 2]; 181 | byte n2 = response[skip + i * 2 + 1]; 182 | 183 | if (n1 > '9') { 184 | n1 = (n1 - 'A') + 10; 185 | } else { 186 | n1 = (n1 - '0'); 187 | } 188 | 189 | if (n2 > '9') { 190 | n2 = (n2 - 'A') + 10; 191 | } else { 192 | n2 = (n2 - '0'); 193 | } 194 | 195 | (*_data) += (char)((n1 << 4) | n2); 196 | } 197 | 198 | return (*_data).length(); 199 | } 200 | 201 | uint32_t NBFileUtils::readFile(const String filename, uint8_t* content) 202 | { 203 | String response; 204 | 205 | if (listFile(filename) == 0) { 206 | return 0; 207 | } 208 | 209 | MODEM.sendf("AT+URDFILE=\"%s\"", filename.c_str()); 210 | MODEM.waitForResponse(1000, &response); 211 | 212 | size_t skip = 10; 213 | String _content = response.substring(skip); 214 | 215 | int commaIndex = _content.indexOf(','); 216 | skip += commaIndex; 217 | 218 | _content = _content.substring(commaIndex + 1); 219 | commaIndex = _content.indexOf(','); 220 | skip += commaIndex; 221 | 222 | String sizePart = _content.substring(0, commaIndex); 223 | uint32_t size = sizePart.toInt() / 2; 224 | skip += 3; 225 | 226 | for (auto i = 0; i < size; i++) { 227 | byte n1 = response[skip + i * 2]; 228 | byte n2 = response[skip + i * 2 + 1]; 229 | 230 | if (n1 > '9') { 231 | n1 = (n1 - 'A') + 10; 232 | } else { 233 | n1 = (n1 - '0'); 234 | } 235 | 236 | if (n2 > '9') { 237 | n2 = (n2 - 'A') + 10; 238 | } else { 239 | n2 = (n2 - '0'); 240 | } 241 | 242 | content[i] = (n1 << 4) | n2; 243 | } 244 | 245 | return size; 246 | } 247 | 248 | uint32_t NBFileUtils::readBlock(const String filename, const uint32_t offset, const uint32_t len, uint8_t* content) 249 | { 250 | String response; 251 | 252 | if (listFile(filename) == 0) { 253 | return 0; 254 | } 255 | 256 | MODEM.sendf("AT+URDBLOCK=\"%s\",%d,%d", filename.c_str(), offset * 2, len * 2); 257 | MODEM.waitForResponse(1000, &response); 258 | 259 | size_t skip = 10; 260 | String _content = response.substring(skip); 261 | 262 | int commaIndex = _content.indexOf(','); 263 | skip += commaIndex; 264 | 265 | _content = _content.substring(commaIndex + 1); 266 | commaIndex = _content.indexOf(','); 267 | skip += commaIndex; 268 | 269 | String sizePart = _content.substring(0, commaIndex); 270 | uint32_t size = sizePart.toInt() / 2; 271 | skip += 3; 272 | 273 | for (auto i = 0; i < size; i++) { 274 | byte n1 = response[skip + i * 2]; 275 | byte n2 = response[skip + i * 2 + 1]; 276 | 277 | if (n1 > '9') { 278 | n1 = (n1 - 'A') + 10; 279 | } else { 280 | n1 = (n1 - '0'); 281 | } 282 | 283 | if (n2 > '9') { 284 | n2 = (n2 - 'A') + 10; 285 | } else { 286 | n2 = (n2 - '0'); 287 | } 288 | 289 | content[i] = (n1 << 4) | n2; 290 | } 291 | 292 | return size; 293 | } 294 | 295 | bool NBFileUtils::deleteFile(const String filename) 296 | { 297 | String response; 298 | 299 | MODEM.sendf("AT+UDELFILE=\"%s\"", filename.c_str()); 300 | auto status = MODEM.waitForResponse(100, &response); 301 | 302 | if (status == 0) 303 | return false; 304 | 305 | _getFileList(); 306 | _countFiles(); 307 | 308 | return true; 309 | } 310 | 311 | int NBFileUtils::deleteFiles() 312 | { 313 | int n = 0; 314 | String files[_count]; 315 | 316 | int num = listFiles(files); 317 | 318 | while (_count > 0) { 319 | n += deleteFile(files[_count - 1]); 320 | } 321 | 322 | return n; 323 | } 324 | 325 | uint32_t NBFileUtils::listFile(const String filename) const 326 | { 327 | String response; 328 | int res; 329 | uint32_t size = 0; 330 | 331 | MODEM.sendf("AT+ULSTFILE=2,\"%s\"", filename.c_str()); 332 | res = MODEM.waitForResponse(5000, &response); 333 | if (res == 1) { 334 | String content = response.substring(11); 335 | size = content.toInt(); 336 | } 337 | 338 | return size / 2; 339 | } 340 | 341 | uint32_t NBFileUtils::freeSpace() 342 | { 343 | String response; 344 | int res; 345 | uint32_t size = 0; 346 | 347 | MODEM.send("AT+ULSTFILE=1"); 348 | res = MODEM.waitForResponse(100, &response); 349 | if (res == 1) { 350 | String content = response.substring(11); 351 | size = content.toInt(); 352 | } 353 | 354 | return size; 355 | } 356 | 357 | void printFiles(const NBFileUtils fu) 358 | { 359 | auto count { fu.fileCount() }; 360 | String files[count]; 361 | 362 | Serial.print(count); 363 | Serial.print(count == 1 ? " file" : " files"); 364 | Serial.println(" found."); 365 | 366 | fu.listFiles(files); 367 | 368 | for (auto f : files) { 369 | Serial.print("File "); 370 | Serial.print(f); 371 | Serial.print(" - Size: "); 372 | Serial.print(fu.listFile(f)); 373 | Serial.println(); 374 | } 375 | } -------------------------------------------------------------------------------- /src/NBFileUtils.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | 6 | class NBFileUtils { 7 | public: 8 | NBFileUtils(bool debug = false); 9 | 10 | bool begin(const bool restart); 11 | bool begin() { return begin(true); }; 12 | 13 | int existFile(const String filename); 14 | 15 | uint32_t fileCount() const { return _count; }; 16 | size_t listFiles(String list[]) const; 17 | uint32_t listFile(const String filename) const; 18 | 19 | uint32_t downloadFile(const String filename, const char buf[], const uint32_t size, const bool append); 20 | uint32_t downloadFile(const String filename, const char buf[], const uint32_t size) { return downloadFile(filename, buf, size, false); }; 21 | uint32_t downloadFile(const String filename, const String& buf) { return downloadFile(filename, buf.c_str(), buf.length(), false); } 22 | 23 | uint32_t createFile(const String filename, const char buf[], uint32_t size); 24 | 25 | uint32_t appendFile(const String filename, const String& buf) { return downloadFile(filename, buf.c_str(), buf.length(), true); } 26 | uint32_t appendFile(const String filename, const char buf[], const uint32_t size) { return downloadFile(filename, buf, size, true); } 27 | 28 | bool deleteFile(const String filename); 29 | int deleteFiles(); 30 | 31 | uint32_t readFile(const String filename, String* content); 32 | uint32_t readFile(const String filename, uint8_t* content); 33 | uint32_t readBlock(const String filename, const uint32_t offset, const uint32_t len, uint8_t* content); 34 | 35 | uint32_t freeSpace(); 36 | 37 | private: 38 | int _count; 39 | String _files; 40 | 41 | bool _debug; 42 | 43 | void _countFiles(); 44 | int _getFileList(); 45 | 46 | }; 47 | 48 | void printFiles(const NBFileUtils fileUtils); -------------------------------------------------------------------------------- /src/NBModem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB library. 3 | Copyright (c) 2018 Arduino SA. All rights reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #include "Modem.h" 21 | 22 | #include "NBModem.h" 23 | 24 | NBModem::NBModem() 25 | { 26 | } 27 | 28 | int NBModem::begin() 29 | { 30 | if (!MODEM.begin()) { 31 | return 0; 32 | } 33 | 34 | return 1; 35 | } 36 | 37 | String NBModem::getIMEI() 38 | { 39 | String imei; 40 | 41 | imei.reserve(15); 42 | 43 | MODEM.send("AT+CGSN"); 44 | MODEM.waitForResponse(100, &imei); 45 | 46 | return imei; 47 | } 48 | 49 | String NBModem::getICCID() 50 | { 51 | String iccid; 52 | 53 | iccid.reserve(7 + 20); 54 | 55 | MODEM.send("AT+CCID"); 56 | MODEM.waitForResponse(1000, &iccid); 57 | 58 | if (iccid.startsWith("+CCID: ")) { 59 | iccid.remove(0, 7); 60 | } else { 61 | iccid = ""; 62 | } 63 | 64 | return iccid; 65 | } 66 | -------------------------------------------------------------------------------- /src/NBModem.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB library. 3 | Copyright (c) 2018 Arduino SA. All rights reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #ifndef _NB_MODEM_H_INCLUDED 21 | #define _NB_MODEM_H_INCLUDED 22 | 23 | #include 24 | 25 | class NBModem { 26 | 27 | public: 28 | 29 | /** Constructor */ 30 | NBModem(); 31 | 32 | /** Check modem response and restart it 33 | */ 34 | int begin(); 35 | 36 | /** Obtain modem IMEI (command AT) 37 | @return modem IMEI number 38 | */ 39 | String getIMEI(); 40 | 41 | /** Obtain SIM card ICCID (command AT) 42 | @return SIM ICCID number 43 | */ 44 | String getICCID(); 45 | }; 46 | 47 | #endif 48 | -------------------------------------------------------------------------------- /src/NBPIN.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB library. 3 | Copyright (c) 2018 Arduino SA. All rights reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #include "Modem.h" 21 | 22 | #include "NBPIN.h" 23 | 24 | NBPIN::NBPIN() : 25 | _pinUsed(false) 26 | { 27 | } 28 | 29 | void NBPIN::begin() 30 | { 31 | MODEM.begin(); 32 | } 33 | 34 | int NBPIN::isPIN() 35 | { 36 | String response; 37 | 38 | for (unsigned long start = millis(); (millis() - start) < 1000;) { 39 | MODEM.send("AT+CPIN?"); 40 | 41 | if (MODEM.waitForResponse(10000, &response) == 1) { 42 | if (response.startsWith("+CPIN: ")) { 43 | if (response.endsWith("READY")) { 44 | return 0; 45 | } else if (response.endsWith("SIM PIN")) { 46 | return 1; 47 | } else if (response.endsWith("SIM PUK")) { 48 | return -1; 49 | } else { 50 | return -2; 51 | } 52 | } 53 | } 54 | 55 | delay(100); 56 | } 57 | 58 | return -2; 59 | } 60 | 61 | int NBPIN::checkPIN(String pin) 62 | { 63 | MODEM.sendf("AT+CPIN=\"%s\"", pin.c_str()); 64 | if (MODEM.waitForResponse(10000) == 1) { 65 | return 0; 66 | } 67 | 68 | return -1; 69 | } 70 | 71 | int NBPIN::checkPUK(String puk, String pin) 72 | { 73 | MODEM.sendf("AT+CPIN=\"%s\",\"%s\"", puk.c_str(), pin.c_str()); 74 | if (MODEM.waitForResponse(10000) == 1) { 75 | return 0; 76 | } 77 | 78 | return -1; 79 | } 80 | 81 | void NBPIN::changePIN(String old, String pin) 82 | { 83 | MODEM.sendf("AT+CPWD=\"SC\",\"%s\",\"%s\"", old.c_str(), pin.c_str()); 84 | if (MODEM.waitForResponse(10000) == 1) { 85 | Serial.println("Pin changed successfully."); 86 | } else { 87 | Serial.println("ERROR"); 88 | } 89 | } 90 | 91 | void NBPIN::switchPIN(String pin) 92 | { 93 | String response; 94 | 95 | MODEM.send("AT+CLCK=\"SC\",2"); 96 | if (MODEM.waitForResponse(180000, &response) != 1) { 97 | Serial.println("ERROR"); 98 | return; 99 | } 100 | 101 | if (response == "+CLCK: 0") { 102 | MODEM.sendf("AT+CLCK=\"SC\",1,\"%s\"", pin.c_str()); 103 | if (MODEM.waitForResponse(180000, &response) == 1) { 104 | Serial.println("OK. PIN lock on."); 105 | _pinUsed = true; 106 | } else { 107 | Serial.println("ERROR"); 108 | _pinUsed = false; 109 | } 110 | } else if (response == "+CLCK: 1") { 111 | MODEM.sendf("AT+CLCK=\"SC\",0,\"%s\"", pin.c_str()); 112 | if (MODEM.waitForResponse(180000, &response) == 1) { 113 | Serial.println("OK. PIN lock off."); 114 | _pinUsed = false; 115 | } else { 116 | Serial.println("ERROR"); 117 | _pinUsed = true; 118 | } 119 | } else { 120 | Serial.println("ERROR"); 121 | } 122 | } 123 | 124 | int NBPIN::checkReg() 125 | { 126 | for (unsigned long start = millis(); (millis() - start) < 10000L;) { 127 | MODEM.send("AT+CREG?"); 128 | 129 | String response = ""; 130 | 131 | if (MODEM.waitForResponse(100, &response) == 1) { 132 | if (response.startsWith("+CREG: ")) { 133 | if (response.endsWith(",1")) { 134 | return 0; 135 | } else if (response.endsWith(",5")) { 136 | return 1; 137 | } 138 | } 139 | } 140 | 141 | delay(100); 142 | } 143 | 144 | return -1; 145 | } 146 | 147 | bool NBPIN::getPINUsed() 148 | { 149 | return _pinUsed; 150 | } 151 | 152 | void NBPIN::setPINUsed(bool used) 153 | { 154 | _pinUsed = used; 155 | } 156 | -------------------------------------------------------------------------------- /src/NBPIN.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB library. 3 | Copyright (c) 2018 Arduino SA. All rights reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #ifndef _NB_PIN_H_INCLUDED 21 | #define _NB_PIN_H_INCLUDED 22 | 23 | #include 24 | 25 | class NBPIN { 26 | 27 | public: 28 | 29 | /** Constructor */ 30 | NBPIN(); 31 | 32 | /** Check modem response and restart it 33 | */ 34 | void begin(); 35 | 36 | /** Check if PIN lock or PUK lock is activated 37 | @return 0 if PIN lock is off, 1 if PIN lock is on, -1 if PUK lock is on, -2 if error exists 38 | */ 39 | int isPIN(); 40 | 41 | /** Check if PIN code is correct and valid 42 | @param pin PIN code 43 | @return 0 if is correct, -1 if is incorrect 44 | */ 45 | int checkPIN(String pin); 46 | 47 | /** Check if PUK code is correct and establish new PIN code 48 | @param puk PUK code 49 | @param pin New PIN code 50 | @return 0 if successful, otherwise return -1 51 | */ 52 | int checkPUK(String puk, String pin); 53 | 54 | /** Change PIN code 55 | @param old Old PIN code 56 | @param pin New PIN code 57 | */ 58 | void changePIN(String old, String pin); 59 | 60 | /** Change PIN lock status 61 | @param pin PIN code 62 | */ 63 | void switchPIN(String pin); 64 | 65 | /** Check if modem was registered in NB/GPRS network 66 | @return 0 if modem was registered, 1 if modem was registered in roaming, -1 if error exists 67 | */ 68 | int checkReg(); 69 | 70 | /** Return if PIN lock is used 71 | @return true if PIN lock is used, otherwise, return false 72 | */ 73 | bool getPINUsed(); 74 | 75 | /** Set PIN lock status 76 | @param used New PIN lock status 77 | */ 78 | void setPINUsed(bool used); 79 | 80 | private: 81 | bool _pinUsed; 82 | }; 83 | 84 | #endif 85 | -------------------------------------------------------------------------------- /src/NBSSLClient.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB IoT library. 3 | Copyright (C) 2018 Arduino SA (http://www.arduino.cc/) 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #include "utility/NBRootCerts.h" 21 | 22 | #include "Modem.h" 23 | 24 | #include "NBSSLClient.h" 25 | 26 | enum { 27 | SSL_CLIENT_STATE_LOAD_ROOT_CERT, 28 | SSL_CLIENT_STATE_WAIT_LOAD_ROOT_CERT_RESPONSE, 29 | SSL_CLIENT_STATE_WAIT_DELETE_ROOT_CERT_RESPONSE 30 | }; 31 | 32 | bool NBSSLClient::_defaultRootCertsLoaded = false; 33 | 34 | NBSSLClient::NBSSLClient(bool synch) : 35 | NBClient(synch), 36 | _RCs(NB_ROOT_CERTS), 37 | _numRCs(NB_NUM_ROOT_CERTS), 38 | _customRootCerts(false) 39 | { 40 | } 41 | 42 | NBSSLClient::NBSSLClient(const NBRootCert* myRCs, int myNumRCs, bool synch) : 43 | NBClient(synch), 44 | _RCs(myRCs), 45 | _numRCs(myNumRCs), 46 | _customRootCerts(true), 47 | _customRootCertsLoaded(false) 48 | { 49 | } 50 | 51 | NBSSLClient::~NBSSLClient() 52 | { 53 | } 54 | 55 | int NBSSLClient::ready() 56 | { 57 | if ((!_customRootCerts && _defaultRootCertsLoaded) || 58 | (_customRootCerts && (_numRCs == 0 || _customRootCertsLoaded))) { 59 | // root certs loaded already, continue to regular NBClient 60 | return NBClient::ready(); 61 | } 62 | 63 | int ready = MODEM.ready(); 64 | if (ready == 0) { 65 | // a command is still running 66 | return 0; 67 | } 68 | 69 | switch (_state) { 70 | case SSL_CLIENT_STATE_LOAD_ROOT_CERT: { 71 | if (_RCs[_certIndex].size) { 72 | // load the next root cert 73 | MODEM.sendf("AT+USECMNG=0,0,\"%s\",%d", _RCs[_certIndex].name, _RCs[_certIndex].size); 74 | if (MODEM.waitForPrompt() != 1) { 75 | // failure 76 | ready = -1; 77 | } else { 78 | // send the cert contents 79 | MODEM.write(_RCs[_certIndex].data, _RCs[_certIndex].size); 80 | _state = SSL_CLIENT_STATE_WAIT_LOAD_ROOT_CERT_RESPONSE; 81 | ready = 0; 82 | } 83 | } else { 84 | // remove the next root cert name 85 | MODEM.sendf("AT+USECMNG=2,0,\"%s\"", _RCs[_certIndex].name); 86 | 87 | _state = SSL_CLIENT_STATE_WAIT_DELETE_ROOT_CERT_RESPONSE; 88 | ready = 0; 89 | } 90 | break; 91 | } 92 | 93 | case SSL_CLIENT_STATE_WAIT_LOAD_ROOT_CERT_RESPONSE: { 94 | if (ready > 1) { 95 | // error 96 | } else { 97 | ready = iterateCerts(); 98 | } 99 | break; 100 | } 101 | 102 | case SSL_CLIENT_STATE_WAIT_DELETE_ROOT_CERT_RESPONSE: { 103 | // ignore ready response, root cert might not exist 104 | ready = iterateCerts(); 105 | break; 106 | } 107 | } 108 | 109 | return ready; 110 | } 111 | 112 | int NBSSLClient::connect(IPAddress ip, uint16_t port) 113 | { 114 | _certIndex = 0; 115 | _state = SSL_CLIENT_STATE_LOAD_ROOT_CERT; 116 | 117 | return connectSSL(ip, port); 118 | } 119 | 120 | int NBSSLClient::connect(const char* host, uint16_t port) 121 | { 122 | _certIndex = 0; 123 | _state = SSL_CLIENT_STATE_LOAD_ROOT_CERT; 124 | 125 | return connectSSL(host, port); 126 | } 127 | 128 | int NBSSLClient::iterateCerts() 129 | { 130 | _certIndex++; 131 | if (_certIndex == _numRCs) { 132 | // all certs loaded 133 | if (_customRootCerts) { 134 | _customRootCertsLoaded = true; 135 | } else { 136 | _defaultRootCertsLoaded = true; 137 | } 138 | } else { 139 | // load next 140 | _state = SSL_CLIENT_STATE_LOAD_ROOT_CERT; 141 | } 142 | return 0; 143 | } 144 | -------------------------------------------------------------------------------- /src/NBSSLClient.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB IoT library. 3 | Copyright (C) 2018 Arduino SA (http://www.arduino.cc/) 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #ifndef _NB_SSL_CLIENT_H_INCLUDED 21 | #define _NB_SSL_CLIENT_H_INCLUDED 22 | 23 | #include "NBClient.h" 24 | #include "utility/NBRootCerts.h" 25 | 26 | class NBSSLClient : public NBClient { 27 | 28 | public: 29 | NBSSLClient(bool synch = true); 30 | NBSSLClient(const NBRootCert* myRCs, int myNumRCs, bool synch = true); 31 | virtual ~NBSSLClient(); 32 | 33 | virtual int ready(); 34 | virtual int iterateCerts(); 35 | 36 | virtual int connect(IPAddress ip, uint16_t port); 37 | virtual int connect(const char* host, uint16_t port); 38 | 39 | private: 40 | const NBRootCert* _RCs; 41 | int _numRCs; 42 | static bool _defaultRootCertsLoaded; 43 | bool _customRootCerts; 44 | bool _customRootCertsLoaded; 45 | int _certIndex; 46 | int _state; 47 | }; 48 | 49 | #endif 50 | -------------------------------------------------------------------------------- /src/NBScanner.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB library. 3 | Copyright (C) 2018 Arduino SA (http://www.arduino.cc/) 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #include "Modem.h" 21 | 22 | #include "NBScanner.h" 23 | 24 | NBScanner::NBScanner(bool trace) 25 | { 26 | if (trace) { 27 | MODEM.debug(); 28 | } 29 | } 30 | 31 | NB_NetworkStatus_t NBScanner::begin() 32 | { 33 | MODEM.begin(); 34 | 35 | return IDLE; 36 | } 37 | 38 | String NBScanner::getCurrentCarrier() 39 | { 40 | String response; 41 | 42 | MODEM.send("AT+COPS?"); 43 | if (MODEM.waitForResponse(180000, &response) == 1) { 44 | int firstQuoteIndex = response.indexOf('"'); 45 | int lastQuoteIndex = response.lastIndexOf('"'); 46 | 47 | if (firstQuoteIndex != -1 && lastQuoteIndex != -1 && firstQuoteIndex != lastQuoteIndex) { 48 | return response.substring(firstQuoteIndex + 1, lastQuoteIndex); 49 | } 50 | } 51 | 52 | return ""; 53 | } 54 | 55 | String NBScanner::getSignalStrength() 56 | { 57 | String response; 58 | 59 | MODEM.send("AT+CSQ"); 60 | if (MODEM.waitForResponse(100, &response) == 1) { 61 | int firstSpaceIndex = response.indexOf(' '); 62 | int lastCommaIndex = response.lastIndexOf(','); 63 | 64 | if (firstSpaceIndex != -1 && lastCommaIndex != -1) { 65 | return response.substring(firstSpaceIndex + 1, lastCommaIndex); 66 | } 67 | } 68 | 69 | return ""; 70 | } 71 | 72 | String NBScanner::readNetworks() 73 | { 74 | String response; 75 | 76 | MODEM.send("AT+COPS=?"); 77 | if (MODEM.waitForResponse(180000, &response) == 1) { 78 | String result; 79 | unsigned int responseLength = response.length(); 80 | 81 | for(unsigned int i = 0; i < responseLength; i++) { 82 | for (; i < responseLength; i++) { 83 | if (response[i] == '"') { 84 | result += "> "; 85 | break; 86 | } 87 | } 88 | 89 | for (i++; i < responseLength; i++) { 90 | if (response[i] == '"') { 91 | result += '\n'; 92 | break; 93 | } 94 | 95 | result += response[i]; 96 | } 97 | 98 | for (i++; i < responseLength; i++) { 99 | if (response[i] == ')') { 100 | break; 101 | } 102 | } 103 | } 104 | 105 | return result; 106 | } 107 | 108 | return ""; 109 | } 110 | -------------------------------------------------------------------------------- /src/NBScanner.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB library. 3 | Copyright (C) 2018 Arduino SA (http://www.arduino.cc/) 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #ifndef _NB_SCANNER_H_INCLUDED 21 | #define _NB_SCANNER_H_INCLUDED 22 | 23 | #include "NB.h" 24 | 25 | class NBScanner { 26 | 27 | public: 28 | /** Constructor 29 | @param trace if true, dumps all AT dialogue to Serial 30 | @return - 31 | */ 32 | NBScanner(bool trace = false); 33 | 34 | /** begin (forces modem hardware restart, so we begin from scratch) 35 | @return Always returns IDLE status 36 | */ 37 | NB_NetworkStatus_t begin(); 38 | 39 | /** Read current carrier 40 | @return Current carrier 41 | */ 42 | String getCurrentCarrier(); 43 | 44 | /** Obtain signal strength 45 | @return Signal Strength 46 | */ 47 | String getSignalStrength(); 48 | 49 | /** Search available carriers 50 | @return A string with list of networks available 51 | */ 52 | String readNetworks(); 53 | }; 54 | 55 | #endif 56 | -------------------------------------------------------------------------------- /src/NBUdp.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB library. 3 | Copyright (c) 2018 Arduino SA. All rights reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #include 21 | 22 | #include "NBUdp.h" 23 | 24 | NBUDP::NBUDP() : 25 | _socket(-1), 26 | _packetReceived(false), 27 | _txIp((uint32_t)0), 28 | _txHost(NULL), 29 | _txPort(0), 30 | _txSize(0), 31 | _rxIp((uint32_t)0), 32 | _rxPort(0), 33 | _rxSize(0), 34 | _rxIndex(0) 35 | { 36 | MODEM.addUrcHandler(this); 37 | } 38 | 39 | NBUDP::~NBUDP() 40 | { 41 | MODEM.removeUrcHandler(this); 42 | } 43 | 44 | uint8_t NBUDP::begin(uint16_t port) 45 | { 46 | String response; 47 | 48 | MODEM.send("AT+USOCR=17"); 49 | 50 | if (MODEM.waitForResponse(2000, &response) != 1) { 51 | return 0; 52 | } 53 | 54 | _socket = response.charAt(response.length() - 1) - '0'; 55 | 56 | MODEM.sendf("AT+USOLI=%d,%d", _socket, port); 57 | if (MODEM.waitForResponse(10000) != 1) { 58 | stop(); 59 | return 0; 60 | } 61 | 62 | return 1; 63 | } 64 | 65 | void NBUDP::stop() 66 | { 67 | if (_socket < 0) { 68 | return; 69 | } 70 | 71 | MODEM.sendf("AT+USOCL=%d,1", _socket); 72 | MODEM.waitForResponse(10000); 73 | 74 | _socket = -1; 75 | } 76 | 77 | int NBUDP::beginPacket(IPAddress ip, uint16_t port) 78 | { 79 | if (_socket < 0) { 80 | return 0; 81 | } 82 | 83 | _txIp = ip; 84 | _txHost = NULL; 85 | _txPort = port; 86 | _txSize = 0; 87 | 88 | return 1; 89 | } 90 | 91 | int NBUDP::beginPacket(const char *host, uint16_t port) 92 | { 93 | if (_socket < 0) { 94 | return 0; 95 | } 96 | 97 | _txIp = (uint32_t)0; 98 | _txHost = host; 99 | _txPort = port; 100 | _txSize = 0; 101 | 102 | return 1; 103 | } 104 | 105 | int NBUDP::endPacket() 106 | { 107 | String command; 108 | 109 | if (_txHost != NULL) { 110 | command.reserve(26 + strlen(_txHost) + _txSize * 2); 111 | } else { 112 | command.reserve(41 + _txSize * 2); 113 | } 114 | 115 | command += "AT+USOST="; 116 | command += _socket; 117 | command += ",\""; 118 | 119 | if (_txHost != NULL) { 120 | command += _txHost; 121 | } else { 122 | command += _txIp[0]; 123 | command += '.'; 124 | command += _txIp[1]; 125 | command += '.'; 126 | command += _txIp[2]; 127 | command += '.'; 128 | command += _txIp[3]; 129 | } 130 | 131 | command += "\","; 132 | command += _txPort; 133 | command += ",", 134 | command += _txSize; 135 | command += ",\""; 136 | 137 | for (size_t i = 0; i < _txSize; i++) { 138 | byte b = _txBuffer[i]; 139 | 140 | byte n1 = (b >> 4) & 0x0f; 141 | byte n2 = (b & 0x0f); 142 | 143 | command += (char)(n1 > 9 ? 'A' + n1 - 10 : '0' + n1); 144 | command += (char)(n2 > 9 ? 'A' + n2 - 10 : '0' + n2); 145 | } 146 | 147 | command += "\""; 148 | 149 | MODEM.send(command); 150 | 151 | if (MODEM.waitForResponse() == 1) { 152 | return 1; 153 | } else { 154 | return 0; 155 | } 156 | } 157 | 158 | size_t NBUDP::write(uint8_t b) 159 | { 160 | return write(&b, sizeof(b)); 161 | } 162 | 163 | size_t NBUDP::write(const uint8_t *buffer, size_t size) 164 | { 165 | if (_socket < 0) { 166 | return 0; 167 | } 168 | 169 | size_t spaceAvailable = sizeof(_txBuffer) - _txSize; 170 | 171 | if (size > spaceAvailable) { 172 | size = spaceAvailable; 173 | } 174 | 175 | memcpy(&_txBuffer[_txSize], buffer, size); 176 | _txSize += size; 177 | 178 | return size; 179 | } 180 | 181 | int NBUDP::parsePacket() 182 | { 183 | MODEM.poll(); 184 | 185 | if (_socket < 0) { 186 | return 0; 187 | } 188 | 189 | if (!_packetReceived) { 190 | return 0; 191 | } 192 | _packetReceived = false; 193 | 194 | String response; 195 | 196 | MODEM.sendf("AT+USORF=%d,%d", _socket, sizeof(_rxBuffer)); 197 | if (MODEM.waitForResponse(10000, &response) != 1) { 198 | return 0; 199 | } 200 | 201 | if (!response.startsWith("+USORF: ")) { 202 | return 0; 203 | } 204 | 205 | response.remove(0, 11); 206 | 207 | int firstQuoteIndex = response.indexOf('"'); 208 | if (firstQuoteIndex == -1) { 209 | return 0; 210 | } 211 | 212 | String ip = response.substring(0, firstQuoteIndex); 213 | _rxIp.fromString(ip); 214 | 215 | response.remove(0, firstQuoteIndex + 2); 216 | 217 | int firstCommaIndex = response.indexOf(','); 218 | if (firstCommaIndex == -1) { 219 | return 0; 220 | } 221 | 222 | String port = response.substring(0, firstCommaIndex); 223 | _rxPort = port.toInt(); 224 | firstQuoteIndex = response.indexOf("\""); 225 | 226 | response.remove(0, firstQuoteIndex + 1); 227 | response.remove(response.length() - 1); 228 | 229 | _rxIndex = 0; 230 | _rxSize = response.length() / 2; 231 | 232 | for (size_t i = 0; i < _rxSize; i++) { 233 | byte n1 = response[i * 2]; 234 | byte n2 = response[i * 2 + 1]; 235 | 236 | if (n1 > '9') { 237 | n1 = (n1 - 'A') + 10; 238 | } else { 239 | n1 = (n1 - '0'); 240 | } 241 | 242 | if (n2 > '9') { 243 | n2 = (n2 - 'A') + 10; 244 | } else { 245 | n2 = (n2 - '0'); 246 | } 247 | 248 | _rxBuffer[i] = (n1 << 4) | n2; 249 | } 250 | 251 | MODEM.poll(); 252 | 253 | return _rxSize; 254 | } 255 | 256 | int NBUDP::available() 257 | { 258 | if (_socket < 0) { 259 | return 0; 260 | } 261 | 262 | return (_rxSize - _rxIndex); 263 | } 264 | 265 | int NBUDP::read() 266 | { 267 | byte b; 268 | 269 | if (read(&b, sizeof(b)) == 1) { 270 | return b; 271 | } 272 | 273 | return -1; 274 | } 275 | 276 | int NBUDP::read(unsigned char* buffer, size_t len) 277 | { 278 | size_t readMax = available(); 279 | 280 | if (len > readMax) { 281 | len = readMax; 282 | } 283 | 284 | memcpy(buffer, &_rxBuffer[_rxIndex], len); 285 | 286 | _rxIndex += len; 287 | 288 | return len; 289 | } 290 | 291 | int NBUDP::peek() 292 | { 293 | if (available() > 1) { 294 | return _rxBuffer[_rxIndex]; 295 | } 296 | 297 | return -1; 298 | } 299 | 300 | void NBUDP::flush() 301 | { 302 | } 303 | 304 | IPAddress NBUDP::remoteIP() 305 | { 306 | return _rxIp; 307 | } 308 | 309 | uint16_t NBUDP::remotePort() 310 | { 311 | return _rxPort; 312 | } 313 | 314 | void NBUDP::handleUrc(const String& urc) 315 | { 316 | if (urc.startsWith("+UUSORF: ")) { 317 | int socket = urc.charAt(9) - '0'; 318 | 319 | if (socket == _socket) { 320 | _packetReceived = true; 321 | } 322 | } else if (urc.startsWith("+UUSOCL: ")) { 323 | int socket = urc.charAt(urc.length() - 1) - '0'; 324 | 325 | if (socket == _socket) { 326 | // this socket closed 327 | _socket = -1; 328 | _rxIndex = 0; 329 | _rxSize = 0; 330 | } 331 | } 332 | } 333 | -------------------------------------------------------------------------------- /src/NBUdp.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB library. 3 | Copyright (c) 2018 Arduino SA. All rights reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #ifndef _NB_UDP_H_INCLUDED 21 | #define _NB_UDP_H_INCLUDED 22 | 23 | #include 24 | 25 | #include "Modem.h" 26 | 27 | class NBUDP : public UDP, public ModemUrcHandler { 28 | 29 | public: 30 | NBUDP(); // Constructor 31 | virtual ~NBUDP(); 32 | 33 | virtual uint8_t begin(uint16_t); // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use 34 | virtual void stop(); // Finish with the UDP socket 35 | 36 | // Sending UDP packets 37 | 38 | // Start building up a packet to send to the remote host specific in ip and port 39 | // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port 40 | virtual int beginPacket(IPAddress ip, uint16_t port); 41 | // Start building up a packet to send to the remote host specific in host and port 42 | // Returns 1 if successful, 0 if there was a problem resolving the hostname or port 43 | virtual int beginPacket(const char *host, uint16_t port); 44 | // Finish off this packet and send it 45 | // Returns 1 if the packet was sent successfully, 0 if there was an error 46 | virtual int endPacket(); 47 | // Write a single byte into the packet 48 | virtual size_t write(uint8_t); 49 | // Write size bytes from buffer into the packet 50 | virtual size_t write(const uint8_t *buffer, size_t size); 51 | 52 | using Print::write; 53 | 54 | // Start processing the next available incoming packet 55 | // Returns the size of the packet in bytes, or 0 if no packets are available 56 | virtual int parsePacket(); 57 | // Number of bytes remaining in the current packet 58 | virtual int available(); 59 | // Read a single byte from the current packet 60 | virtual int read(); 61 | // Read up to len bytes from the current packet and place them into buffer 62 | // Returns the number of bytes read, or 0 if none are available 63 | virtual int read(unsigned char* buffer, size_t len); 64 | // Read up to len characters from the current packet and place them into buffer 65 | // Returns the number of characters read, or 0 if none are available 66 | virtual int read(char* buffer, size_t len) { return read((unsigned char*)buffer, len); }; 67 | // Return the next byte from the current packet without moving on to the next byte 68 | virtual int peek(); 69 | virtual void flush(); // Finish reading the current packet 70 | 71 | // Return the IP address of the host who sent the current incoming packet 72 | virtual IPAddress remoteIP(); 73 | // Return the port of the host who sent the current incoming packet 74 | virtual uint16_t remotePort(); 75 | 76 | virtual void handleUrc(const String& urc); 77 | 78 | private: 79 | int _socket; 80 | bool _packetReceived; 81 | 82 | IPAddress _txIp; 83 | const char* _txHost; 84 | uint16_t _txPort; 85 | size_t _txSize; 86 | uint8_t _txBuffer[512]; 87 | 88 | IPAddress _rxIp; 89 | uint16_t _rxPort; 90 | size_t _rxSize; 91 | size_t _rxIndex; 92 | uint8_t _rxBuffer[512]; 93 | }; 94 | 95 | #endif 96 | -------------------------------------------------------------------------------- /src/NB_SMS.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB library. 3 | Copyright (c) 2019 Arduino SA. All rights reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #include "Modem.h" 21 | 22 | #include "NB_SMS.h" 23 | 24 | #define NYBBLETOHEX(x) ((x)<=9?(x)+'0':(x)-10+'A') 25 | #define HEXTONYBBLE(x) ((x)<='9'?(x)-'0':(x)+10-'A') 26 | #define ITOHEX(x) NYBBLETOHEX((x)&0xF) 27 | 28 | enum { 29 | SMS_STATE_IDLE, 30 | SMS_STATE_LIST_MESSAGES, 31 | SMS_STATE_WAIT_LIST_MESSAGES_RESPONSE 32 | }; 33 | 34 | #define SMS_CHARSET_IRA 'I' 35 | #define SMS_CHARSET_GSM 'G' 36 | #define SMS_CHARSET_NONE 'N' 37 | #define SMS_CHARSET_UCS2 'U' 38 | 39 | NB_SMS::NB_SMS(bool synch) : 40 | _synch(synch), 41 | _state(SMS_STATE_IDLE), 42 | _smsTxActive(false), 43 | _charset(SMS_CHARSET_NONE), 44 | _bufferUTF8{0,0,0,0}, 45 | _indexUTF8(0), 46 | _ptrUTF8("") 47 | { 48 | } 49 | 50 | /* Translation tables from GSM_03.38 are equal to UTF-8 for the 51 | * positions 0x0A, 0x0D, 0x1B, 0x20-0x23, 0x25-0x3F, 0x41-0x5A, 0x61-0x7A. 52 | * Collect the others into two translation tables. 53 | * Code uses a simplified range test. */ 54 | 55 | struct gsm_mapping { 56 | const unsigned char gsmc; 57 | const char *utf8; 58 | 59 | gsm_mapping(const char gsmc, const char *utf8) 60 | : gsmc(gsmc), utf8(utf8) {} 61 | }; 62 | 63 | gsm_mapping _gsmUTF8map[] = { 64 | {0x00,"@"},{0x10,"Δ"}, {0x40,"¡"},{0x60,"¿"}, 65 | {0x01,"£"},{0x11,"_"}, 66 | {0x02,"$"},{0x12,"Φ"}, 67 | {0x03,"¥"},{0x13,"Γ"}, 68 | {0x04,"è"},{0x14,"Λ"},{0x24,"¤"}, 69 | {0x05,"é"},{0x15,"Ω"}, 70 | {0x06,"ù"},{0x16,"Π"}, 71 | {0x07,"ì"},{0x17,"Ψ"}, 72 | {0x08,"ò"},{0x18,"Σ"}, 73 | {0x09,"Ç"},{0x19,"Θ"}, 74 | /* Text mode SMS uses 0x1A as send marker so Ξ is not available. */ 75 | //{0x1A,"Ξ"}, 76 | {0x0B,"Ø"}, {0x5B,"Ä"},{0x7B,"ä"}, 77 | {0x0C,"ø"},{0x1C,"Æ"}, {0x5C,"Ö"},{0x7C,"ö"}, 78 | {0x1D,"æ"}, {0x5D,"Ñ"},{0x7D,"ñ"}, 79 | {0x0E,"Å"},{0x1E,"ß"}, {0x5E,"Ü"},{0x7E,"ü"}, 80 | {0x0F,"å"},{0x1F,"É"}, {0x5F,"§"},{0x7F,"à"}}; 81 | 82 | /* Text mode SMS uses 0x1B as abort marker so extended set is not available. */ 83 | #if 0 84 | gsm_mapping _gsmXUTF8map[] = { 85 | {0x40,"|"}, 86 | {0x14,"^"}, 87 | {0x65,"€"}, 88 | {0x28,"{"}, 89 | {0x29,"}"}, 90 | {0x0A,"\f"}, 91 | {0x1B,"\b"}, 92 | {0x3C,"["}, 93 | {0x0D,"\n"},{0x3D,"~"}, 94 | {0x3E,"]"}, 95 | {0x2F,"\\"}}; 96 | */ 97 | #endif 98 | 99 | 100 | int NB_SMS::setCharset(const char* charset) 101 | { 102 | String readcharset(0); 103 | 104 | if ( charset == nullptr ) { 105 | if ( _charset != SMS_CHARSET_NONE ) { 106 | return _charset; 107 | } 108 | } else { 109 | MODEM.sendf("AT+CSCS=\"%s\"", charset); 110 | if (MODEM.waitForResponse() != 1) { 111 | return 0; 112 | } 113 | } 114 | MODEM.sendf("AT+CSCS?"); 115 | if (MODEM.waitForResponse(100,&readcharset) == 1 116 | && readcharset.startsWith("+CSCS: \"")) { 117 | _charset = readcharset[8]; 118 | return _charset; 119 | } 120 | return 0; 121 | } 122 | 123 | 124 | size_t NB_SMS::write(uint8_t c) 125 | { 126 | if (_smsTxActive) { 127 | if (_charset==SMS_CHARSET_GSM 128 | && (c >= 0x80 || c <= 0x24 || (c&0x1F) == 0 || (c&0x1F) >= 0x1B)) { 129 | _bufferUTF8[_indexUTF8++]=c; 130 | if (_bufferUTF8[0] < 0x80 131 | || (_indexUTF8==2 && (_bufferUTF8[0]&0xE0) == 0xC0) 132 | || (_indexUTF8==3 && (_bufferUTF8[0]&0xF0) == 0xE0) 133 | || _indexUTF8==4) { 134 | for (auto &gsmchar : _gsmUTF8map) { 135 | if (strncmp(_bufferUTF8, gsmchar.utf8, _indexUTF8)==0) { 136 | _indexUTF8=0; 137 | return MODEM.write(gsmchar.gsmc); 138 | } 139 | } 140 | // No UTF8 match, echo buffer 141 | for (c=0; c < _indexUTF8; MODEM.write(_bufferUTF8[c++])); 142 | _indexUTF8 = 0; 143 | } 144 | return 1; 145 | } 146 | if (_charset == SMS_CHARSET_UCS2) { 147 | if (c < 0x80) { 148 | MODEM.write('0'); 149 | MODEM.write('0'); 150 | MODEM.write(ITOHEX(c>>4)); 151 | } else { 152 | _bufferUTF8[_indexUTF8++]=c; 153 | if (_indexUTF8==2 && (_bufferUTF8[0]&0xE0) == 0xC0) { 154 | MODEM.write('0'); 155 | MODEM.write(ITOHEX(_bufferUTF8[0]>>2)); 156 | MODEM.write(ITOHEX((_bufferUTF8[0]<<2)|((c>>4)&0x3))); 157 | } else if (_indexUTF8==3 && (_bufferUTF8[0]&0xF0) == 0xE0) { 158 | MODEM.write(ITOHEX(_bufferUTF8[0])); 159 | MODEM.write(ITOHEX(_bufferUTF8[1]>>2)); 160 | MODEM.write(ITOHEX((_bufferUTF8[1]<<2)|((c>>4)&0x3))); 161 | } else if (_indexUTF8==4) { // Missing in UCS2, output SPC 162 | MODEM.write('0'); 163 | MODEM.write('0'); 164 | MODEM.write('2'); 165 | c=0; 166 | } else { 167 | return 1; 168 | } 169 | } 170 | _indexUTF8 = 0; 171 | c = ITOHEX(c); 172 | } 173 | return MODEM.write(c); 174 | } 175 | return 0; 176 | } 177 | 178 | int NB_SMS::beginSMS(const char* to) 179 | { 180 | setCharset(); 181 | for(const char*iptr="AT+CMGS=\"";*iptr!=0;MODEM.write(*iptr++)); 182 | if (_charset==SMS_CHARSET_UCS2 && *to == '+') { 183 | MODEM.write('0'); 184 | MODEM.write('0'); 185 | MODEM.write('2'); 186 | MODEM.write('B'); 187 | to++; 188 | } 189 | while (*to!=0) { 190 | if (_charset==SMS_CHARSET_UCS2) { 191 | MODEM.write('0'); 192 | MODEM.write('0'); 193 | MODEM.write('3'); 194 | } 195 | MODEM.write(*to++); 196 | } 197 | MODEM.send("\""); 198 | if (MODEM.waitForResponse(100) == 2) { 199 | _smsTxActive = false; 200 | 201 | return (_synch) ? 0 : 2; 202 | } 203 | 204 | _indexUTF8 = 0; 205 | _smsTxActive = true; 206 | 207 | return 1; 208 | } 209 | 210 | int NB_SMS::ready() 211 | { 212 | int ready = MODEM.ready(); 213 | 214 | if (ready == 0) { 215 | return 0; 216 | } 217 | 218 | switch(_state) { 219 | case SMS_STATE_IDLE: 220 | default: { 221 | break; 222 | } 223 | 224 | case SMS_STATE_LIST_MESSAGES: { 225 | MODEM.setResponseDataStorage(&_incomingBuffer); 226 | MODEM.send("AT+CMGL=\"REC UNREAD\""); 227 | _state = SMS_STATE_WAIT_LIST_MESSAGES_RESPONSE; 228 | ready = 0; 229 | break; 230 | } 231 | 232 | case SMS_STATE_WAIT_LIST_MESSAGES_RESPONSE: { 233 | _state = SMS_STATE_IDLE; 234 | break; 235 | } 236 | } 237 | 238 | return ready; 239 | } 240 | 241 | int NB_SMS::endSMS() 242 | { 243 | int r; 244 | 245 | if (_smsTxActive) { 246 | // Echo remaining content of UTF8 buffer, empty if no conversion 247 | for (r=0; r < _indexUTF8; MODEM.write(_bufferUTF8[r++])); 248 | _indexUTF8 = 0; 249 | MODEM.write(26); 250 | 251 | if (_synch) { 252 | r = MODEM.waitForResponse(3*60*1000); 253 | } else { 254 | r = MODEM.ready(); 255 | } 256 | 257 | return r; 258 | } else { 259 | return (_synch ? 0 : 2); 260 | } 261 | } 262 | 263 | int NB_SMS::available() 264 | { 265 | int nextMessageIndex = _incomingBuffer.indexOf("+CMGL: "); 266 | 267 | if (nextMessageIndex != -1) { 268 | _incomingBuffer.remove(0, nextMessageIndex); 269 | } else { 270 | _incomingBuffer = ""; 271 | } 272 | 273 | if (_incomingBuffer.length() == 0) { 274 | int r; 275 | 276 | if (_state == SMS_STATE_IDLE) { 277 | setCharset(); 278 | _state = SMS_STATE_LIST_MESSAGES; 279 | } 280 | 281 | if (_synch) { 282 | unsigned long start = millis(); 283 | while ((r = ready()) == 0 && (millis() - start) < 3*60*1000) { 284 | delay(100); 285 | } 286 | } else { 287 | r = ready(); 288 | } 289 | 290 | if (r != 1) { 291 | return 0; 292 | } 293 | } 294 | 295 | if (_incomingBuffer.startsWith("+CMGL: ")) { 296 | 297 | _incomingBuffer.remove(0, 7); 298 | 299 | _smsDataIndex = _incomingBuffer.indexOf('\n') + 1; 300 | 301 | _smsDataEndIndex = _incomingBuffer.indexOf("\r\n+CMGL: ",_smsDataIndex); 302 | if (_smsDataEndIndex == -1) { 303 | _smsDataEndIndex = _incomingBuffer.length() - 1; 304 | } 305 | 306 | return (_smsDataEndIndex - _smsDataIndex) + 1; 307 | } else { 308 | _incomingBuffer = ""; 309 | } 310 | 311 | return 0; 312 | } 313 | 314 | int NB_SMS::remoteNumber(char* number, int nlength) 315 | { 316 | #define PHONE_NUMBER_START_SEARCH_PATTERN "\"REC UNREAD\",\"" 317 | int phoneNumberStartIndex = _incomingBuffer.indexOf(PHONE_NUMBER_START_SEARCH_PATTERN); 318 | 319 | if (phoneNumberStartIndex != -1) { 320 | int i = phoneNumberStartIndex + sizeof(PHONE_NUMBER_START_SEARCH_PATTERN) - 1; 321 | 322 | if (_charset==SMS_CHARSET_UCS2 && _incomingBuffer.substring(i,i+4)=="002B") { 323 | *number++ = '+'; 324 | i += 4; 325 | } 326 | while (i < (int)_incomingBuffer.length() && nlength > 1) { 327 | if (_charset==SMS_CHARSET_UCS2) { 328 | i += 3; 329 | } 330 | char c = _incomingBuffer[i]; 331 | 332 | if (c == '"') { 333 | break; 334 | } 335 | 336 | *number++ = c; 337 | nlength--; 338 | i++; 339 | } 340 | 341 | *number = '\0'; 342 | return 1; 343 | } else { 344 | *number = '\0'; 345 | } 346 | 347 | return 2; 348 | } 349 | 350 | int NB_SMS::read() 351 | { 352 | if (*_ptrUTF8 != 0) { 353 | return *_ptrUTF8++; 354 | } 355 | if (_smsDataIndex < (signed)_incomingBuffer.length() && _smsDataIndex <= _smsDataEndIndex) { 356 | char c; 357 | if (_charset != SMS_CHARSET_UCS2) { 358 | c = _incomingBuffer[_smsDataIndex++]; 359 | if (_charset == SMS_CHARSET_GSM 360 | && (c >= 0x80 || c <= 0x24 || (c&0x1F) == 0 || (c&0x1F) >= 0x1B)) { 361 | for (auto &gsmchar : _gsmUTF8map) { 362 | if (c == gsmchar.gsmc) { 363 | _ptrUTF8 = gsmchar.utf8; 364 | return *_ptrUTF8++; 365 | } 366 | } 367 | } 368 | } else { 369 | c = (HEXTONYBBLE(_incomingBuffer[_smsDataIndex+2])<<4) 370 | | HEXTONYBBLE(_incomingBuffer[_smsDataIndex+3]); 371 | if (strncmp(&_incomingBuffer[_smsDataIndex],"008",3)>=0) { 372 | _ptrUTF8 = _bufferUTF8+1; 373 | _bufferUTF8[2] = 0; 374 | _bufferUTF8[1] = (c&0x3F)|0x80; 375 | c = 0xC0 | (HEXTONYBBLE(_incomingBuffer[_smsDataIndex+1])<<2) 376 | | (HEXTONYBBLE(_incomingBuffer[_smsDataIndex+2])>>2); 377 | if (strncmp(&_incomingBuffer[_smsDataIndex],"08",2)>=0) { 378 | _ptrUTF8 = _bufferUTF8; 379 | _bufferUTF8[0] = c & (0x80|0x3F); 380 | c = 0xE0 | HEXTONYBBLE(_incomingBuffer[_smsDataIndex]); 381 | } 382 | } 383 | _smsDataIndex += 4; 384 | } 385 | return c; 386 | } 387 | 388 | return -1; 389 | } 390 | 391 | int NB_SMS::peek() 392 | { 393 | if (*_ptrUTF8 != 0) { 394 | return *_ptrUTF8; 395 | } 396 | if (_smsDataIndex < (signed)_incomingBuffer.length() && _smsDataIndex <= _smsDataEndIndex) { 397 | char c = _incomingBuffer[_smsDataIndex+1]; 398 | if (_charset == SMS_CHARSET_GSM 399 | && (c >= 0x80 || c <= 0x24 || (c&0x1F) == 0 || (c&0x1F) >= 0x1B)) { 400 | for (auto &gsmchar : _gsmUTF8map) { 401 | if (c == gsmchar.gsmc) { 402 | return gsmchar.utf8[0]; 403 | } 404 | } 405 | } 406 | if (_charset == SMS_CHARSET_UCS2) { 407 | c = (HEXTONYBBLE(_incomingBuffer[_smsDataIndex+2])<<4) 408 | | HEXTONYBBLE(_incomingBuffer[_smsDataIndex+3]); 409 | if (strncmp(&_incomingBuffer[_smsDataIndex],"008",3)>=0) { 410 | c = 0xC0 | (HEXTONYBBLE(_incomingBuffer[_smsDataIndex+1])<<2) 411 | | (HEXTONYBBLE(_incomingBuffer[_smsDataIndex+2])>>2); 412 | if (strncmp(&_incomingBuffer[_smsDataIndex],"08",2)>=0) { 413 | c = 0xE0 | HEXTONYBBLE(_incomingBuffer[_smsDataIndex]); 414 | } 415 | } 416 | } 417 | return c; 418 | } 419 | 420 | return -1; 421 | } 422 | 423 | void NB_SMS::flush() 424 | { 425 | int smsIndexEnd = _incomingBuffer.indexOf(','); 426 | 427 | _ptrUTF8 = ""; 428 | if (smsIndexEnd != -1) { 429 | while (MODEM.ready() == 0); 430 | 431 | MODEM.sendf("AT+CMGD=%s", _incomingBuffer.substring(0, smsIndexEnd).c_str()); 432 | 433 | if (_synch) { 434 | MODEM.waitForResponse(55000); 435 | } 436 | } 437 | } 438 | 439 | void NB_SMS::clear(int flag) 440 | { 441 | _ptrUTF8 = ""; 442 | 443 | while (MODEM.ready() == 0); 444 | 445 | if (flag<1 || flag>4) flag = 2; 446 | 447 | MODEM.sendf("AT+CMGD=0,%d",flag); 448 | 449 | if (_synch) { 450 | MODEM.waitForResponse(55000); 451 | } 452 | } 453 | -------------------------------------------------------------------------------- /src/NB_SMS.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB library. 3 | Copyright (c) 2019 Arduino SA. All rights reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #ifndef _NB_SMS_H_INCLUDED 21 | #define _NB_SMS_H_INCLUDED 22 | 23 | #include 24 | 25 | #define NB_SMS_CLEAR_READ (1) 26 | #define NB_SMS_CLEAR_READ_SENT (2) 27 | #define NB_SMS_CLEAR_READ_SENT_UNSENT (3) 28 | #define NB_SMS_CLEAR_ALL (4) 29 | 30 | class NB_SMS : public Stream { 31 | 32 | public: 33 | /** Constructor 34 | @param synch Determines sync mode 35 | */ 36 | NB_SMS(bool synch = true); 37 | 38 | /** Write a character in SMS message 39 | @param c Character 40 | @return size 41 | */ 42 | size_t write(uint8_t c); 43 | 44 | /** Select SMS charset 45 | @param charset Character set, one of "IRA" (default), "GSM", or "UCS2", reads from modem if null. 46 | @return returns first char of charset identifier on success and 0 on error 47 | */ 48 | int setCharset(const char* charset = nullptr); 49 | 50 | /** Begin a SMS to send it 51 | @param to Destination 52 | @return error command if it exists 53 | */ 54 | int beginSMS(const char* to); 55 | 56 | /** Get last command status 57 | @return returns 0 if last command is still executing, 1 success, >1 error 58 | */ 59 | int ready(); 60 | 61 | /** End SMS 62 | @return error command if it exists 63 | */ 64 | int endSMS(); 65 | 66 | /** Check if SMS available and prepare it to be read 67 | @return number of bytes in a received SMS 68 | */ 69 | int available(); 70 | 71 | /** Read sender number phone 72 | @param number Buffer for save number phone 73 | @param nlength Buffer length 74 | @return 1 success, >1 error 75 | */ 76 | int remoteNumber(char* number, int nlength); 77 | 78 | /** Read one char for SMS buffer (advance circular buffer) 79 | @return byte 80 | */ 81 | int read(); 82 | 83 | /** Read a byte but do not advance the buffer header (circular buffer) 84 | @return byte 85 | */ 86 | int peek(); 87 | 88 | /** Delete the SMS from Modem memory and process answer 89 | */ 90 | void flush(); 91 | 92 | /** Delete all read and sent SMS from Modem memory and process answer 93 | */ 94 | void clear(int flag = NB_SMS_CLEAR_READ_SENT); 95 | 96 | private: 97 | bool _synch; 98 | int _state; 99 | String _incomingBuffer; 100 | int _smsDataIndex; 101 | int _smsDataEndIndex; 102 | bool _smsTxActive; 103 | int _charset; 104 | char _bufferUTF8[4]; 105 | int _indexUTF8; 106 | const char* _ptrUTF8; 107 | }; 108 | 109 | #endif 110 | -------------------------------------------------------------------------------- /src/utility/NBSocketBuffer.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB library. 3 | Copyright (c) 2018 Arduino SA. All rights reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #include 21 | #include 22 | 23 | #include "Modem.h" 24 | 25 | #include "NBSocketBuffer.h" 26 | 27 | #define NB_SOCKET_NUM_BUFFERS (sizeof(_buffers) / sizeof(_buffers[0])) 28 | 29 | #define NB_SOCKET_BUFFER_SIZE 512 30 | 31 | NBSocketBufferClass::NBSocketBufferClass() 32 | { 33 | memset(&_buffers, 0x00, sizeof(_buffers)); 34 | } 35 | 36 | NBSocketBufferClass::~NBSocketBufferClass() 37 | { 38 | for (unsigned int i = 0; i < NB_SOCKET_NUM_BUFFERS; i++) { 39 | close(i); 40 | } 41 | } 42 | 43 | void NBSocketBufferClass::close(int socket) 44 | { 45 | if (_buffers[socket].data) { 46 | free(_buffers[socket].data); 47 | _buffers[socket].data = _buffers[socket].head = NULL; 48 | _buffers[socket].length = 0; 49 | } 50 | } 51 | 52 | int NBSocketBufferClass::available(int socket) 53 | { 54 | if (_buffers[socket].length == 0) { 55 | if (_buffers[socket].data == NULL) { 56 | _buffers[socket].data = _buffers[socket].head = (uint8_t*)malloc(NB_SOCKET_BUFFER_SIZE); 57 | _buffers[socket].length = 0; 58 | } 59 | 60 | String response; 61 | 62 | MODEM.sendf("AT+USORD=%d,%d", socket, NB_SOCKET_BUFFER_SIZE); 63 | int status = MODEM.waitForResponse(10000, &response); 64 | if (status != 1) { 65 | if (status == 2) { 66 | return -1; 67 | } else if (status == 4 && response.indexOf("Operation not allowed") != -1 ) { 68 | return -1; 69 | } else { 70 | return 0; 71 | } 72 | } 73 | 74 | if (!response.startsWith("+USORD: ")) { 75 | return 0; 76 | } 77 | 78 | int firstQuoteIndex = response.indexOf("\""); 79 | 80 | response.remove(0, firstQuoteIndex + 1); 81 | response.remove(response.length() - 1); 82 | 83 | size_t size = response.length() / 2; 84 | 85 | for (size_t i = 0; i < size; i++) { 86 | byte n1 = response[i * 2]; 87 | byte n2 = response[i * 2 + 1]; 88 | 89 | if (n1 > '9') { 90 | n1 = (n1 - 'A') + 10; 91 | } else { 92 | n1 = (n1 - '0'); 93 | } 94 | 95 | if (n2 > '9') { 96 | n2 = (n2 - 'A') + 10; 97 | } else { 98 | n2 = (n2 - '0'); 99 | } 100 | 101 | _buffers[socket].data[i] = (n1 << 4) | n2; 102 | } 103 | 104 | _buffers[socket].head = _buffers[socket].data; 105 | _buffers[socket].length = size; 106 | } 107 | 108 | return _buffers[socket].length; 109 | } 110 | 111 | int NBSocketBufferClass::peek(int socket) 112 | { 113 | if (!available(socket)) { 114 | return -1; 115 | } 116 | 117 | return *_buffers[socket].head; 118 | } 119 | 120 | int NBSocketBufferClass::read(int socket, uint8_t* data, size_t length) 121 | { 122 | int avail = available(socket); 123 | 124 | if (!avail) { 125 | return 0; 126 | } 127 | 128 | if (avail < (int)length) { 129 | length = avail; 130 | } 131 | 132 | memcpy(data, _buffers[socket].head, length); 133 | _buffers[socket].head += length; 134 | _buffers[socket].length -= length; 135 | 136 | return length; 137 | } 138 | 139 | NBSocketBufferClass NBSocketBuffer; 140 | -------------------------------------------------------------------------------- /src/utility/NBSocketBuffer.h: -------------------------------------------------------------------------------- 1 | /* 2 | This file is part of the MKR NB library. 3 | Copyright (c) 2018 Arduino SA. All rights reserved. 4 | 5 | This library is free software; you can redistribute it and/or 6 | modify it under the terms of the GNU Lesser General Public 7 | License as published by the Free Software Foundation; either 8 | version 2.1 of the License, or (at your option) any later version. 9 | 10 | This library is distributed in the hope that it will be useful, 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | Lesser General Public License for more details. 14 | 15 | You should have received a copy of the GNU Lesser General Public 16 | License along with this library; if not, write to the Free Software 17 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 18 | */ 19 | 20 | #ifndef _NBSOCKET_BUFFER_H_INCLUDED 21 | #define _NBSOCKET_BUFFER_H_INCLUDED 22 | 23 | class NBSocketBufferClass { 24 | 25 | public: 26 | public: 27 | NBSocketBufferClass(); 28 | virtual ~NBSocketBufferClass(); 29 | 30 | void close(int socket); 31 | 32 | int available(int socket); 33 | int peek(int socket); 34 | int read(int socket, uint8_t* data, size_t length); 35 | 36 | private: 37 | struct { 38 | uint8_t* data; 39 | uint8_t* head; 40 | int length; 41 | } _buffers[7]; 42 | }; 43 | 44 | extern NBSocketBufferClass NBSocketBuffer; 45 | 46 | #endif 47 | --------------------------------------------------------------------------------