├── .github
├── .cSpellWords.txt
├── pull-request-template.md
└── workflows
│ ├── ci.yml
│ ├── doxygen.yml
│ └── release.yml
├── .gitignore
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE.md
├── README.md
├── SECURITY.md
├── cspell.config.yaml
├── docs
└── doxygen
│ ├── config.doxyfile
│ ├── layout.xml
│ ├── pages.dox
│ └── style.css
├── include
├── iot_adc.h
├── iot_battery.h
├── iot_efuse.h
├── iot_flash.h
├── iot_gpio.h
├── iot_hw.h
├── iot_i2c.h
├── iot_i2s.h
├── iot_perfcounter.h
├── iot_power.h
├── iot_pwm.h
├── iot_reset.h
├── iot_rtc.h
├── iot_sdio.h
├── iot_spi.h
├── iot_timer.h
├── iot_tsensor.h
├── iot_uart.h
├── iot_usb_device.h
├── iot_usb_host.h
└── iot_watchdog.h
├── manifest.yml
└── test
├── .DS_Store
├── iot_test_common_io.c
├── iot_test_common_io_internal.h
├── test_iot_adc.c
├── test_iot_battery.c
├── test_iot_efuse.c
├── test_iot_flash.c
├── test_iot_gpio.c
├── test_iot_i2c.c
├── test_iot_i2s.c
├── test_iot_perfcounter.c
├── test_iot_power.c
├── test_iot_pwm.c
├── test_iot_reset.c
├── test_iot_rtc.c
├── test_iot_sdio.c
├── test_iot_spi.c
├── test_iot_timer.c
├── test_iot_tsensor.c
├── test_iot_uart.c
├── test_iot_watchdog.c
└── test_scripts
├── .DS_Store
├── adc
├── __init__.py
├── test_iot_adc_rp3.py
├── test_iot_adc_test.py
└── test_iot_runonPI_adc.sh
├── gpio
├── __init__.py
├── test_iot_gpio_rp3.py
├── test_iot_gpio_test.py
└── test_iot_runonPI_gpio.sh
├── i2c_master
├── test_iot_i2c_master_rp3.py
├── test_iot_i2c_master_test.py
└── test_iot_runonPI_i2c_master.sh
├── pwm
├── __init__.py
├── test_iot_pwm_rp3.py
├── test_iot_pwm_test.py
└── test_iot_runonPI_pwm.sh
├── spi_master
├── test_iot_spi_master_pyb.sh
└── test_iot_spi_master_test.py
├── test_iot_assisted_tests.py
├── test_iot_test_template.py
├── tsensor
├── __init__.py
├── test_iot_runonPI_tsensor.sh
├── test_iot_tsensor_rp3.py
└── test_iot_tsensor_test.py
├── uart
├── __init__.py
├── test_iot_runonPI_uart.sh
├── test_iot_uart_rp3.py
└── test_iot_uart_test.py
└── usb_device
└── test_iot_usb_device_test.py
/.github/.cSpellWords.txt:
--------------------------------------------------------------------------------
1 | AFQP
2 | AFWP
3 | CCCR
4 | CPHA
5 | Cntx
6 | EFUSE
7 | EHCI
8 | Efuse
9 | GPIO
10 | GPIOs
11 | Gpio
12 | MOSI
13 | OHCI
14 | Pmic
15 | Rxbuf
16 | SDIO
17 | SDMMC
18 | Sdio
19 | Spkr
20 | TSENSOR
21 | Txbuf
22 | UHCI
23 | Vddcore
24 | Wdog
25 | XHCI
26 | bstraction
27 | btest
28 | deinitializes
29 | efunc
30 | efuse
31 | etest
32 | gpio
33 | ltest
34 | nvic
35 | puctest
36 | tsensor
37 | uctest
38 | unstall
39 | ustest
40 | xget
41 | xtest
42 |
--------------------------------------------------------------------------------
/.github/pull-request-template.md:
--------------------------------------------------------------------------------
1 | Description
2 | -----------
3 |
4 |
5 | Test Steps
6 | -----------
7 |
8 |
9 | Checklist:
10 | ----------
11 |
12 |
13 | - [ ] I have tested my changes. No regression in existing tests.
14 | - [ ] I have modified and/or added unit-tests to cover the code changes in this Pull Request.
15 |
16 | Related Issue
17 | -----------
18 |
19 |
20 | By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI Checks
2 |
3 | on:
4 | push:
5 | branches: ["**"]
6 | pull_request:
7 | branches: [main]
8 | workflow_dispatch:
9 |
10 | jobs:
11 | doxygen:
12 | runs-on: ubuntu-latest
13 | steps:
14 | - uses: actions/checkout@v3
15 | - name: Run doxygen build
16 | uses: FreeRTOS/CI-CD-Github-Actions/doxygen@main
17 | with:
18 | path: ./
19 |
20 | spell-check:
21 | runs-on: ubuntu-latest
22 | steps:
23 | - name: Clone repository
24 | uses: actions/checkout@v3
25 | - name: Run spellings check
26 | uses: FreeRTOS/CI-CD-Github-Actions/spellings@main
27 | with:
28 | path: ./
29 |
30 | formatting:
31 | runs-on: ubuntu-latest
32 | steps:
33 | - uses: actions/checkout@v3
34 | - name: Check formatting
35 | uses: FreeRTOS/CI-CD-Github-Actions/formatting@main
36 | with:
37 | path: ./
38 |
39 | link-verifier:
40 | runs-on: ubuntu-latest
41 | steps:
42 | - name: Clone This Repo
43 | uses: actions/checkout@v3
44 | - name: Link Verification
45 | uses: FreeRTOS/CI-CD-Github-Actions/link-verifier@v2
46 |
47 | git-secrets:
48 | runs-on: ubuntu-latest
49 | steps:
50 | - uses: actions/checkout@v3
51 | - name: Checkout awslabs/git-secrets
52 | uses: actions/checkout@v3
53 | with:
54 | repository: awslabs/git-secrets
55 | ref: master
56 | path: git-secrets
57 | - name: Install git-secrets
58 | run: cd git-secrets && sudo make install && cd ..
59 | - name: Run git-secrets
60 | run: |
61 | git-secrets --register-aws
62 | git-secrets --scan
63 |
--------------------------------------------------------------------------------
/.github/workflows/doxygen.yml:
--------------------------------------------------------------------------------
1 | name: Doxygen Generation
2 | on:
3 | push:
4 | branches: [main]
5 | workflow_dispatch:
6 | jobs:
7 | doxygen-generation:
8 | runs-on: ubuntu-latest
9 | steps:
10 | - name: Doxygen generation
11 | uses: FreeRTOS/CI-CD-Github-Actions/doxygen-generation@main
12 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | name: Release automation
2 |
3 | on:
4 | workflow_dispatch:
5 | inputs:
6 | commit_id:
7 | description: 'Commit ID to tag and create a release for'
8 | required: true
9 | version_number:
10 | description: 'Release Version Number (Eg, v1.0.0)'
11 | required: true
12 | delete_existing_tag_release:
13 | description: 'Is this a re-release of existing tag/release? (Default: false)'
14 | default: 'false'
15 | required: false
16 | jobs:
17 | clean-existing-tag-and-release:
18 | if: ${{ github.event.inputs.delete_existing_tag_release == 'true' }}
19 | runs-on: ubuntu-latest
20 | env:
21 | VERSION_NUM: ${{ github.event.inputs.version_number }}
22 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
23 | steps:
24 | - name: Checkout code
25 | uses: actions/checkout@v3
26 | - name: Check if tag exists
27 | run: |
28 | git fetch origin
29 | if git tag --list $VERSION_NUM
30 | then
31 | echo "Deleting existing tag for $VERSION_NUM"
32 | git push origin --delete tags/$VERSION_NUM
33 | fi
34 | - name: Check if release exists
35 | run: |
36 | sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-key 23F3D4EA75716059
37 | sudo apt-add-repository https://cli.github.com/packages
38 | sudo apt update
39 | sudo apt-get install gh
40 | if gh release list | grep $VERSION_NUM
41 | then
42 | echo "Deleting existing release for $VERSION_NUM"
43 | gh release delete --yes $VERSION_NUM
44 | fi
45 | add-sbom-and-tag-commit:
46 | if: ${{ ( github.event.inputs.delete_existing_tag_release == 'true' && success() ) || ( github.event.inputs.delete_existing_tag_release == 'false' && always() ) }}
47 | needs: clean-existing-tag-and-release
48 | name: Tag commit
49 | runs-on: ubuntu-latest
50 | steps:
51 | - name: Checkout code
52 | uses: actions/checkout@v3
53 | with:
54 | ref: ${{ github.event.inputs.commit_id }}
55 | - name: Configure git identity
56 | run: |
57 | git config --global user.name ${{ github.actor }}
58 | git config --global user.email ${{ github.actor }}@users.noreply.github.com
59 | - name: create a new branch that references commit id
60 | run: git checkout -b ${{ github.event.inputs.version_number }} ${{ github.event.inputs.commit_id }}
61 | - name: Generate SBOM
62 | uses: FreeRTOS/CI-CD-Github-Actions/sbom-generator@main
63 | with:
64 | repo_path: ./
65 | source_path: ./source
66 | - name: commit SBOM file
67 | run: |
68 | git add .
69 | git commit -m 'Update SBOM'
70 | git push -u origin ${{ github.event.inputs.version_number }}
71 | - name: Tag Commit and Push to remote
72 | run: |
73 | git tag ${{ github.event.inputs.version_number }} -a -m "coreMQTT Library ${{ github.event.inputs.version_number }}"
74 | git push origin --tags
75 | - name: Verify tag on remote
76 | run: |
77 | git tag -d ${{ github.event.inputs.version_number }}
78 | git remote update
79 | git checkout tags/${{ github.event.inputs.version_number }}
80 | git diff ${{ github.event.inputs.commit_id }} tags/${{ github.event.inputs.version_number }}
81 | create-zip:
82 | if: ${{ ( github.event.inputs.delete_existing_tag_release == 'true' && success() ) || ( github.event.inputs.delete_existing_tag_release == 'false' && always() ) }}
83 | needs: add-sbom-and-tag-commit
84 | name: Create ZIP and verify package for release asset.
85 | runs-on: ubuntu-latest
86 | steps:
87 | - name: Install ZIP tools
88 | run: sudo apt-get install zip unzip
89 | - name: Checkout code
90 | uses: actions/checkout@v3
91 | with:
92 | ref: ${{ github.event.inputs.commit_id }}
93 | path: common-io-basic
94 | submodules: recursive
95 | - name: Checkout disabled submodules
96 | run: |
97 | cd common-io-basic
98 | git submodule update --init --checkout --recursive
99 | - name: Create ZIP
100 | run: |
101 | zip -r common-io-basic-${{ github.event.inputs.version_number }}.zip common-io-basic -x "*.git*"
102 | ls ./
103 | - name: Validate created ZIP
104 | run: |
105 | mkdir zip-check
106 | mv common-io-basic-${{ github.event.inputs.version_number }}.zip zip-check
107 | cd zip-check
108 | unzip common-io-basic-${{ github.event.inputs.version_number }}.zip -d common-io-basic-${{ github.event.inputs.version_number }}
109 | ls common-io-basic-${{ github.event.inputs.version_number }}
110 | diff -r -x "*.git*" common-io-basic-${{ github.event.inputs.version_number }}/common-io-basic/ ../common-io-basic/
111 | cd ../
112 | # - name: Build
113 | # run: |
114 | # cd zip-check/common-io-basic-${{ github.event.inputs.version_number }}/common-io-basic
115 | # sudo apt-get install -y lcov
116 | # cmake -S test -B build/ \
117 | # -G "Unix Makefiles" \
118 | # -DCMAKE_BUILD_TYPE=Debug \
119 | # -DBUILD_CLONE_SUBMODULES=ON \
120 | # -DCMAKE_C_FLAGS='--coverage -Wall -Wextra -Werror -DNDEBUG'
121 | # make -C build/ all
122 | # - name: Test
123 | # run: |
124 | # cd zip-check/common-io-basic-${{ github.event.inputs.version_number }}/common-io-basic/build/
125 | # ctest -E system --output-on-failure
126 | # cd ..
127 | - name: Create artifact of ZIP
128 | uses: actions/upload-artifact@v2
129 | with:
130 | name: common-io-basic-${{ github.event.inputs.version_number }}.zip
131 | path: zip-check/common-io-basic-${{ github.event.inputs.version_number }}.zip
132 | deploy-doxygen:
133 | needs: add-sbom-and-tag-commit
134 | if: ${{ ( github.event.inputs.delete_existing_tag_release == 'true' && success() ) || ( github.event.inputs.delete_existing_tag_release == 'false' && always() ) }}
135 | name: Deploy doxygen documentation
136 | runs-on: ubuntu-latest
137 | steps:
138 | - name: Doxygen generation
139 | uses: FreeRTOS/CI-CD-Github-Actions/doxygen-generation@main
140 | with:
141 | ref: ${{ github.event.inputs.version_number }}
142 | add_release: "true"
143 | create-release:
144 | needs:
145 | - create-zip
146 | - deploy-doxygen
147 | if: ${{ ( github.event.inputs.delete_existing_tag_release == 'true' && success() ) || ( github.event.inputs.delete_existing_tag_release == 'false' && always() ) }}
148 | name: Create Release and Upload Release Asset
149 | runs-on: ubuntu-latest
150 | steps:
151 | - name: Create Release
152 | id: create_release
153 | uses: actions/create-release@v1
154 | env:
155 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
156 | with:
157 | tag_name: ${{ github.event.inputs.version_number }}
158 | release_name: ${{ github.event.inputs.version_number }}
159 | body: Release ${{ github.event.inputs.version_number }} of the Common IO - basic Library.
160 | draft: false
161 | prerelease: false
162 | - name: Download ZIP artifact
163 | uses: actions/download-artifact@v2
164 | with:
165 | name: common-io-basic-${{ github.event.inputs.version_number }}.zip
166 | - name: Upload Release Asset
167 | id: upload-release-asset
168 | uses: actions/upload-release-asset@v1
169 | env:
170 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
171 | with:
172 | upload_url: ${{ steps.create_release.outputs.upload_url }}
173 | asset_path: ./common-io-basic-${{ github.event.inputs.version_number }}.zip
174 | asset_name: common-io-basic-${{ github.event.inputs.version_number }}.zip
175 | asset_content_type: application/zip
176 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # local doxygen generation
2 | docs/doxygen/output/
3 |
4 | # VS Code ignores
5 | .vscode/
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | ## Code of Conduct
2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
4 | opensource-codeofconduct@amazon.com with any additional questions or comments.
5 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing Guidelines
2 |
3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional
4 | documentation, we greatly value feedback and contributions from our community.
5 |
6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary
7 | information to effectively respond to your bug report or contribution.
8 |
9 |
10 | ## Reporting Bugs/Feature Requests
11 |
12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features.
13 |
14 | When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already
15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful:
16 |
17 | * A reproducible test case or series of steps
18 | * The version of our code being used
19 | * Any modifications you've made relevant to the bug
20 | * Anything unusual about your environment or deployment
21 |
22 |
23 | ## Contributing via Pull Requests
24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that:
25 |
26 | 1. You are working against the latest source on the *main* branch.
27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already.
28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted.
29 |
30 | To send us a pull request, please:
31 |
32 | 1. Fork the repository.
33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change.
34 | 3. Ensure local tests pass.
35 | 4. Commit to your fork using clear commit messages.
36 | 5. Send us a pull request, answering any default questions in the pull request interface.
37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation.
38 |
39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and
40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/).
41 |
42 |
43 | ## Finding contributions to work on
44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start.
45 |
46 |
47 | ## Code of Conduct
48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
50 | opensource-codeofconduct@amazon.com with any additional questions or comments.
51 |
52 |
53 | ## Security issue notifications
54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue.
55 |
56 |
57 | ## Licensing
58 |
59 | See the [LICENSE](LICENSE.md) file for our project's licensing. We will ask you to confirm the licensing of your contribution.
60 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy
4 | of this software and associated documentation files (the "Software"), to deal
5 | in the Software without restriction, including without limitation the rights
6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | copies of the Software, and to permit persons to whom the Software is
8 | furnished to do so, subject to the following conditions:
9 |
10 | The above copyright notice and this permission notice shall be included in all
11 | copies or substantial portions of the Software.
12 |
13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 | SOFTWARE.
20 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## Common IO - basic
2 |
3 | This repository provides a basic set of I/O libraries (**HAL**, **H**ardware **A**bstraction **L**ayer) for pins and serial communications on embedded devices.
4 |
5 | ## Security
6 |
7 | See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information.
8 |
9 | ## License
10 |
11 | This library is licensed under the MIT License. See [LICENSE](LICENSE.md) for the license body.
12 |
--------------------------------------------------------------------------------
/SECURITY.md:
--------------------------------------------------------------------------------
1 | ## Reporting a Vulnerability
2 |
3 | If you discover a potential security issue in this project, we ask that you notify AWS/Amazon Security
4 | via our [vulnerability reporting page](https://aws.amazon.com/security/vulnerability-reporting/) or directly via email to aws-security@amazon.com.
5 | Please do **not** create a public github issue.
6 |
--------------------------------------------------------------------------------
/cspell.config.yaml:
--------------------------------------------------------------------------------
1 | ---
2 | $schema: https://raw.githubusercontent.com/streetsidesoftware/cspell/main/cspell.schema.json
3 | version: '0.2'
4 | # Allows things like stringLength
5 | allowCompoundWords: true
6 |
7 | # Read files not to spell check from the git ignore
8 | useGitignore: true
9 |
10 | # Language settings for C
11 | languageSettings:
12 | - caseSensitive: false
13 | enabled: true
14 | languageId: c
15 | locale: "*"
16 |
17 | # Add a dictionary, and the path to the word list
18 | dictionaryDefinitions:
19 | - name: freertos-words
20 | path: '.github/.cSpellWords.txt'
21 | addWords: true
22 |
23 | dictionaries:
24 | - freertos-words
25 |
26 | # Paths and files to ignore
27 | ignorePaths:
28 | - 'docs'
29 |
--------------------------------------------------------------------------------
/docs/doxygen/layout.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 |
189 |
190 |
191 |
192 |
193 |
194 |
195 |
196 |
197 |
198 |
199 |
200 |
201 |
202 |
203 |
204 |
205 |
206 |
207 |
208 |
209 |
210 |
211 |
212 |
213 |
214 |
215 |
216 |
217 |
218 |
219 |
220 |
221 |
222 |
223 |
224 |
225 |
226 |
227 |
228 |
229 |
--------------------------------------------------------------------------------
/docs/doxygen/pages.dox:
--------------------------------------------------------------------------------
1 | /**
2 | @mainpage Overview
3 | @anchor common-io-basic
4 | @brief Common IO - basic v1.0.0 Library
5 |
6 | > AWS Common IO - basic library
7 |
8 | */
9 |
--------------------------------------------------------------------------------
/docs/doxygen/style.css:
--------------------------------------------------------------------------------
1 | /*
2 | * Stylesheet for Doxygen HTML output.
3 | *
4 | * This file defines styles for custom elements in the header/footer and
5 | * overrides some of the default Doxygen styles.
6 | *
7 | * Styles in this file do not affect the treeview sidebar.
8 | */
9 |
10 | /* Set the margins to place a small amount of whitespace on the left and right
11 | * side of the page. */
12 | div.contents {
13 | margin-left:4em;
14 | margin-right:4em;
15 | }
16 |
17 | /* Justify text in paragraphs. */
18 | p {
19 | text-align: justify;
20 | }
21 |
22 | /* Style of section headings. */
23 | h1 {
24 | border-bottom: 1px solid #879ECB;
25 | color: #354C7B;
26 | font-size: 160%;
27 | font-weight: normal;
28 | padding-bottom: 4px;
29 | padding-top: 8px;
30 | }
31 |
32 | /* Style of subsection headings. */
33 | h2:not(.memtitle):not(.groupheader) {
34 | font-size: 125%;
35 | margin-bottom: 0px;
36 | margin-top: 16px;
37 | padding: 0px;
38 | }
39 |
40 | /* Style of paragraphs immediately after subsection headings. */
41 | h2 + p {
42 | margin: 0px;
43 | padding: 0px;
44 | }
45 |
46 | /* Style of subsection headings. */
47 | h3 {
48 | font-size: 100%;
49 | margin-bottom: 0px;
50 | margin-left: 2em;
51 | margin-right: 2em;
52 | }
53 |
54 | /* Style of paragraphs immediately after subsubsection headings. */
55 | h3 + p {
56 | margin-top: 0px;
57 | margin-left: 2em;
58 | margin-right: 2em;
59 | }
60 |
61 | /* Style of the prefix "AWS IoT Device SDK C" that appears in the header. */
62 | #csdkprefix {
63 | color: #757575;
64 | }
65 |
66 | /* Style of the "Return to main page" link that appears in the header. */
67 | #returntomain {
68 | padding: 0.5em;
69 | }
70 |
71 | /* Style of the dividers on Configuration Settings pages. */
72 | div.configpagedivider {
73 | margin-left: 0px !important;
74 | margin-right: 0px !important;
75 | margin-top: 20px !important;
76 | }
77 |
78 | /* Style of configuration setting names. */
79 | dl.section.user ~ h1 {
80 | border-bottom: none;
81 | color: #000000;
82 | font-family: monospace, fixed;
83 | font-size: 16px;
84 | margin-bottom: 0px;
85 | margin-left: 2em;
86 | margin-top: 1.5em;
87 | }
88 |
89 | /* Style of paragraphs on a configuration settings page. */
90 | dl.section.user ~ * {
91 | margin-bottom: 10px;
92 | margin-left: 4em;
93 | margin-right: 4em;
94 | margin-top: 0px;
95 | }
96 |
97 | /* Hide the configuration setting marker. */
98 | dl.section.user {
99 | display: none;
100 | }
101 |
102 | /* Overrides for code fragments and lines. */
103 | div.fragment {
104 | background: #ffffff;
105 | border: none;
106 | padding: 5px;
107 | }
108 |
109 | div.line {
110 | color: #3a3a3a;
111 | }
112 |
113 | /* Overrides for code syntax highlighting colors. */
114 | span.comment {
115 | color: #008000;
116 | }
117 |
118 | span.keyword, span.keywordtype, span.keywordflow {
119 | color: #0000ff;
120 | }
121 |
122 | span.preprocessor {
123 | color: #50015a;
124 | }
125 |
126 | span.stringliteral, span.charliteral {
127 | color: #800c0c;
128 | }
129 |
130 | a.code, a.code:visited, a.line, a.line:visited {
131 | color: #496194;
132 | }
133 |
--------------------------------------------------------------------------------
/include/iot_efuse.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Common IO - basic V1.0.0
3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 | *
5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | * this software and associated documentation files (the "Software"), to deal in
7 | * the Software without restriction, including without limitation the rights to
8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | * the Software, and to permit persons to whom the Software is furnished to do so,
10 | * subject to the following conditions:
11 | *
12 | * The above copyright notice and this permission notice shall be included in all
13 | * copies or substantial portions of the Software.
14 | *
15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 | *
22 | * http://aws.amazon.com/freertos
23 | * http://www.FreeRTOS.org
24 | */
25 |
26 | /**
27 | * @file iot_efuse.h
28 | * @brief File for the APIs of efuse called by application layer.
29 | */
30 | #ifndef _IOT_EFUSE_H_
31 | #define _IOT_EFUSE_H_
32 |
33 | /**
34 | * @defgroup iot_efuse EFUSE Abstraction APIs.
35 | * @{
36 | */
37 |
38 | /**
39 | * The return codes for the functions in EFUSE.
40 | */
41 | #define IOT_EFUSE_SUCCESS ( 0 ) /*!< Efuse operation completed successfully. */
42 | #define IOT_EFUSE_INVALID_VALUE ( 1 ) /*!< At least one parameter is invalid. */
43 | #define IOT_EFUSE_READ_FAIL ( 2 ) /*!< Error reading Efuse value. */
44 | #define IOT_EFUSE_WRITE_FAIL ( 3 ) /*!< Error writing Efuse value. */
45 | #define IOT_EFUSE_CLOSE_FAIL ( 4 ) /*!< Error closing Efuse instance. */
46 | #define IOT_EFUSE_FUNCTION_NOT_SUPPORTED ( 5 ) /*!< Efuse operation not supported. */
47 | #define IOT_EFUSE_ERROR ( 6 ) /*!< Error performing Efuse operation. */
48 |
49 | /**
50 | * @brief The Efuse descriptor type defined in the source file.
51 | */
52 | struct IotEfuseDescriptor;
53 |
54 | /**
55 | * @brief IotEfuseHandle_t is the handle type returned by calling iot_efuse_open().
56 | * This is initialized in open and returned to caller. The caller must pass
57 | * this pointer to the rest of APIs.
58 | */
59 | typedef struct IotEfuseDescriptor * IotEfuseHandle_t;
60 |
61 | /**
62 | * @brief iot_efuse_open is used to Initialize things needed to access efuse.
63 | *
64 | * @return
65 | * - Handle to IotEfuseHandle_t on success
66 | * - NULL if the handle is already opened. handle must be closed before calling open again
67 | */
68 | IotEfuseHandle_t iot_efuse_open( void );
69 |
70 | /**
71 | * @brief iot_efuse_close is used to de Initialize things needed to disable efuse access.
72 | *
73 | * @param[in] pxEfuseHandle handle to efuse interface returned in iot_efuse_open()
74 | *
75 | * @return
76 | * - IOT_EFUSE_SUCCESS if succeeded,
77 | * - IOT_EFUSE_INVALID_VALUE on NULL pxEfuseHandle
78 | * - IOT_EFUSE_INVALID_VALUE if instance not previously opened.
79 | * - IOT_EFUSE_CLOSE_FAIL if the underneath HW deinit api returns fail.
80 | */
81 | int32_t iot_efuse_close( IotEfuseHandle_t const pxEfuseHandle );
82 |
83 | /**
84 | * @brief Read 32-bit efuse word from specified index.
85 | *
86 | * @param[in] pxEfuseHandle handle to efuse interface returned in iot_efuse_open()
87 | * @param[in] ulIndex index of efuse word to read. Caller must know the underlying
88 | * efuse mechanism and make sure index is a valid one.
89 | * @param[out] ulValue The receive buffer to read the data into
90 | *
91 | * @return
92 | * - IOT_EFUSE_SUCCESS if read succeeded,
93 | * - IOT_EFUSE_READ_FAIL if read failed,
94 | * - IOT_EFUSE_INVALID_VALUE if pxEfuseHandle is NULL, index is invalid, or ulValue is NULL.
95 | * - IOT_EFUSE_FUNCTION_NOT_SUPPORTED if 32-bit efuse word is not supported
96 | */
97 | int32_t iot_efuse_read_32bit_word( IotEfuseHandle_t const pxEfuseHandle,
98 | uint32_t ulIndex,
99 | uint32_t * ulValue );
100 |
101 | /**
102 | * @brief Write 32-bit value to the 32-bit efuse word at specified index.
103 | *
104 | * @param[in] pxEfuseHandle handle to efuse interface returned in iot_efuse_open()
105 | * @param[in] ulIndex index of efuse word to write to. Caller must know the underlying
106 | * efuse mechanism and make sure index is a valid one.
107 | * @param[in] ulValue The 32-bit value to write.
108 | *
109 | * @return
110 | * - IOT_EFUSE_SUCCESS if write succeeded,
111 | * - IOT_EFUSE_WRITE_FAIL if write failed
112 | * - IOT_EFUSE_INVALID_VALUE if pxEfuseHandle is NULL, or index is invalid.
113 | * - IOT_EFUSE_FUNCTION_NOT_SUPPORTED if 32-bit efuse word is not supported
114 | */
115 | int32_t iot_efuse_write_32bit_word( IotEfuseHandle_t const pxEfuseHandle,
116 | uint32_t ulIndex,
117 | uint32_t ulValue );
118 |
119 | /**
120 | * @brief Read 16-bit efuse word from specified index.
121 | *
122 | * @param[in] pxEfuseHandle handle to efuse interface returned in iot_efuse_open()
123 | * @param[in] ulIndex index of efuse word to read. Caller must know the underlying
124 | * efuse mechanism and make sure index is a valid one.
125 | * @param[out] ulValue The receive buffer to read the data into
126 | *
127 | * @return
128 | * - IOT_EFUSE_SUCCESS if read succeeded,
129 | * - IOT_EFUSE_READ_FAIL if read failed
130 | * - IOT_EFUSE_INVALID_VALUE if pxEfuseHandle or ulValue is NULL, or index is invalid
131 | * - IOT_EFUSE_FUNCTION_NOT_SUPPORTED if 16-bit efuse word is not supported
132 | */
133 | int32_t iot_efuse_read_16bit_word( IotEfuseHandle_t const pxEfuseHandle,
134 | uint32_t ulIndex,
135 | uint16_t * ulValue );
136 |
137 | /**
138 | * @brief Write 16-bit value to the 16-bit efuse word at specified index.
139 | *
140 | * @param[in] pxEfuseHandle handle to efuse interface returned in iot_efuse_open()
141 | * @param[in] ulIndex index of efuse word to write to. Caller must know the underlying
142 | * efuse mechanism and make sure index is a valid one.
143 | * @param[in] value The 16-bit value to write.
144 | *
145 | * @return
146 | * - IOT_EFUSE_SUCCESS if write succeeded,
147 | * - IOT_EFUSE_WRITE_FAIL if write failed
148 | * - IOT_EFUSE_INVALID_VALUE if index is invalid, or pxEfuseHandle is NULL.
149 | * - IOT_EFUSE_FUNCTION_NOT_SUPPORTED if 16-bit efuse word is not supported
150 | */
151 | int32_t iot_efuse_write_16bit_word( IotEfuseHandle_t const pxEfuseHandle,
152 | uint32_t ulIndex,
153 | uint16_t value );
154 |
155 | /**
156 | * @}
157 | */
158 | /* end of group iot_efuse */
159 |
160 | #endif /* ifndef _IOT_EFUSE_H_ */
161 |
--------------------------------------------------------------------------------
/include/iot_gpio.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Common IO - basic V1.0.0
3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 | *
5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | * this software and associated documentation files (the "Software"), to deal in
7 | * the Software without restriction, including without limitation the rights to
8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | * the Software, and to permit persons to whom the Software is furnished to do so,
10 | * subject to the following conditions:
11 | *
12 | * The above copyright notice and this permission notice shall be included in all
13 | * copies or substantial portions of the Software.
14 | *
15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 | *
22 | * http://aws.amazon.com/freertos
23 | * http://www.FreeRTOS.org
24 | */
25 |
26 | /**
27 | * @file iot_gpio.h
28 | * @brief This file contains all the GPIO HAL API definitions.
29 | * This GPIO interface APIs only provides pin-level functions. To modify a GPIO pin, a handle must be obtained
30 | * by calling the iot_gpio_open() function. This handle must be passed to other functions in this interface.
31 | * Handling multiple GPIOs simultaneously in the same bank or different banks is outside of the scope of this file.
32 | * User can modify multiple pins sequentially using this interface by iterating over multiple GPIOs in a loop.
33 | */
34 |
35 | #ifndef _IOT_GPIO_H_
36 | #define _IOT_GPIO_H_
37 |
38 | /**
39 | * @defgroup iot_gpio GPIO HAL APIs
40 | * @{
41 | */
42 |
43 | /**
44 | * @brief Error codes
45 | */
46 | #define IOT_GPIO_SUCCESS ( 0 ) /*!< GPIO operation completed successfully. */
47 | #define IOT_GPIO_INVALID_VALUE ( 1 ) /*!< At least one parameter is invalid. */
48 | #define IOT_GPIO_READ_FAILED ( 2 ) /*!< GPIO read operation failed. */
49 | #define IOT_GPIO_WRITE_FAILED ( 3 ) /*!< GPIO write operation failed. */
50 | #define IOT_GPIO_FUNCTION_NOT_SUPPORTED ( 4 ) /*!< GPIO operation not supported. */
51 |
52 | /**
53 | * @brief enum for configuring GPIO input/output direction.
54 | */
55 | typedef enum
56 | {
57 | eGpioDirectionInput, /*!< Configure GPIO pin direction for input. */
58 | eGpioDirectionOutput /*!< Configure GPIO pin direction for output. */
59 | } IotGpioDirection_t;
60 |
61 | /**
62 | * @brief enum for configuring GPIO output type.
63 | */
64 | typedef enum
65 | {
66 | eGpioOpenDrain, /*!< Configure GPIO pin mode as open drain. */
67 | eGpioPushPull /*!< Configure GPIO pin mode as push pull. */
68 | } IotGpioOutputMode_t;
69 |
70 | /**
71 | * @brief GPIO pin internal pull state. Sets the default state for output pins.
72 | */
73 | typedef enum
74 | {
75 | eGpioPullNone, /*!< Configure GPIO pin with no pull direction. */
76 | eGpioPullUp, /*!< Configure GPIO pin as pull up. */
77 | eGpioPullDown /*!< Configure GPIO pin as pull down. */
78 | } IotGpioPull_t;
79 |
80 | /**
81 | * @brief GPIO pin interrupt config types.
82 | */
83 | typedef enum
84 | {
85 | eGpioInterruptNone, /*!< Configure GPIO pin to not generate an interrupt. */
86 | eGpioInterruptRising, /*!< Configure GPIO pin to generate an interrupt when signal rises. */
87 | eGpioInterruptFalling, /*!< Configure GPIO pin to generate an interrupt when signal falls. */
88 | eGpioInterruptEdge, /*!< Configure GPIO pin to generate an interrupt when either rising or falling. */
89 | eGpioInterruptLow, /*!< Configure GPIO pin to generate an interrupt when signal is low. */
90 | eGpioInterruptHigh, /*!< Configure GPIO pin to generate an interrupt when signal is high. */
91 | } IotGpioInterrupt_t;
92 |
93 | /**
94 | * @brief Ioctl request types.
95 | */
96 | typedef enum
97 | {
98 | eSetGpioFunction, /*!< Set GPIO function. Takes int32_t as input to set the alternate function.
99 | * The value of the alternate function depends on the HW */
100 | eSetGpioDirection, /*!< Set GPIO Direction. Takes input type IotGpioDirection_t */
101 | eSetGpioPull, /*!< Set GPIO Pull mode. Takes input type IotGpioPull_t */
102 | eSetGpioOutputMode, /*!< Set GPIO output type. Takes input type IotGpioOutputType_t */
103 | eSetGpioInterrupt, /*!< Set GPIO Interrupt type. This configures the GPIO to generate an interrupt based on the configuration.
104 | * Takes input type IotGpioInterrupt_t */
105 | eSetGpioSpeed, /*!< Set GPIO Speed. Takes a int32_t value based on the underlying HW support */
106 | eSetGpioDriveStrength, /*!< Set GPIO Drive Strength. Takes an int32_t value based on the underlying HW support */
107 | eGetGpioFunction, /*!< Get GPIO function setting. Returns an int32_t */
108 | eGetGpioDirection, /*!< Get GPIO Direction setting. Returns IotGpioDirection_t */
109 | eGetGpioPull, /*!< Get GPIO Pull mode setting. Returns IotGpioPull_t */
110 | eGetGpioOutputType, /*!< Get GPIO output type. Returns IotGpioOutputType_t */
111 | eGetGpioInterrupt, /*!< Get GPIO Interrupt config. Returns IotGpioInterrupt_t type */
112 | eGetGpioSpeed, /*!< Get GPIO Speed setting. Returns an int32_t type */
113 | eGetGpioDriveStrength /*!< Get GPIO Drive Strength. Returns int32_t type */
114 | } IotGpioIoctlRequest_t;
115 |
116 | /**
117 | * @brief GPIO descriptor type defined in the source file.
118 | */
119 | struct IotGpioDescriptor;
120 |
121 | /**
122 | * @brief IotGpioHandle_t type is the GPIO handle returned by calling iot_gpio_open()
123 | * this is initialized in open and returned to caller. Caller must pass this pointer
124 | * to the rest of the APIs.
125 | */
126 | typedef struct IotGpioDescriptor * IotGpioHandle_t;
127 |
128 | /**
129 | * @brief GPIO interrupt callback type. This callback is passed
130 | * to the driver by using iot_gpio_set_callback API.
131 | * @param[out] ucPinState The variable which has state of the GPIO pin.
132 | * @param[in] pvUserContext User Context passed when setting the callback.
133 | * This is not used by the driver, but just passed back to the user
134 | * in the callback.
135 | */
136 | typedef void ( * IotGpioCallback_t )( uint8_t ucPinState,
137 | void * pvUserContext );
138 |
139 | /**
140 | * @brief iot_gpio_open is used to open the GPIO handle.
141 | * The application must call this function to open desired GPIO and use other functions.
142 | *
143 | * @param[in] lGpioNumber The logical GPIO number to open. It depends on the
144 | * implementation to map logical GPIO number to physical GPIO port
145 | * and pin.
146 | *
147 | * @return
148 | * - handle to the GPIO peripheral if everything succeeds
149 | * - NULL, if
150 | * - invalid instance number
151 | * - open same instance more than once before closing it.
152 | */
153 | IotGpioHandle_t iot_gpio_open( int32_t lGpioNumber );
154 |
155 | /**
156 | * @brief iot_gpio_set_callback is used to set the callback to be called when an
157 | * interrupt is triggered.
158 | *
159 | * @note Single callback is used for both read_async and write_async. Newly set callback overrides the one previously set
160 | * @note This callback will not be invoked when synchronous operation completes.
161 | * @note This callback is per handle. Each instance has its own callback.
162 | *
163 | * @warning If input handle or if callback function is NULL, this function silently takes no action.
164 | *
165 | * @param[in] pxGpio The GPIO handle returned in the open() call.
166 | * @param[in] xGpioCallback The callback function to be called on interrupt.
167 | * @param[in] pvUserContext The user context to be passed back when callback is called.
168 | */
169 | void iot_gpio_set_callback( IotGpioHandle_t const pxGpio,
170 | IotGpioCallback_t xGpioCallback,
171 | void * pvUserContext );
172 |
173 | /**
174 | * @brief iot_gpio_read_sync is used to read data from GPIO pin in blocking mode.
175 | *
176 | * @param[in] pxGpio The GPIO handle returned in the open() call.
177 | * @param[out] pucPinState The variable which reads state of the GPIO pin.
178 | *
179 | * @return
180 | * - IOT_GPIO_SUCCESS on success
181 | * - IOT_GPIO_INVALID_VALUE if pxGpio or pucPinState are NULL
182 | * - IOT_GPIO_READ_FAILED on failure.
183 | *
184 | */
185 | int32_t iot_gpio_read_sync( IotGpioHandle_t const pxGpio,
186 | uint8_t * pucPinState );
187 |
188 | /**
189 | * @brief iot_gpio_write_sync is used to write data into the GPIO pin in blocking mode.
190 | *
191 | * @param[in] pxGpio The GPIO handle returned in the open() call.
192 | * @param[in] ucPinState The value to write into the GPIO pin.
193 | *
194 | * @return
195 | * - IOT_GPIO_SUCCESS on success
196 | * - IOT_GPIO_INVALID_VALUE if pxGpio or pucPinState are NULL
197 | * - IOT_GPIO_WRITE_FAILED on failure.
198 | */
199 | int32_t iot_gpio_write_sync( IotGpioHandle_t const pxGpio,
200 | uint8_t ucPinState );
201 |
202 | /**
203 | * @brief iot_gpio_close is used to deinitializes the GPIO pin to default value and close the handle.
204 | * The application should call this function to reset and deinitialize the GPIO pin.
205 | *
206 | * @param[in] pxGpio The GPIO handle returned in the open() call.
207 | *
208 | * @return
209 | * - IOT_GPIO_SUCCESS on success
210 | * - IOT_GPIO_INVALID_VALUE if
211 | * - pxGpio handle is NULL
212 | * - if is not in open state (already closed).
213 | */
214 | int32_t iot_gpio_close( IotGpioHandle_t const pxGpio );
215 |
216 | /**
217 | * @brief iot_gpio_ioctl is used to configure GPIO pin options.
218 | * The application should call this function to configure various GPIO
219 | * pin options: pin function, I/O direction, pin internal pull mode,
220 | * drive strength, slew rate etc
221 | *
222 | * @param[in] pxGpio The GPIO handle returned in the open() call.
223 | * @param[in] xRequest One of IotGpioIoctlRequest_t enum
224 | * @param[in,out] pvBuffer Buffer holding GPIO set or get values.
225 | *
226 | * @return
227 | * - IOT_GPIO_SUCCESS on success
228 | * - IOT_GPIO_INVALID_VALUE on NULL handle, invalid request, or NULL buffer when required.
229 | * - IOT_GPIO_FUNCTION_NOT_SUPPORTED is only valid for
230 | * - eSetGpioFunction / eGetGpioFunction
231 | * - eSetGpioSpeed / eGetGpioSpeed
232 | * - eSetGpioDriveStrength / eGetGpioDriveStrength
233 | * - eSetGpioInterrupt / eGetGpioInterrupt
234 | */
235 | int32_t iot_gpio_ioctl( IotGpioHandle_t const pxGpio,
236 | IotGpioIoctlRequest_t xRequest,
237 | void * const pvBuffer );
238 |
239 | /**
240 | * @}
241 | */
242 |
243 | #endif /* _IOT_GPIO_H_ */
244 |
--------------------------------------------------------------------------------
/include/iot_hw.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Common IO - basic V1.0.0
3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 | *
5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | * this software and associated documentation files (the "Software"), to deal in
7 | * the Software without restriction, including without limitation the rights to
8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | * the Software, and to permit persons to whom the Software is furnished to do so,
10 | * subject to the following conditions:
11 | *
12 | * The above copyright notice and this permission notice shall be included in all
13 | * copies or substantial portions of the Software.
14 | *
15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 | *
22 | * http://aws.amazon.com/freertos
23 | * http://www.FreeRTOS.org
24 | */
25 |
26 | /**
27 | * @file iot_hw.h
28 | * @brief Define common APIs to get hardware ID and hardware revision.
29 | */
30 | #ifndef _IOT_HW_H_
31 | #define _IOT_HW_H_
32 |
33 | /**
34 | * @brief Error code returned by platform
35 | *
36 | * We assume that neither hardware ID nor hardware revision number will ever be greater than 255
37 | * it means that API is not implemented or supported if API returns 0xFF
38 | */
39 | #define IOT_HW_UNSUPPORTED ( 0xFFFF )
40 |
41 | /**
42 | * @brief API to read hardware ID.
43 | *
44 | * @note: the format and contents of this field are specific
45 | * to each vendor. With the expectation that they will
46 | * be unique for each board.
47 | *
48 | * @return hardware ID number as unsigned byte
49 | */
50 | uint16_t iot_hw_get_id( void );
51 |
52 | /**
53 | * @brief API to read hardware revision.
54 | *
55 | * @note: the format and contents of this field are specific
56 | * to each vendor. With the expectation that they will
57 | * be unique for each revision.
58 | *
59 | * @return hardware revision number as unsigned byte
60 | */
61 | uint16_t iot_hw_get_rev( void );
62 |
63 | #endif /* _IOT_HW_H_ */
64 |
--------------------------------------------------------------------------------
/include/iot_perfcounter.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Common IO - basic V1.0.0
3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 | *
5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | * this software and associated documentation files (the "Software"), to deal in
7 | * the Software without restriction, including without limitation the rights to
8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | * the Software, and to permit persons to whom the Software is furnished to do so,
10 | * subject to the following conditions:
11 | *
12 | * The above copyright notice and this permission notice shall be included in all
13 | * copies or substantial portions of the Software.
14 | *
15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 | *
22 | * http://aws.amazon.com/freertos
23 | * http://www.FreeRTOS.org
24 | */
25 |
26 | /*******************************************************************************
27 | * @file iot_perfcounter.h
28 | *
29 | * @brief HAL APIs for Performance Counter
30 | *
31 | *******************************************************************************
32 | */
33 |
34 | /**
35 | * @file iot_perfcounter.h
36 | * @brief This file contains all the Performance counters HAL API definitions
37 | */
38 |
39 | #ifndef _IOT_PERFCOUNTER_H
40 | #define _IOT_PERFCOUNTER_H
41 |
42 | /**
43 | * @defgroup iot_perfcounter PerfCounter HAL APIs
44 | * @{
45 | * @brief The perf counter is generally used to measure the cycles (usually processor clock cycles )
46 | * taken between 2 places in code. perfcounters can be implemented using cycle counters if
47 | * the processor supports, or any generic timer that is granular enough to measure the time
48 | * between 2 points in code.
49 | */
50 |
51 | /**
52 | * @brief iot_perfcounter_open is used to Initialize the performance counter.
53 | *
54 | */
55 | void iot_perfcounter_open( void );
56 |
57 | /**
58 | * @brief iot_perfcounter_get_value is used to get the current performance counter
59 | * value.
60 | *
61 | * @return returns performance counter value as uint64 value.
62 | */
63 | uint64_t iot_perfcounter_get_value( void );
64 |
65 | /**
66 | * @brief iot_perfcounter_get_frequency is used to get the current frequency
67 | * performance counters are running at. This can be used to determine the
68 | * time delta between two perfcounter values returned by calling iot_perfcounter_get_value()
69 | *
70 | * @return returns the frequency of the performance counter as a uint32 value.
71 | * This can be used to determine the period between perfcounter
72 | * increments.
73 | */
74 | uint32_t iot_perfcounter_get_frequency( void );
75 |
76 |
77 | /**
78 | * @brief iot_perfcounter_close is used to de-initialize the perfcounter.
79 | * It may reset the counter value in perfcounter.
80 | *
81 | */
82 | void iot_perfcounter_close( void );
83 |
84 | /**
85 | * @}
86 | */
87 |
88 | #endif /* ifndef _IOT_PERFCOUNTER_H */
89 |
--------------------------------------------------------------------------------
/include/iot_pwm.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Common IO - basic V1.0.0
3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 | *
5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | * this software and associated documentation files (the "Software"), to deal in
7 | * the Software without restriction, including without limitation the rights to
8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | * the Software, and to permit persons to whom the Software is furnished to do so,
10 | * subject to the following conditions:
11 | *
12 | * The above copyright notice and this permission notice shall be included in all
13 | * copies or substantial portions of the Software.
14 | *
15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 | *
22 | * http://aws.amazon.com/freertos
23 | * http://www.FreeRTOS.org
24 | */
25 |
26 | /**
27 | * @file iot_pwm.h
28 | * @brief This file contains all the PWM HAL API definitions
29 | */
30 |
31 | #ifndef _IOT_PWM_H_
32 | #define _IOT_PWM_H_
33 |
34 | /**
35 | * @defgroup iot_pwm PWM HAL APIs
36 | * @{
37 | */
38 |
39 | /**
40 | * @brief Return values used by PWM driver.
41 | */
42 | #define IOT_PWM_SUCCESS ( 0 ) /*!< PWM operation completed successfully. */
43 | #define IOT_PWM_INVALID_VALUE ( 1 ) /*!< At least one parameter is invalid. */
44 | #define IOT_PWM_NOT_CONFIGURED ( 2 ) /*!< PWM must be configured prior to start. */
45 | #define IOT_PWM_FUNCTION_NOT_SUPPORTED ( 3 ) /*!< PWM operation not supported. */
46 |
47 |
48 | /**
49 | * @brief PWM configuration type.
50 | */
51 | typedef struct IotPwmConfig
52 | {
53 | uint32_t ulPwmFrequency; /*!< PWM frequency */
54 | uint8_t ucPwmDutyCycle; /*!< PWM duty cycle */
55 | uint8_t ucPwmChannel; /*!< PWM output channel. Depending on individual HW implementations,
56 | * each pwm controller may have one or more channels, where the
57 | * output signal can be directed. */
58 | } IotPwmConfig_t;
59 |
60 | /**
61 | * @brief PWM descriptor type defined in the source file.
62 | */
63 | struct IotPwmDescriptor;
64 |
65 | /**
66 | * @brief IotPwmHandle_t type is the PWM handle returned by calling iot_pwm_open()
67 | * this is initialized in open and returned to caller. Caller must pass this pointer
68 | * to the rest of the APIs.
69 | */
70 | typedef struct IotPwmDescriptor * IotPwmHandle_t;
71 |
72 | /**
73 | * @brief iot_pwm_open is used to initialize the PWM driver instance.
74 | * this API will configure PWM and may reset the PWM hardware.
75 | *
76 | * @param[in] lPwmInstance The instance of the PWM to initialize.
77 | * PWM is output only.
78 | *
79 | * @return
80 | * - Handle to PWM interface on success
81 | * - NULL if
82 | * - invalid instance
83 | * - instance already open
84 | */
85 | IotPwmHandle_t iot_pwm_open( int32_t lPwmInstance );
86 |
87 | /**
88 | * @brief iot_pwm_set_config sets up the PWM frequency and duty cycle
89 | * to generate the PWM pulses required.
90 | *
91 | * @param[in] pxPwmHandle Handle to PWM driver returned in
92 | * iot_pwm_open
93 | * @param[in] xConfig PWM configuration to be setup.
94 | *
95 | * @return
96 | * - IOT_PWM_SUCCESS on success
97 | * - IOT_PWM_INVALID_VALUE if pxPwmHandle == NULL or invalid config setting
98 | */
99 | int32_t iot_pwm_set_config( IotPwmHandle_t const pxPwmHandle,
100 | const IotPwmConfig_t xConfig );
101 |
102 | /**
103 | * @brief iot_pwm_get_config returns the current PWM configuration
104 | *
105 | * @param[in] pxPwmHandle Handle to PWM driver returned in
106 | * iot_pwm_open
107 | *
108 | * @return
109 | * - pointer to current PWM configuration on success
110 | * - NULL if pxPwmHandle == NULL
111 | */
112 | IotPwmConfig_t * iot_pwm_get_config( IotPwmHandle_t const pxPwmHandle );
113 |
114 | /*!
115 | * @brief Start the PWM hardware. PWM configuration must be
116 | * set before PWM is started. PWM signal availability
117 | * on the configured output based on the PWMChannel configured
118 | * in iot_pwm_set_config().
119 | *
120 | * @param[in] pxPwmHandle Handle to PWM driver returned in
121 | * iot_pwm_open
122 | *
123 | * @return
124 | * - IOT_PWM_SUCCESS on success
125 | * - IOT_PWM_INVALID_VALUE if pxPwmHandle == NULL
126 | * - IOT_PWM_NOT_CONFIGURED if iot_pwm_set_config hasn't been called.
127 | */
128 | int32_t iot_pwm_start( IotPwmHandle_t const pxPwmHandle );
129 |
130 | /*!
131 | * @brief Stop the PWM hardware.
132 | *
133 | * @param[in] pxPwmHandle Handle to PWM driver returned in
134 | * iot_pwm_open
135 | *
136 | * @return
137 | * - IOT_PWM_SUCCESS on success
138 | * - IOT_PWM_INVALID_VALUE if pxPwmHandle == NULL
139 | */
140 | int32_t iot_pwm_stop( IotPwmHandle_t const pxPwmHandle );
141 |
142 | /**
143 | * @brief iot_pwm_close de-initializes the PWM.
144 | *
145 | * @param[in] pxPwmHandle Handle to PWM driver returned in
146 | * iot_pwm_open
147 | *
148 | * @return
149 | * - IOT_PWM_SUCCESS on success
150 | * - IOT_PWM_INVALID_VALUE if
151 | * - pxPwmHandle == NULL
152 | * - not in open state (already closed).
153 | *
154 | */
155 | int32_t iot_pwm_close( IotPwmHandle_t const pxPwmHandle );
156 |
157 | /**
158 | * @}
159 | */
160 |
161 | #endif /* ifndef _IOT_PWM_H_ */
162 |
--------------------------------------------------------------------------------
/include/iot_reset.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Common IO - basic V1.0.0
3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 | *
5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | * this software and associated documentation files (the "Software"), to deal in
7 | * the Software without restriction, including without limitation the rights to
8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | * the Software, and to permit persons to whom the Software is furnished to do so,
10 | * subject to the following conditions:
11 | *
12 | * The above copyright notice and this permission notice shall be included in all
13 | * copies or substantial portions of the Software.
14 | *
15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 | *
22 | * http://aws.amazon.com/freertos
23 | * http://www.FreeRTOS.org
24 | */
25 |
26 | /**
27 | * @file iot_reset.h
28 | * @brief This file contains all the Reset HAL API definitions
29 | */
30 |
31 | #ifndef _IOT_RESET_H_
32 | #define _IOT_RESET_H_
33 |
34 | #include
35 |
36 | /**
37 | * @defgroup iot_reset Reset HAL APIs
38 | * @{
39 | */
40 |
41 | /**
42 | * Return values used by reset driver
43 | */
44 | #define IOT_RESET_SUCCESS ( 0 ) /**< Reset operation completed successfully. */
45 | #define IOT_RESET_FUNCTION_NOT_SUPPORTED ( 1 ) /**< Reset function not supported. */
46 | #define IOT_RESET_INVALID_VALUE ( 2 ) /**< At least one parameter is invalid. */
47 |
48 | /**
49 | * @brief enum for the reason of the last reset
50 | */
51 | typedef enum
52 | {
53 | eResetPowerOnBoot, /**< Normal power on Boot, when the power is applied to the device. */
54 | eResetWarmBoot, /**< Last reset triggered due to warm Reset. for ex: iot_reset_reboot(0) was called to reset the device */
55 | eResetColdBoot, /**< Last reset triggered due to cold Reset. for ex: iot_reset_reboot(1) */
56 | eResetWatchdog, /**< Last reset triggered due to watchdog expiration */
57 | eResetBusTimeout, /**< Last reset triggered due to internal bus timeout on the SoC */
58 | eResetPmic, /**< Last reset caused by power management IC */
59 | eResetBrownOut, /**< Last reset caused by power brown out */
60 | eResetOther, /**< Last reset caused by other reasons specific to the underlying hardware */
61 | } IotResetReason_t;
62 |
63 | /**
64 | * @brief enum for the type of reset to perform
65 | */
66 | typedef enum
67 | {
68 | eResetWarmBootFlag, /**< Perform warm-reset */
69 | eResetColdBootFlag, /**< Perform cold-reset */
70 | } IotResetBootFlag_t;
71 |
72 | /**
73 | * @brief iot_reset_reboot is used to reboot the device.
74 | *
75 | * @param[in] xResetBootFlag flag to determine either to do cold-reset or warm-reset.
76 | * cold-reset means the device is restarted and does not keep
77 | * any blocks of the SOC powered on i.e. device is shutdown and rebooted),
78 | * and warm-reset means the device is restarted while keeping some of the SoC blocks
79 | * powered on through the reboot process.
80 | * For example warm-boot may keep the RAM contents valid after reset by keeping the power
81 | * on for RAM banks, while cold-boot will wipe off the contents.
82 | * One of the IotResetBootFlag_t value.
83 | */
84 | void iot_reset_reboot( IotResetBootFlag_t xResetBootFlag );
85 |
86 | /**
87 | * @brief iot_reset_shutdown is used to shutdown the device.
88 | * If the target does not support shutdown of the device, IOT_RESET_FUNCTION_NOT_SUPPORTED
89 | * is returned to the user.
90 | *
91 | * @return
92 | * - does not return and device shutdown on success
93 | * - IOT_RESET_FUNCTION_NOT_SUPPORTED if shutdown not supported.
94 | */
95 | int32_t iot_reset_shutdown( void );
96 |
97 | /**
98 | * @brief iot_get_reset_reason is used to get the last reset reason.
99 | * If the underlying HW does not support the feature of persisting the
100 | * reset reason, then this API will return IOT_RESET_FUNCTION_NOT_SUPPORTED
101 | * error with the value in out as don't care.
102 | *
103 | * @param[out] xResetReason One of the reset reasons specified in IotResetReason_t types
104 | *
105 | * @return
106 | * - IOT_RESET_SUCCESS on success.
107 | * - IOT_RESET_FUNCTION_NOT_SUPPORTED if not supported.
108 | * - IOT_RESET_INVALID_VALUE if xREsetReason == NULL
109 | */
110 | int32_t iot_get_reset_reason( IotResetReason_t * xResetReason );
111 |
112 | /**
113 | * @}
114 | */
115 |
116 | #endif /* ifndef _IOT_RESET_H_ */
117 |
--------------------------------------------------------------------------------
/include/iot_rtc.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Common IO - basic V1.0.0
3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 | *
5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | * this software and associated documentation files (the "Software"), to deal in
7 | * the Software without restriction, including without limitation the rights to
8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | * the Software, and to permit persons to whom the Software is furnished to do so,
10 | * subject to the following conditions:
11 | *
12 | * The above copyright notice and this permission notice shall be included in all
13 | * copies or substantial portions of the Software.
14 | *
15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 | *
22 | * http://aws.amazon.com/freertos
23 | * http://www.FreeRTOS.org
24 | */
25 |
26 | /*******************************************************************************
27 | * @file iot_rtc.h
28 | *
29 | * @brief HAL APIs for RTC
30 | *******************************************************************************
31 | */
32 |
33 | /**
34 | * @file iot_rtc.h
35 | * @brief This file contains all the RTC HAL API definitions
36 | */
37 |
38 | #ifndef _IOT_RTC_H_
39 | #define _IOT_RTC_H_
40 |
41 | /**
42 | * @defgroup iot_rtc RTC HAL APIs
43 | * @{
44 | */
45 |
46 | /**
47 | * @brief Return values used by RTC driver
48 | */
49 | #define IOT_RTC_SUCCESS ( 0 ) /*!< RTC operation completed successfully. */
50 | #define IOT_RTC_INVALID_VALUE ( 1 ) /*!< At least one parameter is invalid. */
51 | #define IOT_RTC_NOT_STARTED ( 2 ) /*!< RTC not started. */
52 | #define IOT_RTC_GET_FAILED ( 3 ) /*!< RTC get operation failed. */
53 | #define IOT_RTC_SET_FAILED ( 4 ) /*!< RTC set operation failed. */
54 | #define IOT_RTC_FUNCTION_NOT_SUPPORTED ( 5 ) /*!< RTC operation not supported. */
55 |
56 | /**
57 | * @brief RTC driver status values
58 | */
59 | typedef enum
60 | {
61 | eRtcTimerStopped, /*!< RTC Timer status: stopped. */
62 | eRtcTimerRunning, /*!< RTC Timer status: running. */
63 | eRtcTimerAlarmTriggered, /*!< RTC Timer status: alarm triggered. */
64 | eRtcTimerWakeupTriggered, /*!< RTC Timer status: wakeup triggered. */
65 | } IotRtcStatus_t;
66 |
67 | /**
68 | * @brief RTC date and time format info.
69 | */
70 | typedef struct IotRtcDatetime
71 | {
72 | uint8_t ucSecond; /*!< Seconds - range from 0 to 59.*/
73 | uint8_t ucMinute; /*!< minutes - range from 0 to 59.*/
74 | uint8_t ucHour; /*!< hours - range from 0 to 23.*/
75 | uint8_t ucDay; /*!< date of month - range from 1 to 31 (depending on month).*/
76 | uint8_t ucMonth; /*!< months since January - range from 0 to 11.*/
77 | uint16_t usYear; /*!< years since 1900 */
78 | uint8_t ucWday; /*!< Week day from Sunday - range from 0 to 6 */
79 | } IotRtcDatetime_t;
80 |
81 | /**
82 | * @brief Ioctl request types.
83 | *
84 | * @note: WakeupTime is a timer, in milliseconds in the future. AlarmTime is an exact time in the future.
85 | */
86 | typedef enum IotRtcIoctlRequest
87 | {
88 | eSetRtcAlarm, /*!< Set Alarm, date&time when Alarm need to occur. Takes input type IotRtcDatetime_t
89 | * @warning time must be in the future.*/
90 | eGetRtcAlarm, /*!< Get Alarm, gives the date&time when Alarm will occur. Returns IotRtcDatetime_t */
91 | eCancelRtcAlarm, /*!< Cancel any scheduled Alarm */
92 | eSetRtcWakeupTime, /*!< Set Wakeup time in miliseconds. Maximum number of miliseconds depend on the platform. Value is uint32_t */
93 | eGetRtcWakeupTime, /*!< Get Wakeup time in milli-seconds */
94 | eCancelRtcWakeup, /*!< Cancel any scheduled wake-up */
95 | eGetRtcStatus /*!< Get the RTC timer status value. Returns IotRtcStatus_t type*/
96 | } IotRtcIoctlRequest_t;
97 |
98 | /**
99 | * @brief RTC descriptor type defined in the source file.
100 | */
101 | struct IotRtcDescriptor;
102 |
103 | /**
104 | * @brief IotRtcHandle_t type is the RTC handle returned by calling iot_rtc_open()
105 | * this is initialized in open and returned to caller. Caller must pass this pointer
106 | * to the rest of the APIs.
107 | */
108 | typedef struct IotRtcDescriptor * IotRtcHandle_t;
109 |
110 | /**
111 | * @brief RTC notification callback type. This callback is passed
112 | * to the driver by using iot_rtc_set_callback API. The callback is
113 | * used to get the notifications for Alarm and Wakeup timers.
114 | *
115 | * @param[out] xStatus RTC timer status.
116 | * @param[in] pvUserContext User Context passed when setting the callback.
117 | * This is not used by the driver, but just passed back to the user
118 | * in the callback.
119 | */
120 | typedef void ( * IotRtcCallback_t)( IotRtcStatus_t xStatus,
121 | void * pvUserContext );
122 |
123 | /**
124 | * @brief iot_rtc_open is used to initialize the RTC timer.
125 | * It usually resets the RTC timer, sets up the clock for RTC etc...
126 | *
127 | * @param[in] lRtcInstance The instance of the RTC timer to initialize.
128 | *
129 | * @return
130 | * - the handle IotRtcHandle_t on success
131 | * - NULL if
132 | * - if instance is already open
133 | * - invalid instance
134 | */
135 | IotRtcHandle_t iot_rtc_open( int32_t lRtcInstance );
136 |
137 | /*!
138 | * @brief iot_rtc_set_callback is used to set the callback to be called when alarmTime triggers.
139 | * The caller must set the Alarm time using IOCTL to get the callback.
140 | *
141 | * @note Single callback is used for both rtc_alarm, and rtc_wakeup features.
142 | * @note Newly set callback overrides the one previously set
143 | * @note This callback is per handle. Each instance has its own callback.
144 | *
145 | * @param[in] pxRtcHandle handle to RTC driver returned in
146 | * iot_rtc_open()
147 | * @param[in] xCallback callback function to be called.
148 | * @param[in] pvUserContext user context to be passed when callback is called.
149 | *
150 | */
151 | void iot_rtc_set_callback( IotRtcHandle_t const pxRtcHandle,
152 | IotRtcCallback_t xCallback,
153 | void * pvUserContext );
154 |
155 | /**
156 | * @brief iot_rtc_ioctl is used to set RTC configuration and
157 | * RTC properties like Wakeup time, alarms etc.
158 | * Supported IOCTL requests are defined in iot_RtcIoctlRequest_t
159 | *
160 | * @param[in] pxRtcHandle handle to RTC driver returned in
161 | * iot_rtc_open()
162 | * @param[in] xRequest configuration request of type IotRtcIoctlRequest_t
163 | * @param[in,out] pvBuffer buffer holding RTC set and get values.
164 | *
165 | * @return
166 | * - IOT_RTC_SUCCESS on success
167 | * - IOT_RTC_INVALID_VALUE if
168 | * - pxRtcHandle == NULL
169 | * - xRequest is invalid
170 | * - pvBuffer == NULL (excluding eCancelRtcAlarm, eCancelRtcWakeup)
171 | * - if date/time is set in the past for eSetRtcAlarm
172 | * - IOT_RTC_SET_FAILED if date/time is invalid for eSetRtcAlarm.
173 | * - IOT_RTC_NOT_STARTED on error
174 | * - IOT_RTC_FUNCTION_NOT_SUPPORTED if feature not supported
175 | * - Only valid for eCancelRtcAlarm, eCancelRtcWakeup
176 | */
177 | int32_t iot_rtc_ioctl( IotRtcHandle_t const pxRtcHandle,
178 | IotRtcIoctlRequest_t xRequest,
179 | void * const pvBuffer );
180 |
181 | /**
182 | * @brief iot_rtc_set_date_time is used to set the current time as a reference in RTC timer counter.
183 | *
184 | * @param[in] pxRtcHandle handle to RTC driver returned in
185 | * iot_rtc_open()
186 | * @param[in] pxDatetime pointer to IotRtcDatetime_t structure to set the date&time
187 | * to be set in RTC counter.
188 | *
189 | * @return
190 | * - IOT_RTC_SUCCESS on success
191 | * - IOT_RTC_INVALID_VALUE if pxRtcHandle == NULL or pxDatetime == NULL
192 | * - IOT_RTC_SET_FAILED on error.
193 | */
194 | int32_t iot_rtc_set_datetime( IotRtcHandle_t const pxRtcHandle,
195 | const IotRtcDatetime_t * pxDatetime );
196 |
197 | /**
198 | * @brief iot_rtc_get_datetime is used to get the current time from the RTC counter.
199 | * The time must be set first as a reference to get the time.
200 | *
201 | * @param[in] pxRtcHandle handle to RTC driver returned in
202 | * iot_rtc_open()
203 | * @param[in] pxDatetime pointer to IotRtcDatetime_t structure to get the date&time
204 | * from RTC counter.
205 | *
206 | * @return
207 | * - IOT_RTC_SUCCESS on success
208 | * - IOT_RTC_INVALID_VALUE if pxRtcHandle == NULL or pxDatetime == NULL
209 | * - IOT_RTC_NOT_STARTED on error
210 | */
211 | int32_t iot_rtc_get_datetime( IotRtcHandle_t const pxRtcHandle,
212 | IotRtcDatetime_t * pxDatetime );
213 |
214 | /**
215 | * @brief iot_rtc_close is used to de-Initialize RTC Timer.
216 | * it resets the RTC timer and may stop the timer.
217 | *
218 | * @param[in] pxRtcHandle handle to RTC interface.
219 | *
220 | * @return
221 | * - IOT_RTC_SUCCESS on success
222 | * - IOT_RTC_INVALID_VALUE if
223 | * - pxRtcHandle == NULL
224 | * - not in open state (already closed).
225 | */
226 | int32_t iot_rtc_close( IotRtcHandle_t const pxRtcHandle );
227 |
228 | /**
229 | * @}
230 | */
231 |
232 | #endif /* ifndef _IOT_RTC_H_ */
233 |
--------------------------------------------------------------------------------
/include/iot_timer.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Common IO - basic V1.0.0
3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 | *
5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | * this software and associated documentation files (the "Software"), to deal in
7 | * the Software without restriction, including without limitation the rights to
8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | * the Software, and to permit persons to whom the Software is furnished to do so,
10 | * subject to the following conditions:
11 | *
12 | * The above copyright notice and this permission notice shall be included in all
13 | * copies or substantial portions of the Software.
14 | *
15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 | *
22 | * http://aws.amazon.com/freertos
23 | * http://www.FreeRTOS.org
24 | */
25 |
26 | /*******************************************************************************
27 | * @file iot_timer.h
28 | *
29 | * @brief HAL APIs for a generic timer driver
30 | *******************************************************************************
31 | */
32 |
33 | /**
34 | * @file iot_timer.h
35 | * @brief This file contains all the Timer HAL API definitions
36 | */
37 |
38 | #ifndef _IOT_TIMER_H_
39 | #define _IOT_TIMER_H_
40 |
41 | /**
42 | * @defgroup iot_timer Timer HAL APIs
43 | * @{
44 | */
45 |
46 | /**
47 | * @brief Return values used by timer driver
48 | */
49 | #define IOT_TIMER_SUCCESS ( 0 ) /*!< Timer operation completed successfully. */
50 | #define IOT_TIMER_INVALID_VALUE ( 1 ) /*!< At least one parameter is invalid. */
51 | #define IOT_TIMER_FUNCTION_NOT_SUPPORTED ( 2 ) /*!< Timer operation not supported. */
52 | #define IOT_TIMER_NOT_RUNNING ( 3 ) /*!< Timer not running. */
53 | #define IOT_TIMER_SET_FAILED ( 4 ) /*!< Timer set failed. */
54 |
55 | /**
56 | * @brief timer descriptor type defined in the source file.
57 | */
58 | struct IotTimerDescriptor;
59 |
60 | /**
61 | * @brief IotTimerHandle_t type is the timer handle returned by calling iot_timer_open()
62 | * this is initialized in open and returned to caller. Caller must pass this pointer
63 | * to the rest of the APIs.
64 | */
65 | typedef struct IotTimerDescriptor * IotTimerHandle_t;
66 |
67 | /**
68 | * @brief timer callback notification type. This callback is used for
69 | * notifying the caller when the setup timer expires.
70 | *
71 | * @param[in] pvUserContext User Context passed when setting the callback.
72 | */
73 | typedef void ( * IotTimerCallback_t)( void * pvUserContext );
74 |
75 | /**
76 | * @brief iot_timer_open is used to initialize the timer.
77 | * This function will start the timer.
78 | *
79 | * @param[in] lTimerInstance instance of the timer to initialize.
80 | *
81 | * @return
82 | * - Handle to IotTimerHandle_t on SUCCESS
83 | * - NULL if
84 | * - lTimerInstance is invalid
85 | * - lTimerInstance is already open.
86 | */
87 | IotTimerHandle_t iot_timer_open( int32_t lTimerInstance );
88 |
89 | /*!
90 | * @brief iot_timer_set_callback is used to set the callback to be called when
91 | * the timer reaches the count (delay) set by the caller.
92 | * Callers can set the delay using the iot_timer_delay API.
93 | *
94 | * @note Newly set callback overrides the one previously set
95 | * @note This callback is per handle. Each instance has its own callback.
96 | *
97 | * @warning This function silently does nothing if either pxTimerHandle or
98 | * xCallback handle are NULL.
99 | *
100 | * @param[in] pxTimerHandle handle to Timer interface returned in
101 | * iot_timer_open()
102 | * @param[in] xCallback The callback function to be called.
103 | * @param[in] pvUserContext The user context to be passed when callback is called.
104 | *
105 | */
106 | void iot_timer_set_callback( IotTimerHandle_t const pxTimerHandle,
107 | IotTimerCallback_t xCallback,
108 | void * pvUserContext );
109 |
110 | /*!
111 | * @brief iot_timer_start is used to start the timer counter. This call only makes the
112 | * timer counter running, and does not setup any match values etc..
113 | *
114 | * @param[in] pxTimerHandle handle to Timer interface returned in
115 | * iot_timer_open()
116 | *
117 | * @return
118 | * - IOT_TIMER_SUCCESS on success
119 | * - IOT_TIMER_INVALID_VALUE if pxTimerHandle is NULL
120 | */
121 | int32_t iot_timer_start( IotTimerHandle_t const pxTimerHandle );
122 |
123 | /*!
124 | * @brief iot_timer_stop is used to stop the timer counter if the timer is running.
125 | *
126 | * @param[in] pxTimerHandle handle to Timer interface returned in
127 | * iot_timer_open()
128 | *
129 | * @return returns IOT_TIMER_SUCCESS on success or returns
130 | * one of IOT_TIMER_INVALID_VALUE, IOT_TIMER_FUNCTION_NOT_SUPPORTED on error.
131 | * @return
132 | * - IOT_TIMER_SUCCESS on success
133 | * - IOT_TIMER_INVALID_VALUE if pxTimerHandle is NULL.
134 | * - IOT_TIMER_FUNCTION_NOT_SUPPORTED, if the free running timer on SoC cant be stopped.
135 | * - IOT_TIMER_NOT_RUNNING if iot_timer_start has not been called.
136 | */
137 | int32_t iot_timer_stop( IotTimerHandle_t const pxTimerHandle );
138 |
139 | /*!
140 | * @brief iot_timer_get_value is used to get the current timer value in micro seconds.
141 | *
142 | * @param[in] pxTimerHandle handle to Timer interface returned in
143 | * iot_timer_open()
144 | * @param[out] ullMicroSeconds current timer count in microseconds.
145 | *
146 | * @return
147 | * - IOT_TIMER_SUCCESS on success
148 | * - IOT_TIMER_INVALID_VALUE if pxTimerHandle or ulMicroSeconds pointers are NULL
149 | * - IOT_TIMER_NOT_RUNNING if timer hasn't been started.
150 | */
151 | int32_t iot_timer_get_value( IotTimerHandle_t const pxTimerHandle,
152 | uint64_t * ullMicroSeconds );
153 |
154 | /*!
155 | * @brief iot_timer_delay is used to set up a delay/wake-up time in microseconds.
156 | * The caller can use this API to delay current execution until the specified microSeconds.
157 | * A callback is called once the delay is expired (i,e the amount of microseconds is passed
158 | * from the time the API is called).
159 | * If no callback is registered by the caller, then once the delay is expired, caller cannot be
160 | * notified, but this mechanism can be useful to wake up the target from sleep.
161 | *
162 | * @param[in] pxTimerHandle handle to Timer interface returned in
163 | * iot_timer_open()
164 | * @param[in] ulDelayMicroSeconds delay time in micro seconds
165 | *
166 | * Example timer delay execution
167 | * The callback function is called to signal when the timer reaches the count (delay)
168 | * set by the caller.
169 | * @code{c}
170 | *
171 | * IotTimerHandle_t xTimerHandle;
172 | *
173 | * xTimerHandle = iot_timer_open( ltestIotTimerInstance);
174 | * // assert( xTimerHandle == NULL );
175 | *
176 | * // Set the callback to call prvTimerCallbackFunction() when delay reached.
177 | * iot_timer_set_callback(xTimerHandle, prvTimerCallbackFunction, NULL);
178 | *
179 | * // Set the timer delay to be TIMER_DEFAULT_DELAY_US
180 | * lRetVal = iot_timer_delay(xTimerHandle, TIMER_DEFAULT_DELAY_US );
181 | * // assert( lRetVal != IOT_TIMER_SUCCESS );
182 | *
183 | * //Start the timer
184 | * lRetVal = iot_timer_start(xTimerHandle);
185 | * // assert ( lRetVal != IOT_TIMER_SUCCESS);
186 | *
187 | * // Wait for the Delay callback to be called. Inside of prvTimerCallbackFunction()
188 | * // the function will use xSemaphoreGive() to signal completion.
189 | * lRetVal = xSemaphoreTake(IotTimerSemaphore, portMAX_DELAY);
190 | * // assert( lRetVal != TRUE );
191 | *
192 | * lRetVal = iot_timer_close(xTimerHandle);
193 | * //assert ( lRetVal != IOT_TIMER_SUCCESS);
194 | * @endcode
195 | *
196 | * @return
197 | * - IOT_TIMER_SUCCESS on success
198 | * - IOT_TIMER_INVALID_VALUE if pxTimerHandle or ulMicroSeconds pointers are NULL
199 | * - IOT_TIMER_NOT_RUNNING if timer hasn't been started.
200 | * - IOT_TIMER_SET_FAILED on error.
201 | */
202 | int32_t iot_timer_delay( IotTimerHandle_t const pxTimerHandle,
203 | uint32_t ulDelayMicroSeconds );
204 |
205 | /**
206 | * @brief iot_timer_cancel is used to cancel any existing delay call.
207 | * If a call to iot_timer_delay() was made earlier, calling iot_timer_cancel
208 | * will cancel that delay call, so no call-back will be called.
209 | *
210 | * @param[in] pxTimerHandle handle to Timer interface returned in
211 | * iot_timer_open()
212 | *
213 | * @return
214 | * - IOT_TIMER_SUCCESS on success
215 | * - IOT_TIMER_INVALID_VALUE if pxTimerHandle is NULL
216 | * - IOT_TIMER_FUNCTION_NOT_SUPPORTED if timer can't be cancelled.
217 | * - IOT_TIMER_NOTHING_TO_CANCEL if there is no timer running to cancel.
218 | */
219 | int32_t iot_timer_cancel( IotTimerHandle_t const pxTimerHandle );
220 |
221 | /**
222 | * @brief iot_timer_close is used to de-initializes the timer, stops the timer
223 | * if it was started and cancels the delay calls, and resets the timer value.
224 | *
225 | * @param[in] pxTimerHandle handle to Timer interface returned in
226 | * iot_timer_open()
227 | *
228 | * @return
229 | * - IOT_TIMER_SUCCESS on success
230 | * - IOT_TIMER_INVALID_VALUE if
231 | * - pxTimerHandle is NULL.
232 | * - pxTimerHandle not open (previously closed).
233 | */
234 | int32_t iot_timer_close( IotTimerHandle_t const pxTimerHandle );
235 |
236 | /**
237 | * @}
238 | */
239 |
240 | #endif /* ifndef _IOT_TIMER_H_ */
241 |
--------------------------------------------------------------------------------
/include/iot_tsensor.h:
--------------------------------------------------------------------------------
1 | /*
2 | * Common IO - basic V1.0.0
3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 | *
5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | * this software and associated documentation files (the "Software"), to deal in
7 | * the Software without restriction, including without limitation the rights to
8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | * the Software, and to permit persons to whom the Software is furnished to do so,
10 | * subject to the following conditions:
11 | *
12 | * The above copyright notice and this permission notice shall be included in all
13 | * copies or substantial portions of the Software.
14 | *
15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 | *
22 | * http://aws.amazon.com/freertos
23 | * http://www.FreeRTOS.org
24 | */
25 |
26 | /**
27 | * @file iot_tsensor.h
28 | * @brief File for the APIs of TempSensor called by application layer.
29 | */
30 |
31 | #ifndef _IOT_TSENSOR_H_
32 | #define _IOT_TSENSOR_H_
33 |
34 | /**
35 | * @defgroup iot_tsensor TempSensor Abstraction APIs.
36 | * @{
37 | */
38 |
39 | #include
40 |
41 | /**
42 | * @brief Return values used by tsensor driver
43 | */
44 | #define IOT_TSENSOR_SUCCESS ( 0 ) /*!< TempSensor operation completed successfully.*/
45 | #define IOT_TSENSOR_INVALID_VALUE ( 1 ) /*!< At least one parameter is invalid.*/
46 | #define IOT_TSENSOR_DISABLED ( 2 ) /*!< TempSensor is disabled.*/
47 | #define IOT_TSENSOR_CLOSED ( 3 ) /*!< TempSensor instance is not open.*/
48 | #define IOT_TSENSOR_GET_TEMP_FAILED ( 4 ) /*!< TempSensor failed to get the temperature.*/
49 | #define IOT_TSENSOR_SET_FAILED ( 5 ) /*!< TempSensor set threshold operation failed.*/
50 | #define IOT_TSENSOR_NOT_SUPPORTED ( 6 ) /*!< TempSensor operation not supported.*/
51 |
52 | /**
53 | * @brief tsensor threshold reached status
54 | */
55 | typedef enum
56 | {
57 | eTsensorMinThresholdReached, /*!< min temperature threshold reached status */
58 | eTsensorMaxThresholdReached /*!< max temperature threshold reached status */
59 | } IotTsensorStatus_t;
60 |
61 | /**
62 | * @brief Ioctl request types.
63 | */
64 | typedef enum
65 | {
66 | eTsensorSetMinThreshold, /*!< Set min temperature threshold using IotI2CIoctlConfig_t. Takes int32_t value in degrees celsius.*/
67 | eTsensorSetMaxThreshold, /*!< Set max temperature threshold using IotI2CIoctlConfig_t . Takes int32_t value in degrees celsius.*/
68 | eTsensorGetMinThreshold, /*!< Get min temperature threshold using IotI2CIoctlConfig_t. Returns int32_t value in degrees celsius.*/
69 | eTsensorGetMaxThreshold, /*!< Get max temperature threshold using IotI2CIoctlConfig_t. Returns int32_t value in degrees celsius.*/
70 | eTsensorPerformCalibration /*!< Perform calibration of the sensor */
71 | } IotTsensorIoctlRequest_t;
72 |
73 | /**
74 | * @brief tsensor descriptor type defined in the source file.
75 | */
76 | struct IotTsensorDescriptor;
77 |
78 | /**
79 | * @brief IotTsensorHandle_t type is the tsensor handle returned by calling iot_tsensor_open()
80 | * this is initialized in open and returned to caller. Caller must pass this pointer
81 | * to the rest of the APIs.
82 | */
83 | typedef struct IotTsensorDescriptor * IotTsensorHandle_t;
84 |
85 | /**
86 | * @brief The callback function for completion of Tsensor operation.
87 | *
88 | * @param[in] xStatus tsensor threshold reached status
89 | * @param[in] pvUserContext user provid context
90 | */
91 | typedef void ( * IotTsensorCallback_t)( IotTsensorStatus_t xStatus,
92 | void * pvUserContext );
93 |
94 | /**
95 | * @brief iot_tsensor_open is used to initialize the temperature sensor.
96 | * It sets up the clocks and power etc, if the sensor is internal
97 | * and sets up the communication channel if the sensor is external.
98 | *
99 | * @param[in] lTsensorInstance The instance of the tsensor to initialize. The instance
100 | * number is platform specific. i,e if you have more than one temperature
101 | * sensors, then 2 instances point to 2 different sensors.
102 | *
103 | * @return
104 | * - Handle to tsensor interface on success.
105 | * - NULL if
106 | * - lTsensorInstance is invalid.
107 | * - instance is already open.
108 | */
109 | IotTsensorHandle_t iot_tsensor_open( int32_t lTsensorInstance );
110 |
111 | /**
112 | * @brief Set the callback to be called when a threshold is reached on the sensor.
113 | * The caller must set the threshold level using IOCTL before the callback can be called.
114 | *
115 | * @note Single callback is used per instance for both min and max threshold points being reached.
116 | * @note Newly set callback overrides the one previously set
117 | *
118 | * @warning If input handle or if callback function is NULL, this function silently takes no action.
119 | *
120 | * @warning If threshold detection is not supported by the hardware, then the callback function will not work.
121 | *
122 | * @param[in] xTsensorHandle Handle to tsensor driver returned in open() call
123 | * @param[in] xCallback The callback function to be called on completion of transaction.
124 | * @param[in] pvUserContext user provid context
125 | */
126 | void iot_tsensor_set_callback( IotTsensorHandle_t const xTsensorHandle,
127 | IotTsensorCallback_t xCallback,
128 | void * pvUserContext );
129 |
130 | /**
131 | * @brief iot_tsensor_enable is used to enable the temperature sensor
132 | * to start reading the temperature and trigger thresholds (if any were set and supported)
133 | *
134 | * @param[in] xTsensorHandle Handle to tsensor driver returned in
135 | * iot_tsensor_open
136 | *
137 | * @return
138 | * - IOT_TSENSOR_SUCCESS on success
139 | * - IOT_TSENSOR_INVALID_VALUE if xTsensorHandle is NULL.
140 | */
141 | int32_t iot_tsensor_enable( IotTsensorHandle_t const xTsensorHandle );
142 |
143 | /**
144 | * @brief iot_tsensor_disable is used to disable the temperature sensor
145 | * which stops monitoring the temperature.
146 | *
147 | * @param[in] xTsensorHandle Handle to tsensor driver returned in
148 | * iot_tsensor_open
149 | *
150 | * @return
151 | * - IOT_TSENSOR_SUCCESS on success
152 | * - IOT_TSENSOR_INVALID_VALUE if xTsensorHandle is NULL.
153 | */
154 | int32_t iot_tsensor_disable( IotTsensorHandle_t const xTsensorHandle );
155 |
156 | /**
157 | * @brief iot_tsensor_get_temp is used to get the current temperature
158 | * read from the sensor.
159 | *
160 | * @param[in] xTsensorHandle handle to tsensor driver returned in
161 | * iot_tsensor_open
162 | * @param[out] plTemp temperature read from the sensor.
163 | *
164 | * @return
165 | * - IOT_TSENSOR_SUCCESS on success
166 | * - IOT_TSENSOR_INVALID_VALUE if
167 | * - xTsensorHandle is NULL
168 | * - lTemp is NULL
169 | * - IOT_TSENSOR_DISABLED if tsensor instance has been disabled with call to iot_tsensor_disable().
170 | * - IOT_TSENSOR_GET_TEMP_FAILED if error occurred reading the temperature.
171 | */
172 | int32_t iot_tsensor_get_temp( IotTsensorHandle_t const xTsensorHandle,
173 | int32_t * plTemp );
174 |
175 | /**
176 | * @brief iot_tsensor_ioctl is used to set tsensor configuration
177 | * and tsensor properties like minimum threshold, maximum threshold value, etc.
178 | * Supported IOCTL requests are defined in aws_hal_Tsensor_Ioctl_Request_t
179 | *
180 | * @param[in] xTsensorHandle handle to tsensor driver returned in
181 | * iot_tsensor_open
182 | * @param[in] xRequest configuration request.
183 | * @param[in,out] pvBuffer buffer holding tsensor set and get values.
184 | *
185 | * @return
186 | * - IOT_TSENSOR_SUCCESS on success
187 | * - IOT_TSENSOR_INVALID_VALUE
188 | * - xTsensorHandle is NULL
189 | * - xRequest is invalid
190 | * - pvBuffer is NULL (excluding eTsensorPerformCalibration)
191 | * - IOT_TSENSOR_CLOSED if instance not in open state.
192 | * - IOT_TSENSOR_DISABLED if tsensor instance has been disabled with call to iot_tsensor_disable().
193 | * - IOT_TSENSOR_GET_TEMP_FAILED if error occurred reading the temperature.
194 | * - IOT_TSENSOR_SET_FAILED if set threshold operation failed.
195 | * - IOT_TSENSOR_NOT_SUPPORTED valid if xRequest feature not supported.
196 | * @note: If eTsensorSetMinThreshold or eTsensorSetMaxThreshold ioctl is supported, then the
197 | * corresponding eTsensorGetMinThreshold and eTsensorGetMaxThreshold must also be supported.
198 | */
199 | int32_t iot_tsensor_ioctl( IotTsensorHandle_t const xTsensorHandle,
200 | IotTsensorIoctlRequest_t xRequest,
201 | void * const pvBuffer );
202 |
203 | /**
204 | * @brief iot_tsensor_close is used to de-initialize Tsensor.
205 | *
206 | * @param[in] xTsensorHandle handle to tsensor driver returned in
207 | * iot_tsensor_open
208 | *
209 | * @return
210 | * - IOT_TSENSOR_SUCCESS on success
211 | * - IOT_TSENSOR_INVALID_VALUE if
212 | * - xTensorHandle is NULL
213 | * - not in open state (already closed)
214 | */
215 | int32_t iot_tsensor_close( IotTsensorHandle_t const xTsensorHandle );
216 |
217 |
218 | /**
219 | * @}
220 | */
221 | /* end of group iot_tsensor */
222 |
223 | #endif /* ifndef _IOT_TSENSOR_H_ */
224 |
--------------------------------------------------------------------------------
/manifest.yml:
--------------------------------------------------------------------------------
1 | name: "common-io-basic"
2 | version: "v1.0.0"
3 | description: |
4 | "Common IO - basic: Hardware Abstraction Layers for basic IO devices.\n"
5 | license: "MIT"
--------------------------------------------------------------------------------
/test/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws/common-io-basic/4cc5c90df9d70dd6cb86ec73736fdcbe6bfaec16/test/.DS_Store
--------------------------------------------------------------------------------
/test/iot_test_common_io.c:
--------------------------------------------------------------------------------
1 | /*
2 | * FreeRTOS Common IO V0.1.3
3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 | *
5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | * this software and associated documentation files (the "Software"), to deal in
7 | * the Software without restriction, including without limitation the rights to
8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | * the Software, and to permit persons to whom the Software is furnished to do so,
10 | * subject to the following conditions:
11 | *
12 | * The above copyright notice and this permission notice shall be included in all
13 | * copies or substantial portions of the Software.
14 | *
15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 | *
22 | * http://aws.amazon.com/freertos
23 | * http://www.FreeRTOS.org
24 | */
25 |
26 | /* Test framework includes. */
27 | #include "unity_fixture.h"
28 |
29 | #include "iot_test_common_io_internal.h"
30 |
31 | /* Define Test Group. */
32 | TEST_GROUP( Common_IO );
33 |
34 | /*-----------------------------------------------------------*/
35 |
36 | /**
37 | * @brief Setup function called before each test in this group is executed.
38 | */
39 | TEST_SETUP( Common_IO )
40 | {
41 | }
42 |
43 | /*-----------------------------------------------------------*/
44 |
45 | /**
46 | * @brief Tear down function called after each test in this group is executed.
47 | */
48 | TEST_TEAR_DOWN( Common_IO )
49 | {
50 | }
51 |
52 | /**
53 | * @brief Function to define which tests to execute as part of this group.
54 | */
55 | TEST_GROUP_RUNNER( Common_IO )
56 | {
57 | size_t i = 0;
58 |
59 | #ifdef IOT_TEST_COMMON_IO_PERFCOUNTER_SUPPORTED
60 | for( i = 0; i < IOT_TEST_COMMON_IO_PERFCOUNTER_SUPPORTED; i++ )
61 | {
62 | SET_TEST_IOT_PERFCOUNTER_CONFIG( i );
63 | RUN_TEST_GROUP( TEST_IOT_PERFCOUNTER );
64 | }
65 | #endif
66 |
67 | /* These already used loop back tests which require minimum of two pins */
68 | #ifdef IOT_TEST_COMMON_IO_GPIO_SUPPORTED
69 | for( i = 1; i < IOT_TEST_COMMON_IO_GPIO_SUPPORTED; i++ )
70 | {
71 | SET_TEST_IOT_GPIO_CONFIG( i );
72 | RUN_TEST_GROUP( TEST_IOT_GPIO )
73 | }
74 | #endif
75 |
76 | #ifdef IOT_TEST_COMMON_IO_UART_SUPPORTED
77 | for( i = 0; i < IOT_TEST_COMMON_IO_UART_SUPPORTED; i++ )
78 | {
79 | SET_TEST_IOT_UART_CONFIG( i );
80 | RUN_TEST_GROUP( TEST_IOT_UART );
81 | }
82 | #endif
83 |
84 | #ifdef IOT_TEST_COMMON_IO_I2C_SUPPORTED
85 | for( i = 0; i < IOT_TEST_COMMON_IO_I2C_SUPPORTED; i++ )
86 | {
87 | SET_TEST_IOT_I2C_CONFIG( i );
88 | RUN_TEST_GROUP( TEST_IOT_I2C );
89 | }
90 | #endif
91 |
92 | #ifdef IOT_TEST_COMMON_IO_SPI_SUPPORTED
93 | for( i = 0; i < IOT_TEST_COMMON_IO_SPI_SUPPORTED; i++ )
94 | {
95 | SET_TEST_IOT_SPI_CONFIG( i );
96 | RUN_TEST_GROUP( TEST_IOT_SPI );
97 | }
98 | #endif
99 |
100 | #ifdef IOT_TEST_COMMON_IO_WATCHDOG_SUPPORTED
101 | for( i = 0; i < IOT_TEST_COMMON_IO_WATCHDOG_SUPPORTED; i++ )
102 | {
103 | SET_TEST_IOT_WATCHDOG_CONFIG( i );
104 | RUN_TEST_GROUP( TEST_IOT_WATCHDOG );
105 | }
106 | #endif
107 |
108 | #ifdef IOT_TEST_COMMON_IO_RTC_SUPPORTED
109 | for( i = 0; i < IOT_TEST_COMMON_IO_RTC_SUPPORTED; i++ )
110 | {
111 | SET_TEST_IOT_RTC_CONFIG( i );
112 | RUN_TEST_GROUP( TEST_IOT_RTC );
113 | }
114 | #endif
115 |
116 | #ifdef IOT_TEST_COMMON_IO_RESET_SUPPORTED
117 | for( i = 0; i < IOT_TEST_COMMON_IO_RESET_SUPPORTED; i++ )
118 | {
119 | SET_TEST_IOT_RESET_CONFIG( i );
120 | RUN_TEST_GROUP( TEST_IOT_RESET );
121 | }
122 | #endif
123 |
124 | #ifdef IOT_TEST_COMMON_IO_TIMER_SUPPORTED
125 | for( i = 0; i < IOT_TEST_COMMON_IO_TIMER_SUPPORTED; i++ )
126 | {
127 | SET_TEST_IOT_TIMER_CONFIG( i );
128 | RUN_TEST_GROUP( TEST_IOT_TIMER );
129 | }
130 | #endif
131 |
132 | #ifdef IOT_TEST_COMMON_IO_FLASH_SUPPORTED
133 | for( i = 0; i < IOT_TEST_COMMON_IO_FLASH_SUPPORTED; i++ )
134 | {
135 | SET_TEST_IOT_FLASH_CONFIG( i );
136 | RUN_TEST_GROUP( TEST_IOT_FLASH );
137 | }
138 | #endif
139 |
140 | #ifdef IOT_TEST_COMMON_IO_ADC_SUPPORTED
141 | for( i = 0; i < IOT_TEST_COMMON_IO_ADC_SUPPORTED; i++ )
142 | {
143 | SET_TEST_IOT_ADC_CONFIG( i );
144 | RUN_TEST_GROUP( TEST_IOT_ADC );
145 | }
146 | #endif
147 |
148 | #ifdef IOT_TEST_COMMON_IO_PWM_SUPPORTED
149 | for( i = 0; i < IOT_TEST_COMMON_IO_PWM_SUPPORTED; i++ )
150 | {
151 | SET_TEST_IOT_PWM_CONFIG( i );
152 | RUN_TEST_GROUP( TEST_IOT_PWM );
153 | }
154 | #endif
155 |
156 | #ifdef IOT_TEST_COMMON_IO_I2S_SUPPORTED
157 | for( i = 0; i < IOT_TEST_COMMON_IO_I2S_SUPPORTED; i++ )
158 | {
159 | SET_TEST_IOT_I2S_CONFIG( i );
160 | RUN_TEST_GROUP( TEST_IOT_I2S );
161 | }
162 | #endif
163 |
164 | #ifdef IOT_TEST_COMMON_IO_EFUSE_SUPPORTED
165 | for( i = 0; i < IOT_TEST_COMMON_IO_EFUSE_SUPPORTED; i++ )
166 | {
167 | SET_TEST_IOT_EFUSE_CONFIG( i );
168 | RUN_TEST_GROUP( TEST_IOT_EFUSE );
169 | }
170 | #endif
171 |
172 | #ifdef IOT_TEST_COMMON_IO_SDIO_SUPPORTED
173 | for( i = 0; i < IOT_TEST_COMMON_IO_SDIO_SUPPORTED; i++ )
174 | {
175 | SET_TEST_IOT_SDIO_CONFIG( i );
176 | RUN_TEST_GROUP( TEST_IOT_SDIO );
177 | }
178 | #endif
179 |
180 | #ifdef IOT_TEST_COMMON_IO_TEMP_SENSOR_SUPPORTED
181 | for( i = 0; i < IOT_TEST_COMMON_IO_TEMP_SENSOR_SUPPORTED; i++ )
182 | {
183 | SET_TEST_IOT_TEMP_SENSOR_CONFIG( i );
184 | RUN_TEST_GROUP( TEST_IOT_TSENSOR );
185 | }
186 | #endif
187 |
188 | #ifdef IOT_TEST_COMMON_IO_POWER_SUPPORTED
189 | for( i = 0; i < IOT_TEST_COMMON_IO_POWER_SUPPORTED; i++ )
190 | {
191 | SET_TEST_IOT_POWER_CONFIG( i );
192 | RUN_TEST_GROUP( TEST_IOT_POWER );
193 | }
194 | #endif
195 |
196 | #ifdef IOT_TEST_COMMON_IO_USB_DEVICE_SUPPORTED
197 | for( i = 0; i < IOT_TEST_COMMON_IO_USB_DEVICE_SUPPORTED; i++ )
198 | {
199 | SET_TEST_IOT_USB_DEVICE_CONFIG( i );
200 | /* No tests currently. */
201 | }
202 | #endif
203 | }
204 |
--------------------------------------------------------------------------------
/test/test_iot_battery.c:
--------------------------------------------------------------------------------
1 | /*
2 | * FreeRTOS Common IO V0.1.3
3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 | *
5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | * this software and associated documentation files (the "Software"), to deal in
7 | * the Software without restriction, including without limitation the rights to
8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | * the Software, and to permit persons to whom the Software is furnished to do so,
10 | * subject to the following conditions:
11 | *
12 | * The above copyright notice and this permission notice shall be included in all
13 | * copies or substantial portions of the Software.
14 | *
15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 | *
22 | * http://aws.amazon.com/freertos
23 | * http://www.FreeRTOS.org
24 | */
25 |
26 | /*******************************************************************************
27 | * @file test_iot_battery.c
28 | * @brief Functional Unit Test - BATTERY
29 | *******************************************************************************
30 | */
31 |
32 | /* Test includes */
33 | #include "unity.h"
34 | #include "unity_fixture.h"
35 |
36 | /* Driver includes */
37 | #include "iot_battery.h"
38 |
39 | #include "FreeRTOS.h"
40 | #include "semphr.h"
41 | #include "task.h"
42 |
43 | /*-----------------------------------------------------------*/
44 |
45 | /*-----------------------------------------------------------*/
46 |
47 | /*-----------------------------------------------------------*/
48 | /** Static globals */
49 | /*-----------------------------------------------------------*/
50 |
51 |
52 | /*-----------------------------------------------------------*/
53 |
54 | /* Define Test Group. */
55 | TEST_GROUP( TEST_IOT_BATTERY );
56 |
57 | /*-----------------------------------------------------------*/
58 |
59 | /**
60 | * @brief Setup function called before each test in this group is executed.
61 | */
62 | TEST_SETUP( TEST_IOT_BATTERY )
63 | {
64 | }
65 |
66 | /*-----------------------------------------------------------*/
67 |
68 | /**
69 | * @brief Tear down function called after each test in this group is executed.
70 | */
71 | TEST_TEAR_DOWN( TEST_IOT_BATTERY )
72 | {
73 | }
74 |
75 | /*-----------------------------------------------------------*/
76 |
77 | /**
78 | * @brief Function to define which tests to execute as part of this group.
79 | */
80 | TEST_GROUP_RUNNER( TEST_IOT_BATTERY )
81 | {
82 | RUN_TEST_CASE( TEST_IOT_BATTERY, AFQP_IotBatteryOpenClose );
83 | RUN_TEST_CASE( TEST_IOT_BATTERY, AFQP_IotBatteryVoltage );
84 | RUN_TEST_CASE( TEST_IOT_BATTERY, AFQP_IotBatteryLevel );
85 | RUN_TEST_CASE( TEST_IOT_BATTERY, AFQP_IotBatteryCapacity );
86 | RUN_TEST_CASE( TEST_IOT_BATTERY, AFQP_IotBatteryVoltageFuzz );
87 | RUN_TEST_CASE( TEST_IOT_BATTERY, AFQP_IotBatteryLevelFuzz );
88 | RUN_TEST_CASE( TEST_IOT_BATTERY, AFQP_IotBatteryCapacityFuzz );
89 | }
90 |
91 | /*-----------------------------------------------------------*/
92 |
93 | /**
94 | * @brief Test Function to test iot_battery_open and iot_battery_close.
95 | *
96 | */
97 | TEST( TEST_IOT_BATTERY, AFQP_IotBatteryOpenClose )
98 | {
99 | IotBatteryHandle_t xBatteryHandle;
100 | int32_t lRetVal;
101 |
102 | /* Open battery to initialize hardware. */
103 | xBatteryHandle = iot_battery_open( 0 );
104 | TEST_ASSERT_NOT_EQUAL( NULL, xBatteryHandle );
105 |
106 | /* Open battery to initialize hardware. */
107 | lRetVal = iot_battery_close( xBatteryHandle );
108 | TEST_ASSERT_EQUAL( IOT_BATTERY_SUCCESS, lRetVal );
109 | }
110 |
111 | /**
112 | * @brief Test Function to test iot_battery_voltage.
113 | *
114 | */
115 | TEST( TEST_IOT_BATTERY, AFQP_IotBatteryVoltage )
116 | {
117 | IotBatteryHandle_t xBatteryHandle;
118 | int32_t lRetVal;
119 | uint16_t usVoltage;
120 |
121 | /* Open battery to initialize hardware. */
122 | xBatteryHandle = iot_battery_open( 0 );
123 | TEST_ASSERT_NOT_EQUAL( NULL, xBatteryHandle );
124 |
125 | /* Get the battery voltage */
126 | lRetVal = iot_battery_voltage( xBatteryHandle, &usVoltage );
127 |
128 | if( lRetVal != IOT_BATTERY_FUNCTION_NOT_SUPPORTED )
129 | {
130 | TEST_ASSERT_EQUAL( IOT_BATTERY_SUCCESS, lRetVal );
131 | TEST_ASSERT_GREATER_THAN_UINT32( 0, usVoltage );
132 | }
133 |
134 | /* Close battery interface */
135 | lRetVal = iot_battery_close( xBatteryHandle );
136 | TEST_ASSERT_EQUAL( IOT_BATTERY_SUCCESS, lRetVal );
137 | }
138 |
139 | /**
140 | * @brief Test Function to test iot_battery_level.
141 | *
142 | */
143 | TEST( TEST_IOT_BATTERY, AFQP_IotBatteryLevel )
144 | {
145 | IotBatteryHandle_t xBatteryHandle;
146 | int32_t lRetVal;
147 | uint8_t ucLevel;
148 |
149 | /* Open battery to initialize hardware. */
150 | xBatteryHandle = iot_battery_open( 0 );
151 | TEST_ASSERT_NOT_EQUAL( NULL, xBatteryHandle );
152 |
153 | /* Get the battery level */
154 | lRetVal = iot_battery_chargeLevel( xBatteryHandle, &ucLevel );
155 |
156 | if( lRetVal != IOT_BATTERY_FUNCTION_NOT_SUPPORTED )
157 | {
158 | TEST_ASSERT_EQUAL( IOT_BATTERY_SUCCESS, lRetVal );
159 | TEST_ASSERT_GREATER_THAN_UINT32( 0, ucLevel );
160 | }
161 |
162 | lRetVal = iot_battery_close( xBatteryHandle );
163 | TEST_ASSERT_EQUAL( IOT_BATTERY_SUCCESS, lRetVal );
164 | }
165 |
166 | /**
167 | * @brief Test Function to test iot_battery_capacity.
168 | *
169 | */
170 | TEST( TEST_IOT_BATTERY, AFQP_IotBatteryCapacity )
171 | {
172 | IotBatteryHandle_t xBatteryHandle;
173 | int32_t lRetVal;
174 | uint8_t ucCapacity;
175 |
176 | /* Open battery to initialize hardware. */
177 | xBatteryHandle = iot_battery_open( 0 );
178 | TEST_ASSERT_NOT_EQUAL( NULL, xBatteryHandle );
179 |
180 | /* Get the battery capacity */
181 | lRetVal = iot_battery_capacity( xBatteryHandle, &ucCapacity );
182 |
183 | if( lRetVal != IOT_BATTERY_FUNCTION_NOT_SUPPORTED )
184 | {
185 | TEST_ASSERT_EQUAL( IOT_BATTERY_SUCCESS, lRetVal );
186 | TEST_ASSERT_GREATER_THAN_UINT32( 0, ucCapacity );
187 | }
188 |
189 | lRetVal = iot_battery_close( xBatteryHandle );
190 | TEST_ASSERT_EQUAL( IOT_BATTERY_SUCCESS, lRetVal );
191 | }
192 |
193 | /**
194 | * @brief Test Function to test fuzzing iot_battery_voltage.
195 | *
196 | */
197 | TEST( TEST_IOT_BATTERY, AFQP_IotBatteryVoltageFuzz )
198 | {
199 | IotBatteryHandle_t xBatteryHandle;
200 | int32_t lRetVal;
201 | uint16_t usVoltage;
202 |
203 | /* Open battery to initialize hardware. */
204 | xBatteryHandle = iot_battery_open( 0 );
205 | TEST_ASSERT_NOT_EQUAL( NULL, xBatteryHandle );
206 |
207 | /* read voltage with NULL handle*/
208 | lRetVal = iot_battery_voltage( NULL, &usVoltage );
209 | TEST_ASSERT_EQUAL( IOT_BATTERY_INVALID_VALUE, lRetVal );
210 |
211 | /* read voltage with valid handle null buffer*/
212 | lRetVal = iot_battery_voltage( xBatteryHandle, NULL );
213 | TEST_ASSERT_EQUAL( IOT_BATTERY_INVALID_VALUE, lRetVal );
214 |
215 | /* Close battery interface */
216 | lRetVal = iot_battery_close( xBatteryHandle );
217 | TEST_ASSERT_EQUAL( IOT_BATTERY_SUCCESS, lRetVal );
218 | }
219 |
220 | /**
221 | * @brief Test Function to test fuzzing iot_battery_level.
222 | *
223 | */
224 | TEST( TEST_IOT_BATTERY, AFQP_IotBatteryLevelFuzz )
225 | {
226 | IotBatteryHandle_t xBatteryHandle;
227 | int32_t lRetVal;
228 | uint8_t ucLevel;
229 |
230 | /* Open battery to initialize hardware. */
231 | xBatteryHandle = iot_battery_open( 0 );
232 | TEST_ASSERT_NOT_EQUAL( NULL, xBatteryHandle );
233 |
234 | /* read charge level with NULL handle*/
235 | lRetVal = iot_battery_chargeLevel( NULL, &ucLevel );
236 | TEST_ASSERT_EQUAL( IOT_BATTERY_INVALID_VALUE, lRetVal );
237 |
238 | /* read charge level with valid handle, null buffer*/
239 | lRetVal = iot_battery_chargeLevel( xBatteryHandle, NULL );
240 | TEST_ASSERT_EQUAL( IOT_BATTERY_INVALID_VALUE, lRetVal );
241 |
242 | lRetVal = iot_battery_close( xBatteryHandle );
243 | TEST_ASSERT_EQUAL( IOT_BATTERY_SUCCESS, lRetVal );
244 | }
245 |
246 | /**
247 | * @brief Test Function to test fuzzing iot_battery_capacity.
248 | *
249 | */
250 | TEST( TEST_IOT_BATTERY, AFQP_IotBatteryCapacityFuzz )
251 | {
252 | IotBatteryHandle_t xBatteryHandle;
253 | int32_t lRetVal;
254 | uint8_t ucCapacity;
255 |
256 | /* Open battery to initialize hardware. */
257 | xBatteryHandle = iot_battery_open( 0 );
258 | TEST_ASSERT_NOT_EQUAL( NULL, xBatteryHandle );
259 |
260 | /* read capacity with NULL handle*/
261 | lRetVal = iot_battery_capacity( NULL, &ucCapacity );
262 | TEST_ASSERT_EQUAL( IOT_BATTERY_INVALID_VALUE, lRetVal );
263 |
264 | /* read capacity with valid handle, null buffer*/
265 | lRetVal = iot_battery_capacity( xBatteryHandle, NULL );
266 | TEST_ASSERT_EQUAL( IOT_BATTERY_INVALID_VALUE, lRetVal );
267 |
268 | lRetVal = iot_battery_close( xBatteryHandle );
269 | TEST_ASSERT_EQUAL( IOT_BATTERY_SUCCESS, lRetVal );
270 | }
271 |
--------------------------------------------------------------------------------
/test/test_iot_efuse.c:
--------------------------------------------------------------------------------
1 | /*
2 | * FreeRTOS Common IO V0.1.3
3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 | *
5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | * this software and associated documentation files (the "Software"), to deal in
7 | * the Software without restriction, including without limitation the rights to
8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | * the Software, and to permit persons to whom the Software is furnished to do so,
10 | * subject to the following conditions:
11 | *
12 | * The above copyright notice and this permission notice shall be included in all
13 | * copies or substantial portions of the Software.
14 | *
15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 | *
22 | * http://aws.amazon.com/freertos
23 | * http://www.FreeRTOS.org
24 | */
25 |
26 | /*******************************************************************************
27 | * @file test_iot_efuse.c
28 | * @brief Functional Unit Test - EFUSE
29 | *******************************************************************************
30 | */
31 |
32 | /* Test includes */
33 | #include "unity.h"
34 | #include "unity_fixture.h"
35 |
36 | /* Driver includes */
37 | #include "iot_efuse.h"
38 |
39 | #include "FreeRTOS.h"
40 | #include "semphr.h"
41 | #include "task.h"
42 |
43 | /*-----------------------------------------------------------*/
44 |
45 | /*-----------------------------------------------------------*/
46 |
47 | /* Globals values which can be overwritten by the test
48 | * framework invoking these tests */
49 | /*-----------------------------------------------------------*/
50 | uint32_t ultestIotEfuse16BitWordValidIdx = 151; /**< A valid 16-bit word fuse index. */
51 | uint32_t ultestIotEfuse16BitWordInvalidIdx = 159; /**< An invalid 16-bit word fuse index. */
52 | uint16_t ustestIotEfuse16BitWordWriteVal = 0x5a5a; /**< test value to write into a 16-bit efuse word */
53 | uint32_t ultestIotEfuse32BitWordValidIdx = 159; /**< A valid 32-bit word fuse index. */
54 | uint32_t ultestIotEfuse32BitWordInvalidIdx = 151; /**< An invalid 32-bit word fuse index. */
55 | uint32_t ultestIotEfuse32BitWordWriteVal = 0x5a5a5a5a; /**< test value to write into a 32-bit efuse word */
56 |
57 |
58 | /*-----------------------------------------------------------*/
59 | /** Static globals */
60 | /*-----------------------------------------------------------*/
61 |
62 |
63 | /*-----------------------------------------------------------*/
64 |
65 | /* Define Test Group. */
66 | TEST_GROUP( TEST_IOT_EFUSE );
67 |
68 | /*-----------------------------------------------------------*/
69 |
70 | /**
71 | * @brief Setup function called before each test in this group is executed.
72 | */
73 | TEST_SETUP( TEST_IOT_EFUSE )
74 | {
75 | }
76 |
77 | /*-----------------------------------------------------------*/
78 |
79 | /**
80 | * @brief Tear down function called after each test in this group is executed.
81 | */
82 | TEST_TEAR_DOWN( TEST_IOT_EFUSE )
83 | {
84 | }
85 |
86 | /*-----------------------------------------------------------*/
87 |
88 | /**
89 | * @brief Function to define which tests to execute as part of this group.
90 | */
91 | TEST_GROUP_RUNNER( TEST_IOT_EFUSE )
92 | {
93 | RUN_TEST_CASE( TEST_IOT_EFUSE, AFQP_IotEfuseOpenClose );
94 | RUN_TEST_CASE( TEST_IOT_EFUSE, AFQP_IotEfuseWriteRead32BitWord );
95 | RUN_TEST_CASE( TEST_IOT_EFUSE, AFQP_IotEfuseWriteRead16BitWord );
96 | }
97 |
98 | /*-----------------------------------------------------------*/
99 |
100 | /**
101 | * @brief Test Function to test iot_efuse_open and iot_efuse_close.
102 | *
103 | */
104 | TEST( TEST_IOT_EFUSE, AFQP_IotEfuseOpenClose )
105 | {
106 | IotEfuseHandle_t xEfuseHandle = NULL;
107 | IotEfuseHandle_t xEfuseHandle2 = NULL;
108 | int32_t lRetVal;
109 |
110 | /* Open efuse to initialize hardware. */
111 | xEfuseHandle = iot_efuse_open();
112 | TEST_ASSERT_NOT_EQUAL( NULL, xEfuseHandle );
113 |
114 | /* Open again should get NULL. */
115 | xEfuseHandle2 = iot_efuse_open();
116 | TEST_ASSERT_EQUAL( NULL, xEfuseHandle2 );
117 |
118 | /* Close efuse to deinit hardware. */
119 | lRetVal = iot_efuse_close( xEfuseHandle );
120 | TEST_ASSERT_EQUAL( IOT_EFUSE_SUCCESS, lRetVal );
121 |
122 | /* Close again should get IOT_EFUSE_INVALID_VALUE */
123 | lRetVal = iot_efuse_close( xEfuseHandle );
124 | TEST_ASSERT_EQUAL( IOT_EFUSE_INVALID_VALUE, lRetVal );
125 | }
126 |
127 | /**
128 | * @brief Test Function to test iot_efuse_write_32bit_word()
129 | * iot_efuse_read_32bit_word().
130 | *
131 | */
132 | TEST( TEST_IOT_EFUSE, AFQP_IotEfuseWriteRead32BitWord )
133 | {
134 | IotEfuseHandle_t xEfuseHandle = NULL;
135 | int32_t lRetVal;
136 | uint32_t ulInvalidIndex = ultestIotEfuse32BitWordInvalidIdx;
137 | uint32_t ulValidIndex = ultestIotEfuse32BitWordValidIdx;
138 | uint32_t ulWriteVal = ultestIotEfuse32BitWordWriteVal;
139 | uint32_t ulReadVal;
140 |
141 | /* Write to 32-bit wide efuse word using a NULL handle */
142 | lRetVal = iot_efuse_write_32bit_word( xEfuseHandle, ulValidIndex, ulWriteVal );
143 |
144 | if( lRetVal != IOT_EFUSE_FUNCTION_NOT_SUPPORTED )
145 | {
146 | TEST_ASSERT_EQUAL( IOT_EFUSE_INVALID_VALUE, lRetVal );
147 | }
148 |
149 | /* Read a 32-bit wide efuse word using a NULL handle */
150 | lRetVal = iot_efuse_read_32bit_word( xEfuseHandle, ulValidIndex, ( uint32_t * ) &ulReadVal );
151 |
152 | if( lRetVal != IOT_EFUSE_FUNCTION_NOT_SUPPORTED )
153 | {
154 | TEST_ASSERT_EQUAL( IOT_EFUSE_INVALID_VALUE, lRetVal );
155 | }
156 |
157 | /* Open efuse to initialize hardware. */
158 | xEfuseHandle = iot_efuse_open();
159 | TEST_ASSERT_NOT_EQUAL( NULL, xEfuseHandle );
160 |
161 | /* Write to 32-bit wide efuse word using an invalid index */
162 | lRetVal = iot_efuse_write_32bit_word( xEfuseHandle, ulInvalidIndex, ulWriteVal );
163 |
164 | if( lRetVal != IOT_EFUSE_FUNCTION_NOT_SUPPORTED )
165 | {
166 | TEST_ASSERT_EQUAL( IOT_EFUSE_INVALID_VALUE, lRetVal );
167 | }
168 |
169 | /* Read a 32-bit wide efuse word using an invalid index */
170 | lRetVal = iot_efuse_read_32bit_word( xEfuseHandle, ulInvalidIndex, ( uint32_t * ) &ulReadVal );
171 |
172 | if( lRetVal != IOT_EFUSE_FUNCTION_NOT_SUPPORTED )
173 | {
174 | TEST_ASSERT_EQUAL( IOT_EFUSE_INVALID_VALUE, lRetVal );
175 | }
176 |
177 | /* Write a 32-bit wide efuse word using a valid index */
178 | lRetVal = iot_efuse_write_32bit_word( xEfuseHandle, ulValidIndex, ulWriteVal );
179 |
180 | if( lRetVal != IOT_EFUSE_FUNCTION_NOT_SUPPORTED )
181 | {
182 | TEST_ASSERT_EQUAL( IOT_EFUSE_SUCCESS, lRetVal );
183 | }
184 |
185 | /* Read back to check it value is written correctly */
186 | lRetVal = iot_efuse_read_32bit_word( xEfuseHandle, ulValidIndex, ( uint32_t * ) &ulReadVal );
187 |
188 | if( lRetVal != IOT_EFUSE_FUNCTION_NOT_SUPPORTED )
189 | {
190 | TEST_ASSERT_EQUAL( IOT_EFUSE_SUCCESS, lRetVal );
191 | TEST_ASSERT_EQUAL( ulWriteVal, ulReadVal );
192 | }
193 |
194 | /* Read a 32-bit wide efuse word using a NULL receive buffer */
195 | lRetVal = iot_efuse_read_32bit_word( xEfuseHandle, ulValidIndex, NULL );
196 |
197 | if( lRetVal != IOT_EFUSE_FUNCTION_NOT_SUPPORTED )
198 | {
199 | TEST_ASSERT_EQUAL( IOT_EFUSE_INVALID_VALUE, lRetVal );
200 | }
201 |
202 | lRetVal = iot_efuse_close( xEfuseHandle );
203 | TEST_ASSERT_EQUAL( IOT_EFUSE_SUCCESS, lRetVal );
204 | }
205 |
206 |
207 | /**
208 | * @brief Test Function to test iot_efuse_write_16bit_word()
209 | * and iot_efuse_read_16bit_word().
210 | *
211 | */
212 | TEST( TEST_IOT_EFUSE, AFQP_IotEfuseWriteRead16BitWord )
213 | {
214 | IotEfuseHandle_t xEfuseHandle = NULL;
215 | int32_t lRetVal;
216 | uint32_t ulInvalidIndex = ultestIotEfuse16BitWordInvalidIdx;
217 | uint32_t ulValidIndex = ultestIotEfuse16BitWordValidIdx;
218 | uint16_t usWriteVal = ustestIotEfuse16BitWordWriteVal;
219 | uint16_t ulReadVal;
220 |
221 | /* Write to 16-bit wide efuse word using a NULL handle*/
222 | lRetVal = iot_efuse_write_16bit_word( xEfuseHandle, ulValidIndex, usWriteVal );
223 |
224 | if( lRetVal != IOT_EFUSE_FUNCTION_NOT_SUPPORTED )
225 | {
226 | TEST_ASSERT_EQUAL( IOT_EFUSE_INVALID_VALUE, lRetVal );
227 | }
228 |
229 | /* Read a 16-bit wide efuse word using a NULL handle */
230 | lRetVal = iot_efuse_read_16bit_word( xEfuseHandle, ulValidIndex, ( uint16_t * ) &ulReadVal );
231 |
232 | if( lRetVal != IOT_EFUSE_FUNCTION_NOT_SUPPORTED )
233 | {
234 | TEST_ASSERT_EQUAL( IOT_EFUSE_INVALID_VALUE, lRetVal );
235 | }
236 |
237 | /* Open efuse to initialize hardware. */
238 | xEfuseHandle = iot_efuse_open();
239 | TEST_ASSERT_NOT_EQUAL( NULL, xEfuseHandle );
240 |
241 | /* Write to 16-bit wide efuse word using an invalid index */
242 | lRetVal = iot_efuse_write_16bit_word( xEfuseHandle, ulInvalidIndex, usWriteVal );
243 |
244 | if( lRetVal != IOT_EFUSE_FUNCTION_NOT_SUPPORTED )
245 | {
246 | TEST_ASSERT_EQUAL( IOT_EFUSE_INVALID_VALUE, lRetVal );
247 | }
248 |
249 | /* Read a 16-bit wide efuse word using an invalid index */
250 | lRetVal = iot_efuse_read_16bit_word( xEfuseHandle, ulInvalidIndex, ( uint16_t * ) &ulReadVal );
251 |
252 | if( lRetVal != IOT_EFUSE_FUNCTION_NOT_SUPPORTED )
253 | {
254 | TEST_ASSERT_EQUAL( IOT_EFUSE_INVALID_VALUE, lRetVal );
255 | }
256 |
257 | /* Write a 16-bit wide efuse word using a valid index */
258 | lRetVal = iot_efuse_write_16bit_word( xEfuseHandle, ulValidIndex, usWriteVal );
259 |
260 | if( lRetVal != IOT_EFUSE_FUNCTION_NOT_SUPPORTED )
261 | {
262 | TEST_ASSERT_EQUAL( IOT_EFUSE_SUCCESS, lRetVal );
263 | }
264 |
265 | /* Read back to check it value is written correctly */
266 | lRetVal = iot_efuse_read_16bit_word( xEfuseHandle, ulValidIndex, ( uint16_t * ) &ulReadVal );
267 |
268 | if( lRetVal != IOT_EFUSE_FUNCTION_NOT_SUPPORTED )
269 | {
270 | TEST_ASSERT_EQUAL( IOT_EFUSE_SUCCESS, lRetVal );
271 | TEST_ASSERT_EQUAL( usWriteVal, ulReadVal );
272 | }
273 |
274 | /* Read a 16-bit wide efuse word using a NULL receive buffer */
275 | lRetVal = iot_efuse_read_16bit_word( xEfuseHandle, ulValidIndex, NULL );
276 |
277 | if( lRetVal != IOT_EFUSE_FUNCTION_NOT_SUPPORTED )
278 | {
279 | TEST_ASSERT_EQUAL( IOT_EFUSE_INVALID_VALUE, lRetVal );
280 | }
281 |
282 | /* Close efuse interface */
283 | lRetVal = iot_efuse_close( xEfuseHandle );
284 | TEST_ASSERT_EQUAL( IOT_EFUSE_SUCCESS, lRetVal );
285 | }
286 |
--------------------------------------------------------------------------------
/test/test_iot_perfcounter.c:
--------------------------------------------------------------------------------
1 | /*
2 | * FreeRTOS Common IO V0.1.3
3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 | *
5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | * this software and associated documentation files (the "Software"), to deal in
7 | * the Software without restriction, including without limitation the rights to
8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | * the Software, and to permit persons to whom the Software is furnished to do so,
10 | * subject to the following conditions:
11 | *
12 | * The above copyright notice and this permission notice shall be included in all
13 | * copies or substantial portions of the Software.
14 | *
15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 | *
22 | * http://aws.amazon.com/freertos
23 | * http://www.FreeRTOS.org
24 | */
25 |
26 | /*******************************************************************************
27 | * @file iot_test_perfcounter.c
28 | * @brief Functional Unit Test - Performance Counter
29 | *******************************************************************************
30 | */
31 |
32 | /* Test includes */
33 | #include "unity.h"
34 | #include "unity_fixture.h"
35 |
36 | /* Driver includes */
37 | #include "iot_perfcounter.h"
38 |
39 | /* FreeRTOS include. */
40 | #include "FreeRTOS.h"
41 | #include "task.h"
42 |
43 | /*-----------------------------------------------------------*/
44 |
45 | #define testIotPERFCOUNTER_INT_MAX_VALUE ( 0xFFFFFFFFUL )
46 |
47 | #define testIotPERFCOUNTER_DEFAULT_DELAY_TIME_MS ( 1 )
48 | #define testIotPERFCOUNTER_SEC_TO_MSEC ( 1000 )
49 |
50 | /*-----------------------------------------------------------*/
51 |
52 | /* Define Test Group. */
53 | TEST_GROUP( TEST_IOT_PERFCOUNTER );
54 |
55 | /*-----------------------------------------------------------*/
56 |
57 | /**
58 | * @brief Setup function called before each test in this group is executed.
59 | */
60 | TEST_SETUP( TEST_IOT_PERFCOUNTER )
61 | {
62 | }
63 |
64 | /*-----------------------------------------------------------*/
65 |
66 | /**
67 | * @brief Tear down function called after each test in this group is executed.
68 | */
69 | TEST_TEAR_DOWN( TEST_IOT_PERFCOUNTER )
70 | {
71 | }
72 |
73 | /*-----------------------------------------------------------*/
74 |
75 | /**
76 | * @brief Function to define which tests to execute as part of this group.
77 | */
78 | TEST_GROUP_RUNNER( TEST_IOT_PERFCOUNTER )
79 | {
80 | RUN_TEST_CASE( TEST_IOT_PERFCOUNTER, AFQP_IotPerfCounterGetValue );
81 | RUN_TEST_CASE( TEST_IOT_PERFCOUNTER, AFQP_IotPerfCounterGetValueWithDelay );
82 | }
83 |
84 | /*-----------------------------------------------------------*/
85 |
86 | /**
87 | * @brief Test Function to test iot_perfcounter values
88 | *
89 | */
90 | TEST( TEST_IOT_PERFCOUNTER, AFQP_IotPerfCounterGetValue )
91 | {
92 | uint64_t ullCounter1 = 0, ullCounter2 = 0;
93 |
94 | /* Open the interface. */
95 | iot_perfcounter_open();
96 |
97 | /* Get the value from perf counter. */
98 | ullCounter1 = iot_perfcounter_get_value();
99 |
100 | /* This is always true. Attempting to space out two reads. */
101 | TEST_ASSERT( ullCounter1 >= 0 );
102 |
103 | /* Get the value from perf counter again. */
104 | ullCounter2 = iot_perfcounter_get_value();
105 |
106 | /* For reference, to overflow 64-bit with clock running at say GHz, it takes years.
107 | * By when it's probably better to fail the test if it takes that long.
108 | * Two reads can be equal, depending on what frequency the counter is running at.
109 | */
110 | TEST_ASSERT_MESSAGE( ullCounter2 >= ullCounter1, "The value from the second read is expected to be no smaller than the first." );
111 |
112 | /* Close the interface. */
113 | iot_perfcounter_close();
114 | }
115 |
116 | /*-----------------------------------------------------------*/
117 |
118 | /**
119 | * @brief Test Function to test iot_perfcounter values with delay inserted.
120 | * The delay is used to calculate the next read of perfcounter shall be no smaller than
121 | * the delay inserted.
122 | *
123 | */
124 | TEST( TEST_IOT_PERFCOUNTER, AFQP_IotPerfCounterGetValueWithDelay )
125 | {
126 | uint64_t ullCounter1 = 0, ullCounter2 = 0;
127 | uint32_t ulFreq = 0;
128 |
129 | /* Open the interface. */
130 | iot_perfcounter_open();
131 |
132 | /* Get counter frequency. */
133 | ulFreq = iot_perfcounter_get_frequency();
134 |
135 | /* Get the value from perf counter. */
136 | ullCounter1 = iot_perfcounter_get_value();
137 |
138 | /* Delay for AT MOST 1 msec. (Assume no interrupt.) */
139 | vTaskDelay( testIotPERFCOUNTER_DEFAULT_DELAY_TIME_MS / portTICK_PERIOD_MS );
140 |
141 | /* Get the value from perf counter again. */
142 | ullCounter2 = iot_perfcounter_get_value();
143 |
144 | /* Test has been running for a while now. Reading should not be zero.
145 | * If fails --
146 | * 1. Timer might not have been started correctly.
147 | * 2. Timer frequency might not be realistic.
148 | */
149 | TEST_ASSERT_MESSAGE( ( ullCounter1 > 0 && ullCounter2 > 0 ), "Perf counter value did not increase." );
150 |
151 | /* Frequency value should never be zero in any counter configuration. */
152 | TEST_ASSERT_MESSAGE( ( ulFreq > 0 ), "Counter frequency is expected to be not zero." );
153 |
154 | /* Convert time elapsed to counter cycles. The result can be zero, if counter is running at unrealistic frequency.
155 | * Keeping below line for understanding purpose.
156 | */
157 | /* ullCounterThreshold = ( uint64_t ) testIotPERFCOUNTER_DEFAULT_DELAY_TIME_MS * ulFreq / testIotPERFCOUNTER_SEC_TO_MSEC; */
158 |
159 | /* We can never have a golden assertion here, since --
160 | * 1, if no interrupt during vTaskDelay(), this is always true: ullCounter2 <= ullCounter1 + ullCounterThreshold
161 | * 2, if interrupt during vTaskDelay(), this is true: ullCounter2 >= ullCounter1 + ullCounterThreshold
162 | * The only thing we know for sure is ullCounter2 > ullCounter1. And for most of the time
163 | * ullCounter2 ~= ullCounter1 + ullCounterThreshold.
164 | *
165 | * Note that vTaskDelay() delays AT MOST time specified. This is to meet scheduling deadline.
166 | *
167 | * Overflow 64-bit is not taken into consideration for similar reason.
168 | * See comment in previous test.
169 | */
170 | TEST_ASSERT_MESSAGE( ( ullCounter2 > ullCounter1 ), "Expected the value from the second read to be larger than the first. " );
171 |
172 | /* Close the interface. */
173 | iot_perfcounter_close();
174 | }
175 |
--------------------------------------------------------------------------------
/test/test_iot_reset.c:
--------------------------------------------------------------------------------
1 | /*
2 | * FreeRTOS Common IO V0.1.3
3 | * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 | *
5 | * Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | * this software and associated documentation files (the "Software"), to deal in
7 | * the Software without restriction, including without limitation the rights to
8 | * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | * the Software, and to permit persons to whom the Software is furnished to do so,
10 | * subject to the following conditions:
11 | *
12 | * The above copyright notice and this permission notice shall be included in all
13 | * copies or substantial portions of the Software.
14 | *
15 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 | * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 | * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 | * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 | * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 | *
22 | * http://aws.amazon.com/freertos
23 | * http://www.FreeRTOS.org
24 | */
25 |
26 | /*******************************************************************************
27 | * @file iot_test_reset.c
28 | * @brief Functional Unit Test - TIMER
29 | *******************************************************************************
30 | */
31 |
32 | /* Test includes */
33 | #include "unity.h"
34 | #include "unity_fixture.h"
35 |
36 | /* Driver includes */
37 | #include "iot_reset.h"
38 |
39 | #include "FreeRTOS.h"
40 | #include "task.h"
41 |
42 |
43 | /*-----------------------------------------------------------*/
44 |
45 | /* Define Test Group. */
46 | TEST_GROUP( TEST_IOT_RESET );
47 |
48 | /*-----------------------------------------------------------*/
49 |
50 | /**
51 | * @brief Setup function called before each test in this group is executed.
52 | */
53 | TEST_SETUP( TEST_IOT_RESET )
54 | {
55 | }
56 |
57 | /*-----------------------------------------------------------*/
58 |
59 | /**
60 | * @brief Tear down function called after each test in this group is executed.
61 | */
62 | TEST_TEAR_DOWN( TEST_IOT_RESET )
63 | {
64 | }
65 |
66 | /*-----------------------------------------------------------*/
67 |
68 | /**
69 | * @brief Function to define which tests to execute as part of this group.
70 | */
71 | TEST_GROUP_RUNNER( TEST_IOT_RESET )
72 | {
73 | RUN_TEST_CASE( TEST_IOT_RESET, AFQP_IotResetShutdown );
74 | RUN_TEST_CASE( TEST_IOT_RESET, AFQP_IotResetRebootZero );
75 | RUN_TEST_CASE( TEST_IOT_RESET, AFQP_IotResetRebootNonZero );
76 | }
77 |
78 | /*-----------------------------------------------------------*/
79 |
80 | /**
81 | * @brief Test Function to test iot_reset_shutdown
82 | *
83 | */
84 | TEST( TEST_IOT_RESET, AFQP_IotResetShutdown )
85 | {
86 | int32_t lRetVal;
87 |
88 | /* Shutdown the device.
89 | * Only return on error */
90 | lRetVal = iot_reset_shutdown();
91 |
92 | /* If shutdown is supported then
93 | * execution shall not reach here */
94 | if( lRetVal != IOT_RESET_FUNCTION_NOT_SUPPORTED )
95 | {
96 | TEST_ASSERT_NOT_EQUAL( NULL, NULL );
97 | }
98 | }
99 |
100 | /*-----------------------------------------------------------*/
101 |
102 | /**
103 | * @brief Test Function to test iot_reset_reboot with
104 | * Zero coldBootFlag
105 | *
106 | */
107 | TEST( TEST_IOT_RESET, AFQP_IotResetRebootZero )
108 | {
109 | uint8_t coldBootFlag = 0;
110 |
111 | /* Reboot the device. No returning */
112 | iot_reset_reboot( coldBootFlag );
113 |
114 | /* Execution does not reach here */
115 | TEST_ASSERT_NOT_EQUAL( NULL, NULL );
116 | }
117 |
118 | /*-----------------------------------------------------------*/
119 |
120 | /**
121 | * @brief Test Function to test iot_reset_reboot with
122 | * Non-Zero coldBootFlag
123 | *
124 | */
125 | TEST( TEST_IOT_RESET, AFQP_IotResetRebootNonZero )
126 | {
127 | uint8_t coldBootFlag = -1;
128 |
129 | /* Reboot the device. No returning */
130 | iot_reset_reboot( coldBootFlag );
131 |
132 | /* Execution does not reach here */
133 | TEST_ASSERT_NOT_EQUAL( NULL, NULL );
134 | }
135 |
--------------------------------------------------------------------------------
/test/test_scripts/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws/common-io-basic/4cc5c90df9d70dd6cb86ec73736fdcbe6bfaec16/test/test_scripts/.DS_Store
--------------------------------------------------------------------------------
/test/test_scripts/adc/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws/common-io-basic/4cc5c90df9d70dd6cb86ec73736fdcbe6bfaec16/test/test_scripts/adc/__init__.py
--------------------------------------------------------------------------------
/test/test_scripts/adc/test_iot_adc_rp3.py:
--------------------------------------------------------------------------------
1 | # FreeRTOS Common IO V0.1.2
2 | # Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | #
4 | # Permission is hereby granted, free of charge, to any person obtaining a copy of
5 | # this software and associated documentation files (the "Software"), to deal in
6 | # the Software without restriction, including without limitation the rights to
7 | # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
8 | # the Software, and to permit persons to whom the Software is furnished to do so,
9 | # subject to the following conditions:
10 | #
11 | # The above copyright notice and this permission notice shall be included in all
12 | # copies or substantial portions of the Software.
13 | #
14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
16 | # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
17 | # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
18 | # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
19 | # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20 | #
21 | # http://aws.amazon.com/freertos
22 | # http://www.FreeRTOS.org
23 |
24 |
25 | import smbus
26 | import argparse
27 |
28 | MAX_OUT = int((1.8 / 3.3) * 0xFFF)
29 |
30 | if __name__ == "__main__":
31 | parser = argparse.ArgumentParser()
32 | parser.add_argument('d', nargs='?', type=int, default=0, help='dac input')
33 | args = parser.parse_args()
34 |
35 | data = args.d & 0xFFF
36 |
37 | if data > MAX_OUT:
38 | data = MAX_OUT
39 |
40 | # I2C channel 1 is connected to the GPIO pins
41 | channel = 1
42 |
43 | # MCP4725 on adafruit board defaults to address 0x62
44 | address = 0x62
45 |
46 | # Register addresses (with "normal mode" power-down bits)
47 | reg_write_dac = 0x40
48 |
49 | bus = smbus.SMBus(channel)
50 |
51 | # 12 bits data is aligned into two bytes with bit 11 as msb i.e. bit 11-4 in the byte 3,
52 | # bit 3-0 in the byte 4 up four bits.
53 | lo4 = (data & 0xF) << 4
54 | hi8 = data >> 4
55 |
56 | bus.write_i2c_block_data(address, reg_write_dac, [hi8, lo4])
57 |
--------------------------------------------------------------------------------
/test/test_scripts/adc/test_iot_adc_test.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | # FreeRTOS Common IO V0.1.2
4 | # Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 | #
6 | # Permission is hereby granted, free of charge, to any person obtaining a copy of
7 | # this software and associated documentation files (the "Software"), to deal in
8 | # the Software without restriction, including without limitation the rights to
9 | # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
10 | # the Software, and to permit persons to whom the Software is furnished to do so,
11 | # subject to the following conditions:
12 | #
13 | # The above copyright notice and this permission notice shall be included in all
14 | # copies or substantial portions of the Software.
15 | #
16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
18 | # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
19 | # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
20 | # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 | # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 | #
23 | # http://aws.amazon.com/freertos
24 | # http://www.FreeRTOS.org
25 |
26 |
27 | import serial
28 | import csv
29 | from time import sleep
30 | import argparse
31 | import os, sys
32 | import re
33 |
34 | scriptdir = os.path.dirname(os.path.realpath(__file__))
35 | parentdir = os.path.dirname(scriptdir)
36 | if parentdir not in sys.path:
37 | print("Script Dir: %s" % scriptdir)
38 | print("Parent Dir: %s" % parentdir)
39 | sys.path.append(parentdir)
40 | from test_iot_test_template import test_template
41 |
42 |
43 | class TestAdcAssisted(test_template):
44 | """
45 | Test class for adc tests.
46 | """
47 | ADC_READING_ERR = 20
48 |
49 | def __init__(self, serial, ip, login, pwd, csv_handler):
50 | self._func_list = [self.test_IotAdcPrintReadSample]
51 |
52 | self._serial = serial
53 | self._ip = ip
54 | self._login = login
55 | self._pwd = pwd
56 | self._cr = csv_handler
57 |
58 | # print("Please input platform ADC reference voltage:")
59 | # self.platform_ref_voltage = float(input())
60 | self.platform_ref_voltage = 1.8
61 |
62 | shell_script = "%s/test_iot_runonPI_adc.sh" % scriptdir
63 |
64 | def test_IotAdcPrintReadSample(self):
65 | """
66 | Test body of adc reading test. It takes average of 5 adc samples and compares with the converted dac input based
67 | on the reference voltage. Return pass if error is smaller than defined error.
68 | :return: 'Pass' or 'Fail'
69 | """
70 | dac_inputs = ['500', '1000', '1500', '2000']
71 | dac_ref_voltage = 3.3
72 |
73 | for di in dac_inputs:
74 | self.run_shell_script(" ".join([self.shell_script, self._ip, self._login, self._pwd, di]))
75 | adc = []
76 |
77 | # Read five times for each dac input
78 | for j in range(0, 5):
79 |
80 | self._serial.reset_input_buffer()
81 |
82 | cmd = "iot_tests test 7 1"
83 | self._serial.write('\r\n'.encode('utf-8'))
84 |
85 | self._serial.write(cmd.encode('utf-8'))
86 |
87 | self._serial.write('\r\n'.encode('utf-8'))
88 |
89 | res = self._serial.read_until(terminator=serial.to_bytes([ord(c) for c in 'Ignored '])).decode('utf-8')
90 |
91 | for x in re.sub('\r', '', res).split('\n'):
92 | # Look for the line with ADC reading.
93 | if x.find('Expected -1') != -1:
94 | adc.append(int(x.split()[-1]))
95 | break
96 | # Wait serial to flush out.
97 | sleep(0.2)
98 |
99 | # Derive theoretical reading on the device under test based on ref voltage.
100 | ideal_adc_reading = int(di) / self.platform_ref_voltage * dac_ref_voltage
101 |
102 | # Compare the average reading with the ideal reading
103 | if abs(ideal_adc_reading - sum(adc) / len(adc)) > self.ADC_READING_ERR:
104 | print(ideal_adc_reading, sum(adc) / len(adc))
105 | return 'Fail'
106 |
107 | return 'Pass'
108 |
109 |
110 | # unit test
111 | if __name__ == "__main__":
112 | parser = argparse.ArgumentParser()
113 |
114 | parser.add_argument('-i', '--ip', nargs=1, help='ip address of rpi')
115 | parser.add_argument('-l', '--login_name', nargs=1, help='login name of rpi')
116 | parser.add_argument('-s', '--password', nargs=1, help='password of rpi')
117 | parser.add_argument('-p', '--port', nargs=1, help='serial port of connected platform')
118 |
119 | args = parser.parse_args()
120 | print(args.port[0])
121 | try:
122 | serial_port = serial.Serial(port=args.port[0], timeout=5, baudrate=115200)
123 | except Exception as e:
124 | print(e)
125 | exit()
126 |
127 | rpi_ip = args.ip[0]
128 | rpi_login = args.login_name[0]
129 | rpi_pwd = args.password[0]
130 |
131 | with open(scriptdir + '/test_result.csv', 'w', newline='') as csvfile:
132 | field_name = ['test name', 'test result']
133 | writer = csv.DictWriter(csvfile, fieldnames=field_name)
134 | writer.writeheader()
135 | t_handler = TestAdcAssisted(serial_port, rpi_ip, rpi_login, rpi_pwd, writer)
136 | t_handler.auto_run()
137 |
138 | serial_port.close()
139 |
--------------------------------------------------------------------------------
/test/test_scripts/adc/test_iot_runonPI_adc.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | # FreeRTOS Common IO V0.1.2
3 | # Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 | #
5 | # Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | # this software and associated documentation files (the "Software"), to deal in
7 | # the Software without restriction, including without limitation the rights to
8 | # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | # the Software, and to permit persons to whom the Software is furnished to do so,
10 | # subject to the following conditions:
11 | #
12 | # The above copyright notice and this permission notice shall be included in all
13 | # copies or substantial portions of the Software.
14 | #
15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 | # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 | # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 | # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 | # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 | #
22 | # http://aws.amazon.com/freertos
23 | # http://www.FreeRTOS.org
24 |
25 |
26 |
27 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
28 | IP=$1
29 | shift
30 | LOGINID=$1
31 | shift
32 | PASSWD=$1
33 | shift
34 |
35 | if [ "$1" == "-p" ]; then
36 | #Secure copy the test_iot_adc_rp3.py from Host to RP3
37 | sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} "mkdir -p /home/pi/Tests"
38 | sshpass -p ${PASSWD} scp ${DIR}/test_iot_adc_rp3.py ${LOGINID}@${IP}:/home/pi/Tests
39 | elif [ ! -z $1 ]; then
40 | #Set dac output voltage
41 | sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} "python /home/pi/Tests/test_iot_adc_rp3.py $1"
42 | fi
43 |
--------------------------------------------------------------------------------
/test/test_scripts/gpio/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws/common-io-basic/4cc5c90df9d70dd6cb86ec73736fdcbe6bfaec16/test/test_scripts/gpio/__init__.py
--------------------------------------------------------------------------------
/test/test_scripts/gpio/test_iot_gpio_rp3.py:
--------------------------------------------------------------------------------
1 | # FreeRTOS Common IO V0.1.2
2 | # Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | #
4 | # Permission is hereby granted, free of charge, to any person obtaining a copy of
5 | # this software and associated documentation files (the "Software"), to deal in
6 | # the Software without restriction, including without limitation the rights to
7 | # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
8 | # the Software, and to permit persons to whom the Software is furnished to do so,
9 | # subject to the following conditions:
10 | #
11 | # The above copyright notice and this permission notice shall be included in all
12 | # copies or substantial portions of the Software.
13 | #
14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
16 | # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
17 | # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
18 | # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
19 | # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20 | #
21 | # http://aws.amazon.com/freertos
22 | # http://www.FreeRTOS.org
23 |
24 |
25 |
26 | # This script will read the GPIO pin on RP3 and prints the Pin status
27 | import argparse
28 | from gpiozero import LED, Button
29 | from time import sleep
30 | import socket
31 |
32 | HOST = ''
33 | PORT = 50007
34 |
35 | if __name__ == "__main__":
36 |
37 | parser = argparse.ArgumentParser("default is input test")
38 |
39 | parser.add_argument('-o', nargs=1, type=int, metavar='level',
40 | help='set rpi gpio 20 to output mode. level=1: high 0: low')
41 | parser.add_argument('-i', nargs=1, type=int, metavar='pull_up_down',
42 | help='set rpi gpio 21 to input mode. 1: pull up 0: pull down')
43 |
44 | args = parser.parse_args()
45 |
46 | # Check if gpio output or input is requested.
47 | if args.o:
48 | GPIO = 20
49 | socket.setdefaulttimeout(10)
50 | # Create socket server.
51 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
52 | s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
53 | s.bind((HOST, PORT))
54 | s.listen(1)
55 | led = LED(GPIO)
56 | # Set gpio high if platform is performing input high test, otherwise set gpio to low.
57 | if args.o[0] > 0:
58 | led.on()
59 | else:
60 | led.off()
61 | # Start to accept connection from client. It can notify host process, rpi is ready.
62 | conn, addr = s.accept()
63 | # End process until received data from host or time out.
64 | data = conn.recv(1024)
65 | s.close()
66 |
67 | elif args.i:
68 | GPIO = 21
69 | # If platform gpio is push pull high, set RPi gpio as pull down, otherwise pull up.
70 | if args.i[0] > 0:
71 | button = Button(GPIO)
72 | else:
73 | button = Button(GPIO, pull_up=False)
74 | sleep(1)
75 | print(button.is_pressed)
76 |
--------------------------------------------------------------------------------
/test/test_scripts/gpio/test_iot_runonPI_gpio.sh:
--------------------------------------------------------------------------------
1 | #! /bin/bash
2 |
3 | # FreeRTOS Common IO V0.1.2
4 | # Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 | #
6 | # Permission is hereby granted, free of charge, to any person obtaining a copy of
7 | # this software and associated documentation files (the "Software"), to deal in
8 | # the Software without restriction, including without limitation the rights to
9 | # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
10 | # the Software, and to permit persons to whom the Software is furnished to do so,
11 | # subject to the following conditions:
12 | #
13 | # The above copyright notice and this permission notice shall be included in all
14 | # copies or substantial portions of the Software.
15 | #
16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
18 | # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
19 | # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
20 | # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 | # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 | #
23 | # http://aws.amazon.com/freertos
24 | # http://www.FreeRTOS.org
25 |
26 |
27 |
28 | # This is a shell script to secure copy the GPIO_RP3 to RP3
29 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
30 | IP=$1
31 | shift
32 | LOGINID=$1
33 | shift
34 | PASSWD=$1
35 | shift
36 | if [ "$1" == "-p" ]; then
37 | #Secure copy the test_iot_gpio_rp3.py from Host to RP3
38 | sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} "mkdir -p /home/pi/Tests"
39 | sshpass -p ${PASSWD} scp ${DIR}/test_iot_gpio_rp3.py ${LOGINID}@${IP}:/home/pi/Tests/
40 | elif [ "$1" == "-w" ]; then
41 |
42 | #Open a SSH connection to RP3 and run the test_iot_gpio_rp3.py to read the GPIO pin status
43 | sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} "python /home/pi/Tests/test_iot_gpio_rp3.py -i $2 > /home/pi/Tests/gpio_rpi_res.txt"
44 |
45 | #Copy the GPIO pin status to host for validation
46 | sshpass -p ${PASSWD} scp ${LOGINID}@${IP}:/home/pi/Tests/gpio_rpi_res.txt ${DIR}
47 |
48 | elif [ "$1" == "-r" ]; then
49 | #Open a SSH connection to RP3 and run the test_iot_gpio_rp3.py to set the GPIO pin output
50 | sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} "python /home/pi/Tests/test_iot_gpio_rp3.py -o $2"
51 |
52 | elif [ "$1" == "-c" ]; then
53 | sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} "rm /home/pi/Tests/gpio_rpi_res.txt"
54 | fi
55 |
56 | exit 0
57 |
--------------------------------------------------------------------------------
/test/test_scripts/i2c_master/test_iot_i2c_master_rp3.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | # FreeRTOS Common IO V0.1.2
4 | # Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 | #
6 | # Permission is hereby granted, free of charge, to any person obtaining a copy of
7 | # this software and associated documentation files (the "Software"), to deal in
8 | # the Software without restriction, including without limitation the rights to
9 | # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
10 | # the Software, and to permit persons to whom the Software is furnished to do so,
11 | # subject to the following conditions:
12 | #
13 | # The above copyright notice and this permission notice shall be included in all
14 | # copies or substantial portions of the Software.
15 | #
16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
18 | # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
19 | # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
20 | # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 | # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 | #
23 | # http://aws.amazon.com/freertos
24 | # http://www.FreeRTOS.org
25 |
26 |
27 | import time
28 | import pigpio
29 | import random
30 | import socket
31 |
32 | SDA = 18
33 | SCL = 19
34 |
35 | I2C_ADDR = 9
36 | HOST = ''
37 | PORT = 50007
38 |
39 |
40 | def i2c(id, tick):
41 | global pi, wr_bytes, rd_bytes
42 |
43 | s, b, d = pi.bsc_i2c(0x9)
44 | if b > 1:
45 | wr_bytes = d
46 | elif b == 1:
47 | if d[0] == 0x80:
48 | rd_bytes = [random.randrange(0, 128) for i in range(0, 16)]
49 | s, b, d = pi.bsc_i2c(0x9, ''.join('{}'.format(chr(b)) for b in rd_bytes))
50 |
51 |
52 | if __name__ == "__main__":
53 |
54 | pi = pigpio.pi()
55 |
56 | if not pi.connected:
57 | exit()
58 |
59 | # Add pull-ups in case external pull-ups haven't been added
60 | pi.set_pull_up_down(SDA, pigpio.PUD_UP)
61 | pi.set_pull_up_down(SCL, pigpio.PUD_UP)
62 |
63 | socket.setdefaulttimeout(10)
64 | # Create socket server.
65 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
66 | s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
67 | s.bind((HOST, PORT))
68 | s.listen(1)
69 |
70 | wr_bytes, rd_bytes = ([] for i in range(2))
71 | # Respond to BSC slave activity
72 | e = pi.event_callback(pigpio.EVENT_BSC, i2c)
73 | # Configure BSC as I2C slave
74 | st, b, d = pi.bsc_i2c(0x9)
75 |
76 | conn, addr = s.accept()
77 |
78 | # Stay in the process until host request to end.
79 | time_out = 30
80 | while time_out > 0:
81 | try:
82 | req = conn.recv(1024)
83 | except:
84 | print("No request from host.")
85 | break
86 |
87 | if len(req) > 0 and req[0] == 's':
88 | if wr_bytes != []:
89 | conn.sendall(wr_bytes)
90 | elif rd_bytes != []:
91 | conn.sendall(bytearray(rd_bytes))
92 | else:
93 | break
94 |
95 | e.cancel()
96 |
97 | pi.bsc_i2c(0) # Disable BSC peripheral
98 | pi.stop()
99 |
100 | s.close()
101 |
--------------------------------------------------------------------------------
/test/test_scripts/i2c_master/test_iot_i2c_master_test.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | # FreeRTOS Common IO V0.1.2
4 | # Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 | #
6 | # Permission is hereby granted, free of charge, to any person obtaining a copy of
7 | # this software and associated documentation files (the "Software"), to deal in
8 | # the Software without restriction, including without limitation the rights to
9 | # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
10 | # the Software, and to permit persons to whom the Software is furnished to do so,
11 | # subject to the following conditions:
12 | #
13 | # The above copyright notice and this permission notice shall be included in all
14 | # copies or substantial portions of the Software.
15 | #
16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
18 | # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
19 | # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
20 | # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 | # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 | #
23 | # http://aws.amazon.com/freertos
24 | # http://www.FreeRTOS.org
25 |
26 |
27 | import serial
28 | from time import sleep
29 | import csv
30 | import os, sys
31 | import argparse
32 | import threading
33 | import socket
34 | import re
35 |
36 | scriptdir = os.path.dirname(os.path.realpath(__file__))
37 | parentdir = os.path.dirname(scriptdir)
38 | if parentdir not in sys.path:
39 | print("Script Dir: %s" % scriptdir)
40 | print("Parent Dir: %s" % parentdir)
41 | sys.path.append(parentdir)
42 | from test_iot_test_template import test_template
43 |
44 |
45 |
46 | class TestI2cMasterAssisted(test_template):
47 | """
48 | Test class for i2c master tests.
49 | """
50 |
51 | def __init__(self, serial, ip, login, pwd, csv_handler):
52 | self._func_list = [self.test_IotI2CWriteSyncAssisted,
53 | self.test_IotI2CWriteAsyncAssisted,
54 | self.test_IotI2CReadSyncAssisted,
55 | self.test_IotI2CReadAsyncAssisted
56 | ]
57 |
58 | self._serial = serial
59 | self._ip = ip
60 | self._login = login
61 | self._pwd = pwd
62 | self._cr = csv_handler
63 |
64 | shell_script = "%s/test_iot_runonPI_i2c_master.sh" % scriptdir
65 | port = 50007
66 |
67 | def i2c_write_test(self, cmd):
68 | """
69 | Test body of write test.
70 | :param cmd: iot test cmd
71 | :return:
72 | """
73 | t_shell = threading.Thread(target=self.run_shell_script,
74 | args=(" ".join([self.shell_script, self._ip, self._login, self._pwd, '-s']),))
75 | t_shell.start()
76 |
77 | socket.setdefaulttimeout(10)
78 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
79 | time_out = 10
80 | # Wait until connection with the process on rpi is established.
81 | while s.connect_ex((self._ip, self.port)) != 0 and time_out > 0:
82 | time_out -= 1
83 | sleep(1)
84 | if time_out == 0:
85 | print("Socket connection cannot be established")
86 | s.close()
87 | return "Fail"
88 |
89 | self._serial.reset_input_buffer()
90 | self._serial.write('\r\n'.encode('utf-8'))
91 |
92 | self._serial.write(cmd.encode('utf-8'))
93 |
94 | self._serial.write('\r\n'.encode('utf-8'))
95 |
96 | res = self._serial.read_until(terminator=serial.to_bytes([ord(c) for c in 'Ignored '])).decode('utf-8')
97 |
98 | w_bytes = []
99 | for x in re.sub(r'\r', '', res).split('\n'):
100 | if x.find('IGNORE') != -1:
101 | w_bytes = [s for s in x.split(',') if len(s) == 2]
102 | break
103 |
104 | # Retrieve bytes read by rpi.
105 | s.sendall(b's')
106 | try:
107 | r_bytes = s.recv(1024)
108 | except:
109 | print("No data received from rpi.\n", repr(res))
110 | s.close()
111 | return 'Fail'
112 | r_bytes = ["{:02X}".format(b) for b in r_bytes]
113 | # End process on the rpi.
114 | s.sendall(b'E')
115 |
116 | t_shell.join()
117 | s.close()
118 |
119 | # Compare read and write bytes.
120 | if self.compare_host_dut_result(r_bytes, w_bytes) == -1:
121 | print(repr(res))
122 | return "Fail"
123 |
124 | return 'Pass'
125 |
126 | def test_IotI2CWriteSyncAssisted(self):
127 | return self.i2c_write_test("iot_tests test 11 1")
128 |
129 | def test_IotI2CWriteAsyncAssisted(self):
130 | return self.i2c_write_test("iot_tests test 11 2")
131 |
132 | def i2c_read_test(self, cmd):
133 | """
134 | Test body for read test. The i2c slave callback function in the rpi library is only called after i2c stop. The
135 | register address cannot be read by rpi before restart so the data to send can only be loaded to rpi fifo after
136 | stop. As a result, the first read from host is always the data loaded from last request or some random value if
137 | fifo is never loaded before.
138 | The solution with the current rpi library is to read rpi twice. Compare the second dut read data with the first
139 | rpi send data.
140 | :param cmd: iot test cmd
141 | :return:
142 | """
143 | w_bytes, r_bytes = ([] for i in range(2))
144 |
145 | t_shell = threading.Thread(target=self.run_shell_script,
146 | args=(" ".join([self.shell_script, self._ip, self._login, self._pwd, '-s']),))
147 | t_shell.start()
148 |
149 | socket.setdefaulttimeout(10)
150 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
151 | time_out = 10
152 | # Wait until connection with the process on rpi is established.
153 | while s.connect_ex((self._ip, self.port)) != 0 and time_out > 0:
154 | time_out -= 1
155 | sleep(1)
156 | if time_out == 0:
157 | print("Socket connection cannot be established")
158 | s.close()
159 | return "Fail"
160 |
161 | for i in range(2):
162 | self._serial.reset_input_buffer()
163 | self._serial.write('\r\n'.encode('utf-8'))
164 |
165 | self._serial.write(cmd.encode('utf-8'))
166 |
167 | self._serial.write('\r\n'.encode('utf-8'))
168 |
169 | res = self._serial.read_until(terminator=serial.to_bytes([ord(c) for c in 'Ignored '])).decode('utf-8')
170 |
171 | for x in re.sub(r'\r', '', res).split('\n'):
172 | if x.find('IGNORE') != -1:
173 | r_bytes.append([s for s in x.split(',') if len(s) == 2])
174 | break
175 |
176 | # Retrieve bytes sent by rpi
177 | s.sendall(b's')
178 | try:
179 | data = s.recv(1024)
180 | except:
181 | print("No data from pi")
182 | s.close()
183 | return 'Fail'
184 |
185 | w_bytes.append(["{:02X}".format(b) for b in data])
186 | # Exit if failed to read bytes from DUT.
187 | if len(r_bytes) != i + 1:
188 | print("No data read by DUT.\n", repr(res))
189 | break
190 | # End process on the rpi.
191 | s.sendall(b'E')
192 |
193 | t_shell.join()
194 | s.close()
195 |
196 | if len(r_bytes) != 2 or len(w_bytes) != 2:
197 | print("Write and read different number of bytes.\npi:", w_bytes, "\ndut:", r_bytes)
198 | return 'Fail'
199 |
200 | # Compare read and write bytes.
201 | if self.compare_host_dut_result(w_bytes[0], r_bytes[1]) == -1:
202 | print(repr(res))
203 | return "Fail"
204 |
205 | return 'Pass'
206 |
207 | def test_IotI2CReadSyncAssisted(self):
208 | return self.i2c_read_test("iot_tests test 11 3")
209 |
210 | def test_IotI2CReadAsyncAssisted(self):
211 | return self.i2c_read_test("iot_tests test 11 4")
212 |
213 |
214 | # unit test
215 | if __name__ == "__main__":
216 | parser = argparse.ArgumentParser()
217 |
218 | parser.add_argument('-i', '--ip', nargs=1, default=[''], help='ip address of rpi')
219 | parser.add_argument('-l', '--login_name', nargs=1, default=[''], help='login name of rpi')
220 | parser.add_argument('-s', '--password', nargs=1, default=[''], help='password of rpi')
221 | parser.add_argument('-p', '--port', nargs=1, default=[''], help='serial port of connected platform')
222 |
223 | args = parser.parse_args()
224 |
225 | try:
226 | serial_port = serial.Serial(port=args.port[0], timeout=5)
227 | except Exception as e:
228 | print(e)
229 | exit()
230 |
231 | rpi_ip = args.ip[0]
232 | rpi_login = args.login_name[0]
233 | rpi_pwd = args.password[0]
234 |
235 | with open(scriptdir + 'test_result.csv', 'w', newline='') as csvfile:
236 | field_name = ['test name', 'test result']
237 | writer = csv.DictWriter(csvfile, fieldnames=field_name)
238 | writer.writeheader()
239 | t_handler = TestI2cMasterAssisted(serial_port, rpi_ip, rpi_login, rpi_pwd, writer)
240 | t_handler.auto_run()
241 |
242 | serial_port.close()
243 |
--------------------------------------------------------------------------------
/test/test_scripts/i2c_master/test_iot_runonPI_i2c_master.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # FreeRTOS Common IO V0.1.2
4 | # Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 | #
6 | # Permission is hereby granted, free of charge, to any person obtaining a copy of
7 | # this software and associated documentation files (the "Software"), to deal in
8 | # the Software without restriction, including without limitation the rights to
9 | # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
10 | # the Software, and to permit persons to whom the Software is furnished to do so,
11 | # subject to the following conditions:
12 | #
13 | # The above copyright notice and this permission notice shall be included in all
14 | # copies or substantial portions of the Software.
15 | #
16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
18 | # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
19 | # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
20 | # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 | # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 | #
23 | # http://aws.amazon.com/freertos
24 | # http://www.FreeRTOS.org
25 |
26 |
27 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
28 | IP=$1
29 | shift
30 | LOGINID=$1
31 | shift
32 | PASSWD=$1
33 | shift
34 |
35 | if [ "$1" == "-p" ]; then
36 | #Secure copy the test_iot_adc_rp3.py from Host to RP3
37 | sshpass -p "$PASSWD" ssh "$LOGINID"@"$IP" "mkdir -p /home/pi/Tests"
38 | sshpass -p "$PASSWD" scp ${DIR}/test_iot_i2c_master_rp3.py "$LOGINID"@"$IP":/home/pi/Tests
39 | elif [ "$1" == "-s" ]; then
40 | #Run demon
41 | sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} 'sudo pigpiod -s 1 -b 200'
42 | sleep .1
43 | #Run rpi script
44 | sshpass -p "$PASSWD" ssh "$LOGINID"@"$IP" "python /home/pi/Tests/test_iot_i2c_master_rp3.py"
45 | #Kill demon
46 | sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} "sudo killall pigpiod"
47 | elif [ "$1" == "-c" ]; then
48 | sshpass -p "$PASSWD" ssh "$LOGINID"@"$IP" "rm /home/pi/Tests/i2c_master_res.txt"
49 | fi
--------------------------------------------------------------------------------
/test/test_scripts/pwm/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws/common-io-basic/4cc5c90df9d70dd6cb86ec73736fdcbe6bfaec16/test/test_scripts/pwm/__init__.py
--------------------------------------------------------------------------------
/test/test_scripts/pwm/test_iot_pwm_rp3.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | # FreeRTOS Common IO V0.1.2
4 | # Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 | #
6 | # Permission is hereby granted, free of charge, to any person obtaining a copy of
7 | # this software and associated documentation files (the "Software"), to deal in
8 | # the Software without restriction, including without limitation the rights to
9 | # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
10 | # the Software, and to permit persons to whom the Software is furnished to do so,
11 | # subject to the following conditions:
12 | #
13 | # The above copyright notice and this permission notice shall be included in all
14 | # copies or substantial portions of the Software.
15 | #
16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
18 | # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
19 | # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
20 | # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 | # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 | #
23 | # http://aws.amazon.com/freertos
24 | # http://www.FreeRTOS.org
25 |
26 |
27 | import time
28 | import pigpio
29 | import socket
30 | import threading
31 |
32 | GPIO_R = 4
33 | GPIO_W = 23
34 |
35 | sample_counts = 50
36 | sample_duration = 0.2
37 |
38 | rising_edge = -1
39 | period = -1
40 | high = -1
41 |
42 | HOST = ''
43 | PORT = 50007
44 |
45 | process_end = False
46 |
47 |
48 | def callback_function(gpio, level, tick):
49 | """
50 | Interrrupt call back function triggered by pwm input pulses.
51 | :param gpio: gpio pin num
52 | :param level: gpio level
53 | :param tick: The number of microseconds since boot
54 | :return:
55 | """
56 | if gpio == GPIO_R:
57 | global rising_edge, high, period
58 | if level == 1:
59 | if rising_edge != -1:
60 | period = pigpio.tickDiff(rising_edge, tick)
61 |
62 | rising_edge = tick
63 |
64 | else:
65 | if rising_edge != -1:
66 | high = pigpio.tickDiff(rising_edge, tick)
67 |
68 |
69 | def socket_thread(s):
70 | """
71 | Thread function to monitor socket.
72 | :param s: Socket handler.
73 | :return:
74 | """
75 | global process_end
76 | try:
77 | conn, addr = s.accept()
78 | conn.recv(1024)
79 | except Exception as e:
80 | print(e)
81 | # Notify the main thread to end process.
82 | process_end = True
83 |
84 |
85 | def start_pwm(pi, gpio=23, frequency=1000, duty_cycle=30):
86 | """
87 | Setup gpio and start to generate pwm.
88 | :param pi: pigpio handler
89 | :param gpio: gpio
90 | :param frequency: pwm frequency
91 | :param duty_cycle: pwm duty cycle
92 | :return: wave id
93 | """
94 | if duty_cycle > 100:
95 | duty_cycle = 100
96 |
97 | pi.set_mode(gpio, pigpio.OUTPUT)
98 | # Calculate period in micro seconds.
99 | period = int(1000000.0 / frequency)
100 | # Calculate micro seconds of falling edge.
101 | falling_edge = int(duty_cycle / 100 * period)
102 | # Setup one cycle of pwm.
103 | pi.wave_add_generic([
104 | pigpio.pulse(0, 1 << gpio, 0),
105 | pigpio.pulse(1 << gpio, 0, falling_edge),
106 | pigpio.pulse(0, 1 << gpio, period - falling_edge),
107 | ])
108 | # Start pwm.
109 | wid = pi.wave_create()
110 | pi.wave_send_repeat(wid)
111 |
112 | return wid
113 |
114 |
115 | if __name__ == "__main__":
116 |
117 | pi = pigpio.pi()
118 | pi.set_mode(GPIO_R, pigpio.INPUT)
119 |
120 | callback_handler = pi.callback(GPIO_R, pigpio.EITHER_EDGE, callback_function)
121 |
122 | socket.setdefaulttimeout(10)
123 | # Create socket server.
124 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
125 | s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
126 | s.bind((HOST, PORT))
127 | s.listen(1)
128 | # Start to generate pwm output.
129 | wid = start_pwm(pi, GPIO_W)
130 |
131 | # Create a thread to monitor socket.
132 | t_s = threading.Thread(target=socket_thread, args=(s,))
133 | t_s.start()
134 |
135 | time_out = 100
136 | # Polling pwm input.
137 | while not process_end and time_out > 0:
138 | time.sleep(sample_duration)
139 | # Calculate frequency with period in micro seconds.
140 | frequency = 1000000.0 / period if period > 0 else 0
141 | # Calculate duty cycle.
142 | duty_cycle = 100.0 * high / period if period > 0 else 0
143 |
144 | print("{:.5f} {:.5f}".format(frequency, duty_cycle))
145 | # Reset variables for next round.
146 | rising_edge = period = high = -1
147 | time_out -= 1
148 |
149 | pi.wave_tx_stop()
150 | pi.wave_delete(wid)
151 |
152 | callback_handler.cancel()
153 | pi.stop()
154 | s.close()
155 |
--------------------------------------------------------------------------------
/test/test_scripts/pwm/test_iot_pwm_test.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | # FreeRTOS Common IO V0.1.2
4 | # Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 | #
6 | # Permission is hereby granted, free of charge, to any person obtaining a copy of
7 | # this software and associated documentation files (the "Software"), to deal in
8 | # the Software without restriction, including without limitation the rights to
9 | # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
10 | # the Software, and to permit persons to whom the Software is furnished to do so,
11 | # subject to the following conditions:
12 | #
13 | # The above copyright notice and this permission notice shall be included in all
14 | # copies or substantial portions of the Software.
15 | #
16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
18 | # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
19 | # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
20 | # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 | # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 | #
23 | # http://aws.amazon.com/freertos
24 | # http://www.FreeRTOS.org
25 |
26 |
27 | import serial
28 | import csv
29 | import threading
30 | from time import sleep
31 | import sys
32 | import math
33 | import os
34 | import argparse
35 | import re
36 |
37 | scriptdir = os.path.dirname(os.path.realpath(__file__))
38 | parentdir = os.path.dirname(scriptdir)
39 | if parentdir not in sys.path:
40 | print("Script Dir: %s" % scriptdir)
41 | print("Parent Dir: %s" % parentdir)
42 | sys.path.append(parentdir)
43 | from test_iot_test_template import test_template
44 | import socket
45 |
46 |
47 | class TestPwmAssisted(test_template):
48 | """
49 | Test class for pwm tests.
50 | """
51 | PWM_FREQUENCY = 1000
52 | PWM_DUTYCYCLE = 30
53 | PWM_FREQUENCY_READING_ERR = 3.0
54 | PWM_DUTYCYCLE_READING_ERR = 1.0
55 |
56 | def __init__(self, serial, ip, login, pwd, csv_handler):
57 | self._func_list = [self.test_IotPwmAccuracy]
58 |
59 | self._serial = serial
60 | self._ip = ip
61 | self._login = login
62 | self._pwd = pwd
63 | self._cr = csv_handler
64 |
65 | shell_script = "%s/test_iot_runonPI_pwm.sh" % scriptdir
66 | rpi_output_file = "%s/pwm_rpi_res.txt" % scriptdir
67 | port = 50007
68 |
69 | def test_IotPwmAccuracy(self):
70 | """
71 | Test to verify pwm accuracy. It contains two parts. Platform board generates pwm to RPi and RPi capture it to
72 | verify. RPi samples pwm frequency and duty cycle every 200ms. RPi will also generate the same pwm to complete
73 | the iot test.
74 | :return: 'Pass' or 'Fail'
75 | """
76 | t_shell = threading.Thread(target=self.run_shell_script,
77 | args=(" ".join([self.shell_script, self._ip, self._login, self._pwd]),))
78 | t_shell.start()
79 | # Create a tcp type socket with AF_INET address family.
80 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
81 | time_out = 10
82 | # Wait until connection with the process on rpi is established.
83 | while s.connect_ex((self._ip, self.port)) != 0 and time_out > 0:
84 | time_out -= 1
85 | sleep(1)
86 | if time_out == 0:
87 | print("Socket connection cannot be established")
88 | s.close()
89 | return "Fail"
90 |
91 | self._serial.reset_input_buffer()
92 |
93 | cmd = "iot_tests test 10 3"
94 | self._serial.write('\r\n'.encode('utf-8'))
95 |
96 | self._serial.write(cmd.encode('utf-8'))
97 |
98 | self._serial.write('\r\n'.encode('utf-8'))
99 |
100 | sleep(5)
101 | # End rpi process.
102 | s.send(b'E')
103 |
104 | # wait the script on rpi to finish.
105 | t_shell.join()
106 | s.close()
107 | res = self._serial.read_until(terminator=serial.to_bytes([ord(c) for c in 'Ignored '])).decode('utf-8')
108 |
109 | if re.sub('\r', '', res).find('PASS\n') == -1:
110 | print(sys._getframe().f_code.co_name, ": device under test pwm capture failed")
111 | return 'Fail'
112 |
113 | no_of_correct_freq = 0
114 | with open(self.rpi_output_file, "r") as f:
115 | for line in f:
116 | data = line.split()
117 | # Test whether the read frequency and duty cycle are within the error.
118 | # Consider as valid pwm output, if five concecutive rows are with correct frequency and duty cycle.
119 | if math.fabs(float(data[0]) - self.PWM_FREQUENCY) < self.PWM_FREQUENCY_READING_ERR and math.fabs(
120 | float(data[1]) - self.PWM_DUTYCYCLE) < self.PWM_DUTYCYCLE_READING_ERR:
121 | no_of_correct_freq += 1
122 |
123 | if no_of_correct_freq >= 5:
124 | self.clean()
125 | return 'Pass'
126 | elif no_of_correct_freq > 0:
127 | print(sys._getframe().f_code.co_name, ": device under test pwm output failed")
128 | return 'Fail'
129 |
130 | return 'Fail'
131 |
132 |
133 | # unit test
134 | if __name__ == "__main__":
135 | parser = argparse.ArgumentParser()
136 |
137 | parser.add_argument('-i', '--ip', nargs=1, help='ip address of rpi')
138 | parser.add_argument('-l', '--login_name', nargs=1, help='login name of rpi')
139 | parser.add_argument('-s', '--password', nargs=1, help='password of rpi')
140 | parser.add_argument('-p', '--port', nargs=1, help='serial port of connected platform')
141 |
142 | args = parser.parse_args()
143 |
144 | try:
145 | serial_port = serial.Serial(port=args.port[0], timeout=5, baudrate=115200)
146 | except Exception as e:
147 | print(e)
148 | exit()
149 |
150 | rpi_ip = args.ip[0]
151 | rpi_login = args.login_name[0]
152 | rpi_pwd = args.password[0]
153 |
154 | with open(scriptdir + '/test_result.csv', 'w', newline='') as csvfile:
155 | field_name = ['test name', 'test result']
156 | writer = csv.DictWriter(csvfile, fieldnames=field_name)
157 | writer.writeheader()
158 | t_handler = TestPwmAssisted(serial_port, rpi_ip, rpi_login, rpi_pwd, writer)
159 | t_handler.auto_run()
160 |
161 | serial_port.close()
162 |
--------------------------------------------------------------------------------
/test/test_scripts/pwm/test_iot_runonPI_pwm.sh:
--------------------------------------------------------------------------------
1 | #! /bin/bash
2 |
3 | # FreeRTOS Common IO V0.1.2
4 | # Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 | #
6 | # Permission is hereby granted, free of charge, to any person obtaining a copy of
7 | # this software and associated documentation files (the "Software"), to deal in
8 | # the Software without restriction, including without limitation the rights to
9 | # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
10 | # the Software, and to permit persons to whom the Software is furnished to do so,
11 | # subject to the following conditions:
12 | #
13 | # The above copyright notice and this permission notice shall be included in all
14 | # copies or substantial portions of the Software.
15 | #
16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
18 | # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
19 | # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
20 | # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 | # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 | #
23 | # http://aws.amazon.com/freertos
24 | # http://www.FreeRTOS.org
25 |
26 |
27 |
28 |
29 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
30 | IP=$1
31 | shift
32 | LOGINID=$1
33 | shift
34 | PASSWD=$1
35 | shift
36 |
37 | if [ "$1" == "-p" ]; then
38 | #Secure copy the test_iot_read_PWM.py and test_iot_wave_PWM.py from Host to RP3
39 | sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} "mkdir -p /home/pi/Tests"
40 | sshpass -p ${PASSWD} scp ${DIR}/test_iot_pwm_rp3.py ${LOGINID}@${IP}:/home/pi/Tests
41 | elif [ "$1" == "-c" ]; then
42 | #Delete the result file on rpi
43 | sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} "rm /home/pi/Tests/pwm_rpi_res.txt"
44 | else
45 | #Run demon
46 | sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} 'sudo pigpiod -s 1 -b 200'
47 | #Run two pwm scripts at same time
48 | sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} 'python /home/pi/Tests/test_iot_pwm_rp3.py > /home/pi/Tests/pwm_rpi_res.txt'
49 | #Kill demon
50 | sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} 'sudo killall pigpiod'
51 | #Copy back result
52 | sshpass -p ${PASSWD} scp ${LOGINID}@${IP}:/home/pi/Tests/pwm_rpi_res.txt ${DIR}
53 | fi
54 |
--------------------------------------------------------------------------------
/test/test_scripts/spi_master/test_iot_spi_master_pyb.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # FreeRTOS Common IO V0.1.2
4 | # Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 | #
6 | # Permission is hereby granted, free of charge, to any person obtaining a copy of
7 | # this software and associated documentation files (the "Software"), to deal in
8 | # the Software without restriction, including without limitation the rights to
9 | # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
10 | # the Software, and to permit persons to whom the Software is furnished to do so,
11 | # subject to the following conditions:
12 | #
13 | # The above copyright notice and this permission notice shall be included in all
14 | # copies or substantial portions of the Software.
15 | #
16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
18 | # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
19 | # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
20 | # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 | # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 | #
23 | # http://aws.amazon.com/freertos
24 | # http://www.FreeRTOS.org
25 |
26 |
27 |
28 | if [ "$1" == "-t" ]; then
29 | for sysdevpath in $(find /sys/bus/usb/devices/usb*/ -name dev); do
30 | (
31 | syspath="${sysdevpath%/dev}"
32 | devname="$(udevadm info -q name -p $syspath)"
33 | [[ "$devname" == "bus/"* ]] && continue
34 | eval "$(udevadm info -q property --export -p $syspath)"
35 | [[ (-z "$ID_SERIAL") || ("$ID_SERIAL" != *"MicroPython"*)]] && continue
36 | echo "/dev/$devname"
37 | break
38 | )
39 | done
40 | fi
41 |
--------------------------------------------------------------------------------
/test/test_scripts/test_iot_assisted_tests.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | # FreeRTOS Common IO V0.1.2
4 | # Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 | #
6 | # Permission is hereby granted, free of charge, to any person obtaining a copy of
7 | # this software and associated documentation files (the "Software"), to deal in
8 | # the Software without restriction, including without limitation the rights to
9 | # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
10 | # the Software, and to permit persons to whom the Software is furnished to do so,
11 | # subject to the following conditions:
12 | #
13 | # The above copyright notice and this permission notice shall be included in all
14 | # copies or substantial portions of the Software.
15 | #
16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
18 | # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
19 | # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
20 | # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 | # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 | #
23 | # http://aws.amazon.com/freertos
24 | # http://www.FreeRTOS.org
25 |
26 |
27 |
28 | import csv
29 | import argparse
30 | import serial
31 | from gpio.test_iot_gpio_test import TestGpioAssisted
32 | from pwm.test_iot_pwm_test import TestPwmAssisted
33 | from adc.test_iot_adc_test import TestAdcAssisted
34 | from tsensor.test_iot_tsensor_test import TestTsensorAssisted
35 | from uart.test_iot_uart_test import TestUartAssisted
36 | from spi_master.test_iot_spi_master_test import TestSPIMasterAssisted
37 | import os, sys
38 |
39 | scriptdir = os.path.dirname(os.path.realpath(__file__))
40 | parentdir = os.path.dirname(scriptdir)
41 |
42 | test_class_list = [(TestGpioAssisted, "gpio"),
43 | (TestPwmAssisted, "pwm"),
44 | (TestAdcAssisted, "adc"),
45 | (TestTsensorAssisted, "tsensor"),
46 | (TestUartAssisted, "uart"),
47 | (TestSPIMasterAssisted, "spi_master")
48 | ]
49 |
50 | if __name__ == "__main__":
51 | parser = argparse.ArgumentParser()
52 |
53 | parser.add_argument('-i', '--ip', nargs=1, default=[''], help='ip address of rpi')
54 | parser.add_argument('-l', '--login_name', nargs=1, default=[''], help='login name of rpi')
55 | parser.add_argument('-s', '--password', nargs=1, default=[''], help='password of rpi')
56 | parser.add_argument('-p', '--port', nargs=1, default=[''], help='serial port of connected platform')
57 |
58 | args = parser.parse_args()
59 |
60 | try:
61 | serial_port = serial.Serial(port=args.port[0], timeout=5, baudrate=115200)
62 | except Exception as e:
63 | print(e)
64 | exit()
65 |
66 | rpi_ip = args.ip[0]
67 | rpi_login = args.login_name[0]
68 | rpi_pwd = args.password[0]
69 |
70 | with open(scriptdir+'/test_result.csv', 'w', newline='') as csvfile:
71 | field_name = ['test name', 'test result']
72 | writer = csv.DictWriter(csvfile, fieldnames=field_name)
73 | writer.writeheader()
74 | root_dir = scriptdir
75 | print(scriptdir)
76 | for i in range(0, len(test_class_list)):
77 | print(test_class_list[i][0].__name__)
78 | os.chdir(scriptdir+'/'+test_class_list[i][1])
79 | test_obj = test_class_list[i][0](serial_port, rpi_ip, rpi_login, rpi_pwd, writer)
80 | test_obj.auto_run()
81 | os.chdir(root_dir)
82 | print("****************************")
83 |
84 | serial_port.close()
85 |
--------------------------------------------------------------------------------
/test/test_scripts/test_iot_test_template.py:
--------------------------------------------------------------------------------
1 | # FreeRTOS Common IO V0.1.2
2 | # Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | #
4 | # Permission is hereby granted, free of charge, to any person obtaining a copy of
5 | # this software and associated documentation files (the "Software"), to deal in
6 | # the Software without restriction, including without limitation the rights to
7 | # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
8 | # the Software, and to permit persons to whom the Software is furnished to do so,
9 | # subject to the following conditions:
10 | #
11 | # The above copyright notice and this permission notice shall be included in all
12 | # copies or substantial portions of the Software.
13 | #
14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
16 | # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
17 | # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
18 | # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
19 | # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
20 | #
21 | # http://aws.amazon.com/freertos
22 | # http://www.FreeRTOS.org
23 |
24 |
25 | import subprocess
26 | import os
27 | from abc import ABC, abstractmethod
28 | from datetime import datetime
29 |
30 |
31 | class test_template(ABC):
32 | @abstractmethod
33 | def __init__(self, serial, ip, login, pwd, csv_handler):
34 | self._func_list = []
35 |
36 | self._serial = serial
37 | self._ip = ip
38 | self._login = login
39 | self._pwd = pwd
40 | self._cr = csv_handler
41 |
42 | shell_script = ''
43 | rpi_output_file = ''
44 |
45 | def print_result(self, testcase, result, extra = None):
46 | if extra == None:
47 | extra = "%s %sed" % (testcase, result)
48 | print("%s [INFO] %s 0 %s : %s" % (str(datetime.now()), testcase, result.upper(), extra))
49 | self._cr.writerow({'test name': testcase, 'test result': result})
50 | def auto_run(self):
51 | # print('hardware ready? (y/n)')
52 | # string = str(input())
53 | string = 'y'
54 |
55 | if string == 'y':
56 | skip_test = False
57 | else:
58 | skip_test = True
59 |
60 | if skip_test == True:
61 | for f in self._func_list:
62 | self.print_result(f.__name__, "Skip")
63 | else:
64 | print("tests start")
65 | if self.shell_script:
66 | subprocess.call([self.shell_script, self._ip, self._login, self._pwd, '-p'])
67 | for f in self._func_list:
68 | result = f()
69 | self.print_result(f.__name__, result)
70 |
71 | def run_shell_script(self, cmd):
72 | cmd_l = cmd.split()
73 | subprocess.call(cmd_l)
74 |
75 | def compare_host_dut_result(self, hl, dl):
76 | """
77 | Compare host and dut bytes.
78 | :param hl: a list of host bytes.
79 | :param dl: a list of dut bytes.
80 | :return: -1-unmatch 0-mathced
81 | """
82 | if len(hl) != len(dl) or len(hl) == 0:
83 | print("Host and dut have different number of bytes.\nhost:", hl, "\ndut:", dl)
84 | return -1
85 |
86 | for h, d in zip(hl, dl):
87 | if h != d:
88 | print("Host and dut have different bytes.\nhost:", hl, "\ndut:", dl)
89 | return -1
90 |
91 | return 0
92 |
93 | def clean(self):
94 | if os.path.isfile(self.rpi_output_file):
95 | os.remove(self.rpi_output_file)
96 | self.run_shell_script(" ".join([self.shell_script, self._ip, self._login, self._pwd, '-c']))
97 |
--------------------------------------------------------------------------------
/test/test_scripts/tsensor/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws/common-io-basic/4cc5c90df9d70dd6cb86ec73736fdcbe6bfaec16/test/test_scripts/tsensor/__init__.py
--------------------------------------------------------------------------------
/test/test_scripts/tsensor/test_iot_runonPI_tsensor.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # FreeRTOS Common IO V0.1.2
4 | # Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 | #
6 | # Permission is hereby granted, free of charge, to any person obtaining a copy of
7 | # this software and associated documentation files (the "Software"), to deal in
8 | # the Software without restriction, including without limitation the rights to
9 | # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
10 | # the Software, and to permit persons to whom the Software is furnished to do so,
11 | # subject to the following conditions:
12 | #
13 | # The above copyright notice and this permission notice shall be included in all
14 | # copies or substantial portions of the Software.
15 | #
16 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
18 | # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
19 | # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
20 | # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
21 | # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22 | #
23 | # http://aws.amazon.com/freertos
24 | # http://www.FreeRTOS.org
25 |
26 |
27 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
28 | IP=$1
29 | shift
30 | LOGINID=$1
31 | shift
32 | PASSWD=$1
33 | shift
34 |
35 | if [ "$1" == "-p" ]; then
36 | #Secure copy test script from Host ubuntu to RP3
37 | sshpass -p "${PASSWD}" ssh ${LOGINID}@${IP} "mkdir -p /home/pi/Tests"
38 | sshpass -p "${PASSWD}" scp ${DIR}/test_iot_tsensor_rp3.py ${LOGINID}@${IP}:/home/pi/Tests
39 | elif [ "$1" == "-c" ]; then
40 | #Delete the result file on rpi
41 | sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} "rm /home/pi/Tests/tsensor_rpi_res.txt"
42 | else
43 | sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} "python /home/pi/Tests/test_iot_tsensor_rp3.py > /home/pi/Tests/tsensor_rpi_res.txt"
44 | #Copy back result
45 | sshpass -p ${PASSWD} scp ${LOGINID}@${IP}:/home/pi/Tests/tsensor_rpi_res.txt ${DIR}
46 | fi
47 |
--------------------------------------------------------------------------------
/test/test_scripts/tsensor/test_iot_tsensor_rp3.py:
--------------------------------------------------------------------------------
1 |
2 | # FreeRTOS Common IO V0.1.2
3 | # Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 | #
5 | # Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | # this software and associated documentation files (the "Software"), to deal in
7 | # the Software without restriction, including without limitation the rights to
8 | # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | # the Software, and to permit persons to whom the Software is furnished to do so,
10 | # subject to the following conditions:
11 | #
12 | # The above copyright notice and this permission notice shall be included in all
13 | # copies or substantial portions of the Software.
14 | #
15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 | # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 | # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 | # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 | # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 | #
22 | # http://aws.amazon.com/freertos
23 | # http://www.FreeRTOS.org
24 |
25 |
26 | import smbus
27 |
28 | if __name__ == "__main__":
29 | channel = 1
30 | device_addr = 0x18
31 | ambient_temp_reg = 0x5
32 |
33 | bus = smbus.SMBus(channel)
34 |
35 | data = bus.read_i2c_block_data(device_addr, ambient_temp_reg, 2)
36 |
37 | temp = float((data[0] << 8 | data[1]) & 0xFFF) / 16
38 |
39 | if data[0] & 0x10:
40 | temp -= 256.0
41 |
42 | print(temp)
43 |
--------------------------------------------------------------------------------
/test/test_scripts/tsensor/test_iot_tsensor_test.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # FreeRTOS Common IO V0.1.2
3 | # Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 | #
5 | # Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | # this software and associated documentation files (the "Software"), to deal in
7 | # the Software without restriction, including without limitation the rights to
8 | # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | # the Software, and to permit persons to whom the Software is furnished to do so,
10 | # subject to the following conditions:
11 | #
12 | # The above copyright notice and this permission notice shall be included in all
13 | # copies or substantial portions of the Software.
14 | #
15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 | # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 | # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 | # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 | # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 | #
22 | # http://aws.amazon.com/freertos
23 | # http://www.FreeRTOS.org
24 |
25 | import serial
26 | from time import sleep
27 | import csv
28 | import os, sys
29 | import argparse
30 |
31 | scriptdir = os.path.dirname(os.path.realpath(__file__))
32 | parentdir = os.path.dirname(scriptdir)
33 | if parentdir not in sys.path:
34 | print("Script Dir: %s" % scriptdir)
35 | print("Parent Dir: %s" % parentdir)
36 | sys.path.append(parentdir)
37 | from test_iot_test_template import test_template
38 |
39 |
40 | class TestTsensorAssisted(test_template):
41 | """
42 | Test class for temperature sensor.
43 | """
44 |
45 | def __init__(self, serial, ip, login, pwd, csv_handler):
46 | self._func_list = [self.test_IotTsensorTemp]
47 |
48 | self._serial = serial
49 | self._ip = ip
50 | self._login = login
51 | self._pwd = pwd
52 | self._cr = csv_handler
53 |
54 | shell_script = "%s/test_iot_runonPI_tsensor.sh" % scriptdir
55 | rpi_output_file = "%s/tsensor_rpi_res.txt" % scriptdir
56 |
57 | def test_IotTsensorTemp(self):
58 | """
59 | Test to verify the temperature reading on the device under test board. Five consecutive reading is performed
60 | for both external and on board sensors. Average of five readings is compared.
61 | :return:
62 | """
63 | temp_list = []
64 | ref_temp = 0
65 | sample_times = 5
66 | for i in range(0, sample_times):
67 | self._serial.reset_input_buffer()
68 |
69 | cmd = "iot_tests test 12 1"
70 | self._serial.write('\r\n'.encode('utf-8'))
71 |
72 | self._serial.write(cmd.encode('utf-8'))
73 |
74 | self._serial.write('\r\n'.encode('utf-8'))
75 |
76 | res = self._serial.read_until(terminator=serial.to_bytes([ord(c) for c in 'Ignored '])).decode('utf-8')
77 | # print(res)
78 | temp = []
79 | # Extract temperature readings from all of on board sensors.
80 | for x in res.split('\n'):
81 | # Look for the line with ADC reading.
82 | if x.find('TEST(TEST_IOT_TSENSOR, AFQP_IotTsensorTemp)') != -1:
83 | for s in x.split():
84 | if s.isdigit():
85 | temp.append(int(s))
86 |
87 | temp_list.append(temp)
88 | # Wait serial to flush out.
89 | sleep(0.2)
90 |
91 | # Get reference temperature.
92 | self.run_shell_script(" ".join([self.shell_script, self._ip, self._login, self._pwd]))
93 | fp = open(self.rpi_output_file)
94 | line = fp.readline()
95 | fp.close()
96 |
97 | try:
98 | ref_temp = ref_temp + float(line)
99 | except:
100 | print("Failed to get ref temp")
101 | return 'Fail'
102 |
103 | avg_temp = [sum([_list[i] for _list in temp_list]) / len(temp_list) for i in range(len(temp_list[0]))]
104 | ref_temp = ref_temp / sample_times
105 |
106 | if len(temp) == 0:
107 | print("Failed to get temp from DUT.")
108 | return 'Fail'
109 |
110 | for temp in avg_temp:
111 | if abs(temp / 1000 - ref_temp) > 5:
112 | print("DUT temp:", temp / 1000, "Ref temp:", ref_temp)
113 | self.clean()
114 | return 'Fail'
115 |
116 | # print(avg_temp)
117 | self.clean()
118 | return 'Pass'
119 |
120 |
121 | # unit test
122 | if __name__ == "__main__":
123 | parser = argparse.ArgumentParser()
124 |
125 | parser.add_argument('-i', '--ip', nargs=1, help='ip address of rpi')
126 | parser.add_argument('-l', '--login_name', nargs=1, help='login name of rpi')
127 | parser.add_argument('-s', '--password', nargs=1, help='password of rpi')
128 | parser.add_argument('-p', '--port', nargs=1, help='serial port of connected platform')
129 |
130 | args = parser.parse_args()
131 | print(args.port[0])
132 | try:
133 | serial_port = serial.Serial(port=args.port[0], timeout=5, baudrate=115200)
134 | except Exception as e:
135 | print(e)
136 | exit()
137 |
138 | rpi_ip = args.ip[0]
139 | rpi_login = args.login_name[0]
140 | rpi_pwd = args.password[0]
141 |
142 | with open(scriptdir + '/test_result.csv', 'w', newline='') as csvfile:
143 | field_name = ['test name', 'test result']
144 | writer = csv.DictWriter(csvfile, fieldnames=field_name)
145 | writer.writeheader()
146 | t_handler = TestTsensorAssisted(serial_port, rpi_ip, rpi_login, rpi_pwd, writer)
147 | t_handler.auto_run()
148 |
149 | serial_port.close()
150 |
--------------------------------------------------------------------------------
/test/test_scripts/uart/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/aws/common-io-basic/4cc5c90df9d70dd6cb86ec73736fdcbe6bfaec16/test/test_scripts/uart/__init__.py
--------------------------------------------------------------------------------
/test/test_scripts/uart/test_iot_runonPI_uart.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | # FreeRTOS Common IO V0.1.2
3 | # Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 | #
5 | # Permission is hereby granted, free of charge, to any person obtaining a copy
6 | # of this software and associated documentation files (the "Software"), to deal
7 | # in the Software without restriction, including without limitation the rights
8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | # copies of the Software, and to permit persons to whom the Software is
10 | #
11 | # The above copyright notice and this permission notice shall be included in
12 | # all copies or substantial portions of the Software.
13 | #
14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 | # SOFTWARE.
21 | #
22 | # http://aws.amazon.com/freertos
23 | # http://www.FreeRTOS.org
24 |
25 |
26 |
27 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
28 | IP=$1
29 | shift
30 | LOGINID=$1
31 | shift
32 | PASSWD=$1
33 | shift
34 |
35 | if [ "$1" == "-p" ]; then
36 | #Secure copy the test_iot_uart_rp3.py from Host to RP3
37 | sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} "mkdir -p /home/pi/Tests"
38 | sshpass -p ${PASSWD} scp ${DIR}/test_iot_uart_rp3.py ${LOGINID}@${IP}:/home/pi/Tests
39 | elif [ "$1" == "-c" ]; then
40 | sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} "rm /home/pi/Tests/uart_res.txt"
41 | else
42 | sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} "python3 /home/pi/Tests/test_iot_uart_rp3.py $1 > /home/pi/Tests/uart_res.txt"
43 | #Copy back result
44 | sshpass -p ${PASSWD} scp ${LOGINID}@${IP}:/home/pi/Tests/uart_res.txt ${DIR}
45 | fi
46 |
--------------------------------------------------------------------------------
/test/test_scripts/uart/test_iot_uart_rp3.py:
--------------------------------------------------------------------------------
1 | # FreeRTOS Common IO V0.1.2
2 | # Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 | #
4 | # Permission is hereby granted, free of charge, to any person obtaining a copy
5 | # of this software and associated documentation files (the "Software"), to deal
6 | # in the Software without restriction, including without limitation the rights
7 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 | # copies of the Software, and to permit persons to whom the Software is
9 | #
10 | # The above copyright notice and this permission notice shall be included in
11 | # all copies or substantial portions of the Software.
12 | #
13 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 | # SOFTWARE.
20 | #
21 | # http://aws.amazon.com/freertos
22 | # http://www.FreeRTOS.org
23 |
24 | import argparse
25 | import serial
26 | import time
27 | import re
28 | import socket
29 |
30 | HOST = ''
31 | PORT = 50007
32 |
33 | # open GPIO pins UART on PI. Make sure that you have enabled the PI in raspi-config.
34 | serialport = serial.Serial(
35 | port="/dev/serial0",
36 | baudrate=115200,
37 | parity=serial.PARITY_NONE,
38 | stopbits=serial.STOPBITS_ONE,
39 | bytesize=serial.EIGHTBITS,
40 | timeout=10,
41 | )
42 |
43 |
44 | def write_async(s):
45 | print("write_async")
46 | # Notify host rpi is ready.
47 | conn, addr = s.accept()
48 | # Read from UART until '\n' line ending is found
49 | rcv = serialport.read_until()
50 | print(str(rcv))
51 |
52 |
53 | def write_read_sync(s):
54 | print("write_read_sync")
55 | # Notify host rpi is ready.
56 | conn, addr = s.accept()
57 | # Read from UART until '\n' line ending is found
58 | rcv = serialport.read_until()
59 | rcv_str = str(repr(rcv))
60 | print(rcv_str)
61 | # Echo message back to UART
62 | serialport.write(rcv)
63 |
64 |
65 | def baud_change_test(s):
66 | print("baud_change_test")
67 | # Pattern to find baudrate to switch to. The new baudrate for tests are signaled by DUT
68 | baud_pattern = re.compile(r"Baudrate:\s(\d+)")
69 |
70 | # Notify host rpi is ready.
71 | conn, addr = s.accept()
72 | for i in range(4):
73 | # Read from UART until '\n' line ending is found
74 | rcv = serialport.read_until()
75 | rcv_str = str(repr(rcv))
76 | baudrate = baud_pattern.search(rcv_str)
77 | # Last message from UART was to switch to a different baudrate
78 | if baudrate:
79 | # switch RPI UART baudrate to baudrate indicated by DUT
80 | serialport.baudrate = baudrate.group(1)
81 | else:
82 | # If message was not signaling a new baudrate, the DUT sent a message with the intention of receiving an echo back
83 | serialport.write(rcv)
84 | print(rcv_str)
85 |
86 |
87 | if __name__ == "__main__":
88 |
89 | parser = argparse.ArgumentParser("default is input test")
90 |
91 | parser.add_argument(
92 | "d",
93 | nargs="+",
94 | type=int,
95 | default=0,
96 | help="select an assisted UART test: 1 for WriteReadSync, 2 for BaudChange, 3 for WriteAsync",
97 | )
98 |
99 | args = parser.parse_args()
100 | socket.setdefaulttimeout(5)
101 |
102 | # Use socket to signal RPI is ready
103 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
104 | s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
105 | s.bind((HOST, PORT))
106 | s.listen(1)
107 |
108 | if args.d[0] == 1:
109 | write_read_sync(s)
110 | elif args.d[0] == 2:
111 | baud_change_test(s)
112 | elif args.d[0] == 3:
113 | write_async(s)
114 |
115 | s.close()
116 |
--------------------------------------------------------------------------------
/test/test_scripts/uart/test_iot_uart_test.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # FreeRTOS Common IO V0.1.2
3 | # Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 | #
5 | # Permission is hereby granted, free of charge, to any person obtaining a copy
6 | # of this software and associated documentation files (the "Software"), to deal
7 | # in the Software without restriction, including without limitation the rights
8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | # copies of the Software, and to permit persons to whom the Software is
10 | #
11 | # The above copyright notice and this permission notice shall be included in
12 | # all copies or substantial portions of the Software.
13 | #
14 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20 | # SOFTWARE.
21 | #
22 | # http://aws.amazon.com/freertos
23 | # http://www.FreeRTOS.org
24 |
25 |
26 | import serial
27 | import csv
28 | import argparse
29 | import os, sys
30 | import re
31 | import socket
32 | from time import sleep
33 | import threading
34 |
35 | scriptdir = os.path.dirname(os.path.realpath(__file__))
36 | parentdir = os.path.dirname(scriptdir)
37 | if parentdir not in sys.path:
38 | print("Script Dir: %s" % scriptdir)
39 | print("Parent Dir: %s" % parentdir)
40 | sys.path.append(parentdir)
41 | from test_iot_test_template import test_template
42 |
43 |
44 | class TestUartAssisted(test_template):
45 | """
46 | Test class for uart tests.
47 | """
48 |
49 | rpi_output_file = "%s/uart_res.txt" % scriptdir
50 |
51 | def __init__(self, serial, ip, login, pwd, csv_handler):
52 | self._func_list = [self.test_IotUartWriteReadAsync,
53 | self.test_IotUartBaudChange,
54 | self.test_IotUartWriteAsync
55 | ]
56 |
57 | self._serial = serial
58 | self._ip = ip
59 | self._login = login
60 | self._pwd = pwd
61 | self._cr = csv_handler
62 |
63 | shell_script = "%s/test_iot_runonPI_uart.sh" % scriptdir
64 | port = 50007
65 |
66 | def test_IotUartWriteReadAsync(self):
67 | """
68 | Test body of uart write then read async test. Return pass if expected message is recieved
69 | :return: 'Pass' or 'Fail'
70 | """
71 | dut_result = None
72 | pi_result = None
73 | dut_res_pattern = re.compile(r"AFQP_AssistedIotUARTWriteReadSync.*?PASS")
74 | pi_regex = re.compile(r"UART\sread-write")
75 |
76 | t_shell = threading.Thread(target=self.run_shell_script,
77 | args=(" ".join([self.shell_script, self._ip, self._login, self._pwd, '1']),))
78 | t_shell.start()
79 |
80 | # IMPORTANT: without this, the socket won't connect on mac; reason not known.
81 | sleep(1)
82 |
83 | # Create a tcp type socket with AF_INET address family.
84 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
85 | time_out = 10
86 |
87 | # Wait until connection with the process on rpi is established.
88 | while s.connect_ex((self._ip, self.port)) != 0 and time_out > 0:
89 | time_out -= 1
90 | sleep(1)
91 | if time_out == 0:
92 | print("Socket connection cannot be established")
93 | s.close()
94 | return "Fail"
95 |
96 | print("connnected successfully")
97 |
98 | self._serial.reset_input_buffer()
99 |
100 | cmd = "iot_tests test 1 1"
101 | self._serial.write("\r\n".encode("utf-8"))
102 | self._serial.write(cmd.encode("utf-8"))
103 | self._serial.write("\r\n".encode("utf-8"))
104 |
105 | dut_res = str(self._serial.read_until(terminator=serial.to_bytes([ord(c) for c in 'Ignored '])))
106 | dut_result = dut_res_pattern.search(dut_res)
107 | print(dut_res)
108 | t_shell.join()
109 |
110 | with open(self.rpi_output_file, "r") as f:
111 | rpi_output = str(f.read())
112 | print(rpi_output)
113 | pi_result = pi_regex.search(rpi_output)
114 |
115 | s.send(b'E')
116 | s.close()
117 | self.clean()
118 |
119 | return "Pass" if pi_result and dut_result else "Fail"
120 |
121 | def test_IotUartBaudChange(self):
122 | """
123 | Test body of uart baud change test. Return pass if expected messages are recieved
124 | :return: 'Pass' or 'Fail'
125 | """
126 | result_matches = []
127 | dut_result = None
128 | dut_res_pattern = re.compile(r"AFQP_AssistedIotUARTBaudChange.*?PASS")
129 | pi_res_pattern = re.compile(r"UART\sread-write")
130 |
131 | t_shell = threading.Thread(target=self.run_shell_script,
132 | args=(" ".join([self.shell_script, self._ip, self._login, self._pwd, '2']),))
133 | t_shell.start()
134 |
135 | # IMPORTANT: without this, the socket won't connect on mac; reason not known.
136 | sleep(1)
137 |
138 | # Create a tcp type socket with AF_INET address family.
139 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
140 | time_out = 10
141 | # Wait until connection with the process on rpi is established.
142 | while s.connect_ex((self._ip, self.port)) != 0 and time_out > 0:
143 | time_out -= 1
144 | sleep(1)
145 | if time_out == 0:
146 | print("Socket connection cannot be established")
147 | s.close()
148 | return "Fail"
149 |
150 | print("connnected successfully")
151 |
152 | self._serial.reset_input_buffer()
153 |
154 | cmd = "iot_tests test 1 2"
155 | self._serial.write("\r\n".encode("utf-8"))
156 | self._serial.write(cmd.encode("utf-8"))
157 | self._serial.write("\r\n".encode("utf-8"))
158 |
159 | dut_res = str(self._serial.read_until(terminator=serial.to_bytes([ord(c) for c in 'Ignored '])))
160 | dut_result = dut_res_pattern.search(dut_res)
161 |
162 | print(dut_res)
163 | t_shell.join()
164 |
165 | with open(self.rpi_output_file, "r") as f:
166 | result_matches = pi_res_pattern.findall(str(f.read()))
167 | s.send(b'E')
168 | s.close()
169 | self.clean()
170 |
171 | return "Pass" if len(result_matches) >= 2 and dut_result else "Fail"
172 |
173 | def test_IotUartWriteAsync(self):
174 | """
175 | Test body of uart write async test. Return pass if expected message is received
176 | :return: 'Pass' or 'Fail'
177 | """
178 | pi_result = None
179 | dut_result = None
180 | dut_res_pattern = re.compile(r"AFQP_AssistedIotUARTWriteAsync.*?PASS")
181 | # 199 corresponds to the config testIotUART_BUFFER_LENGTH_LARGE - 1 on the DUT
182 | pi_res_pattern = re.compile(r"(?:\\xaa){199}")
183 |
184 | t_shell = threading.Thread(target=self.run_shell_script,
185 | args=(" ".join([self.shell_script, self._ip, self._login, self._pwd, '3']),))
186 | t_shell.start()
187 |
188 | # IMPORTANT: without this, the socket won't connect on mac; reason not known.
189 | sleep(1)
190 |
191 | # Create a tcp type socket with AF_INET address family.
192 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
193 | time_out = 10
194 |
195 | # Wait until connection with the process on rpi is established.
196 | while s.connect_ex((self._ip, self.port)) != 0 and time_out > 0:
197 | time_out -= 1
198 | sleep(1)
199 | if time_out == 0:
200 | print("Socket connection cannot be established")
201 | s.close()
202 | return "Fail"
203 |
204 | print("connnected successfully")
205 |
206 | self._serial.reset_input_buffer()
207 |
208 | cmd = "iot_tests test 1 3"
209 | self._serial.write("\r\n".encode("utf-8"))
210 | self._serial.write(cmd.encode("utf-8"))
211 | self._serial.write("\r\n".encode("utf-8"))
212 |
213 | dut_res = str(self._serial.read_until(terminator=serial.to_bytes([ord(c) for c in 'Ignored '])))
214 | dut_result = dut_res_pattern.search(dut_res)
215 | print(dut_res)
216 | t_shell.join()
217 |
218 | with open(self.rpi_output_file, "r") as f:
219 | rpi_output = str(f.read())
220 | print(rpi_output)
221 | pi_result = pi_res_pattern.search(rpi_output)
222 |
223 | s.send(b'E')
224 | s.close()
225 | self.clean()
226 |
227 | return "Pass" if pi_result and dut_result else "Fail"
228 |
229 |
230 | # unit test
231 | if __name__ == "__main__":
232 | parser = argparse.ArgumentParser()
233 |
234 | parser.add_argument('-i', '--ip', nargs=1, help='ip address of rpi')
235 | parser.add_argument('-l', '--login_name', nargs=1, help='login name of rpi')
236 | parser.add_argument('-s', '--password', nargs=1, help='password of rpi')
237 | parser.add_argument('-p', '--port', nargs=1, help='serial port of connected platform')
238 |
239 | args = parser.parse_args()
240 |
241 | try:
242 | serial_port = serial.Serial(port=args.port[0], baudrate=115200, timeout=20)
243 | except Exception as e:
244 | print(e)
245 | exit()
246 |
247 | rpi_ip = args.ip[0]
248 | rpi_login = args.login_name[0]
249 | rpi_pwd = args.password[0]
250 |
251 | with open("test_result.csv", "w", newline="") as csvfile:
252 | field_name = ["test name", "test result"]
253 | writer = csv.DictWriter(csvfile, fieldnames=field_name)
254 | writer.writeheader()
255 | t_handler = TestUartAssisted(serial_port, rpi_ip, rpi_login, rpi_pwd, writer)
256 | t_handler.auto_run()
257 |
258 | serial_port.close()
259 |
--------------------------------------------------------------------------------
/test/test_scripts/usb_device/test_iot_usb_device_test.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # FreeRTOS Common IO V0.1.2
3 | # Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4 | #
5 | # Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | # this software and associated documentation files (the "Software"), to deal in
7 | # the Software without restriction, including without limitation the rights to
8 | # use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | # the Software, and to permit persons to whom the Software is furnished to do so,
10 | # subject to the following conditions:
11 | #
12 | # The above copyright notice and this permission notice shall be included in all
13 | # copies or substantial portions of the Software.
14 | #
15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 | # FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 | # COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 | # IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 | # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 | #
22 | # http://aws.amazon.com/freertos
23 | # http://www.FreeRTOS.org
24 |
25 | import serial
26 | from time import sleep
27 | import csv
28 | import os, sys
29 | import argparse
30 | import usb.core
31 | import usb.util
32 | import re
33 | import threading
34 | import random
35 |
36 | scriptdir = os.path.dirname(os.path.realpath(__file__))
37 | parentdir = os.path.dirname(scriptdir)
38 | if parentdir not in sys.path:
39 | print("Script Dir: %s" % scriptdir)
40 | print("Parent Dir: %s" % parentdir)
41 | sys.path.append(parentdir)
42 | from test_iot_test_template import test_template
43 |
44 |
45 | class TestUSBDeviceAssisted(test_template):
46 | """
47 | Test class for usb device tests.
48 | """
49 |
50 | def __init__(self, serial, ip, login, pwd, csv_handler):
51 | self._func_list = [self.test_IotUsbDeviceHidAttachAssisted,
52 | self.test_IotUsbDeviceWriteSyncAssisted,
53 | self.test_IotUsbDeviceWriteAsyncAssisted,
54 | self.test_IotUsbDeviceReadAsyncAssisted,
55 | self.test_IotUsbDeviceReadSyncAssisted,
56 | self.test_IotUsbDeviceHidDetachAssisted
57 | ]
58 |
59 | self._serial = serial
60 | self._ip = ip
61 | self._login = login
62 | self._pwd = pwd
63 | self._cr = csv_handler
64 | self.vid = self.pid = None
65 | self.reattach = None
66 | self.host_bytes = []
67 | self.dev = []
68 | self.epo = self.epi = None
69 |
70 | def test_IotUsbDeviceHidAttachAssisted(self):
71 | """
72 | Test body for attach test.
73 | :return:
74 | """
75 | self._serial.reset_input_buffer()
76 | self._serial.write('\r\n'.encode('utf-8'))
77 | self._serial.write("iot_tests test 17 11".encode('utf-8'))
78 | self._serial.write('\r\n'.encode('utf-8'))
79 | res = self._serial.read_until(terminator=serial.to_bytes([ord(c) for c in 'Ignored '])).decode('utf-8')
80 |
81 | # Grab vendor id and product id.
82 | self.vid, self.pid = map(lambda x: int(x, 16), re.findall(r'[vid|pid]:(\w+)', res))
83 |
84 | sleep(5)
85 | # find usb device
86 | self.dev = usb.core.find(idVendor=self.vid, idProduct=self.pid)
87 |
88 | if self.dev is None:
89 | raise ValueError('Device not found')
90 |
91 | print(self.dev)
92 |
93 | if self.dev.is_kernel_driver_active(0):
94 | self.reattach = True
95 | self.dev.detach_kernel_driver(0)
96 |
97 | # set the active configuration. With no arguments, the first
98 | # configuration will be the active one
99 | self.dev.set_configuration()
100 |
101 | # get an endpoint instance
102 | cfg = self.dev.get_active_configuration()
103 | intf = usb.util.find_descriptor(cfg, bInterfaceClass=3)
104 |
105 | self.epo = usb.util.find_descriptor(
106 | intf,
107 | # match the first OUT endpoint
108 | custom_match= \
109 | lambda e: \
110 | usb.util.endpoint_direction(e.bEndpointAddress) == \
111 | usb.util.ENDPOINT_OUT)
112 | self.epi = usb.util.find_descriptor(
113 | intf,
114 | # match the first IN endpoint
115 | custom_match= \
116 | lambda e: \
117 | usb.util.endpoint_direction(e.bEndpointAddress) == \
118 | usb.util.ENDPOINT_IN)
119 |
120 | assert self.epo and self.epi is not None
121 |
122 | return 'Pass'
123 |
124 | def usb_device_interrupt_type(self, cmd, host_func):
125 | """Test body for interrupt type tests."""
126 | t_host = threading.Thread(target=host_func)
127 | t_host.start()
128 | sleep(3)
129 | self._serial.reset_input_buffer()
130 | self._serial.write('\r\n'.encode('utf-8'))
131 | self._serial.write(cmd.encode('utf-8'))
132 | self._serial.write('\r\n'.encode('utf-8'))
133 | sleep(1)
134 | res = self._serial.read_until(terminator=serial.to_bytes([ord(c) for c in 'Ignored '])).decode('utf-8')
135 | print(repr(res))
136 | t_host.join()
137 |
138 | assert res.find('Ignored ') is not -1
139 |
140 | dut_bytes = []
141 | for x in re.sub('\r', '', res).split('\n'):
142 | if x.find('IGNORE') != -1:
143 | dut_bytes = [int(s, 16) for s in x.split(',') if len(s) == 2]
144 | break
145 |
146 | if self.compare_host_dut_result(self.host_bytes, dut_bytes) == -1:
147 | print(repr(res))
148 | return "Fail"
149 |
150 | return "Pass"
151 |
152 | def host_read_thread(self):
153 | """
154 | Host read thread.
155 | :return:
156 | """
157 | self.host_bytes = []
158 | self.host_bytes = list(self.epi.read(16, timeout=10000))
159 | # print(self.r_bytes)
160 |
161 | def test_IotUsbDeviceWriteSyncAssisted(self):
162 | return self.usb_device_interrupt_type("iot_tests test 17 14", self.host_read_thread)
163 |
164 | def test_IotUsbDeviceWriteAsyncAssisted(self):
165 | return self.usb_device_interrupt_type("iot_tests test 17 12", self.host_read_thread)
166 |
167 | def host_write_thread(self):
168 | """
169 | Host write thread.
170 | :return:
171 | """
172 | self.host_bytes = [random.randrange(0, 128) for i in range(0, 16)]
173 | self.epo.write(self.host_bytes, 10000)
174 | # print(self.w_bytes)
175 |
176 | def test_IotUsbDeviceReadAsyncAssisted(self):
177 | return self.usb_device_interrupt_type("iot_tests test 17 13", self.host_write_thread)
178 |
179 | def test_IotUsbDeviceReadSyncAssisted(self):
180 | return self.usb_device_interrupt_type("iot_tests test 17 15", self.host_write_thread)
181 |
182 | def test_IotUsbDeviceHidDetachAssisted(self):
183 | """
184 | Test body for detach test.
185 | :return:
186 | """
187 | # This is needed to release interface, otherwise attach_kernel_driver fails due to "Resource busy"
188 | usb.util.dispose_resources(self.dev)
189 | # It may raise USBError if there's e.g. no kernel driver loaded at all
190 | if self.reattach:
191 | self.dev.attach_kernel_driver(0)
192 |
193 | self._serial.reset_input_buffer()
194 | self._serial.write('\r\n'.encode('utf-8'))
195 | self._serial.write("iot_tests test 17 2".encode('utf-8'))
196 | self._serial.write('\r\n'.encode('utf-8'))
197 | res = self._serial.read_until(terminator=serial.to_bytes([ord(c) for c in 'Ignored '])).decode('utf-8')
198 | print(repr(res))
199 |
200 | assert res.find('Ignored ') is not -1
201 | sleep(5)
202 | # Make sure device is detached.
203 | self.dev = usb.core.find(idVendor=self.vid, idProduct=self.pid)
204 | # print(self.dev)
205 |
206 | if self.dev is None:
207 | return "Pass"
208 |
209 | return "Fail"
210 |
211 |
212 | # unit test
213 | if __name__ == "__main__":
214 | parser = argparse.ArgumentParser()
215 |
216 | parser.add_argument('-i', '--ip', nargs=1, default=[''], help='ip address of rpi')
217 | parser.add_argument('-l', '--login_name', nargs=1, default=[''], help='login name of rpi')
218 | parser.add_argument('-s', '--password', nargs=1, default=[''], help='password of rpi')
219 | parser.add_argument('-p', '--port', nargs=1, default=[''], help='serial port of connected platform')
220 |
221 | args = parser.parse_args()
222 |
223 | try:
224 | serial_port = serial.Serial(port=args.port[0], baudrate=115200, timeout=5)
225 | except Exception as e:
226 | print(e)
227 | exit()
228 |
229 | rpi_ip = args.ip[0]
230 | rpi_login = args.login_name[0]
231 | rpi_pwd = args.password[0]
232 |
233 | with open(scriptdir + '/test_result.csv', 'w', newline='') as csvfile:
234 | field_name = ['test name', 'test result']
235 | writer = csv.DictWriter(csvfile, fieldnames=field_name)
236 | writer.writeheader()
237 | t_handler = TestUSBDeviceAssisted(serial_port, rpi_ip, rpi_login, rpi_pwd, writer)
238 | t_handler.auto_run()
239 |
240 | serial_port.close()
241 |
--------------------------------------------------------------------------------